001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.util;
019
020import java.io.IOException;
021import java.net.InetAddress;
022import org.apache.hadoop.conf.Configuration;
023import org.apache.hadoop.security.UserGroupInformation;
024import org.apache.yetus.audience.InterfaceAudience;
025import org.slf4j.Logger;
026import org.slf4j.LoggerFactory;
027
028@InterfaceAudience.Private
029/**
030 * Utility class for Kerberos authentication.
031 */
032public class KerberosUtils {
033  private static final Logger LOG = LoggerFactory.getLogger(KerberosUtils.class);
034
035  /**
036   * Logs in a user using Kerberos keytab and returns the UserGroupInformation (UGI) instance.
037   * @param conf     the configuration object
038   * @param username the username for which the keytab file and principal are configured.
039   * @return the UserGroupInformation instance for the logged-in user.
040   * @throws IOException If an I/O error occurs during login.
041   */
042  public static UserGroupInformation loginAndReturnUGI(Configuration conf, String username)
043    throws IOException {
044    String hostname = InetAddress.getLocalHost().getHostName();
045    String keyTabFileConfKey = "hbase." + username + ".keytab.file";
046    String keyTabFileLocation = conf.get(keyTabFileConfKey);
047    String principalConfKey = "hbase." + username + ".kerberos.principal";
048    String principal = org.apache.hadoop.security.SecurityUtil
049      .getServerPrincipal(conf.get(principalConfKey), hostname);
050    if (keyTabFileLocation == null || principal == null) {
051      LOG.warn(
052        "Principal or key tab file null for : " + principalConfKey + ", " + keyTabFileConfKey);
053    }
054    UserGroupInformation ugi =
055      UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keyTabFileLocation);
056    return ugi;
057  }
058}