【kerberos】使用keytab文件,kerberos认证工具类 scala版本

scala 复制代码
import org.apache.commons.lang3.StringUtils
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.security.{SecurityUtil, UserGroupInformation}
import org.apache.kerby.kerberos.kerb.keytab.Keytab
import org.slf4j.Logger
import sun.security.provider.ConfigFile

import java.io.File
import java.net.{URI, URL}
import java.nio.file.{Files, Paths}
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scala.io.Source

case class KerberosConf(var principal: String,var keytab: String,var krb5conf: String="/etc/krb5.conf")


object KerberosUtils {
  val LOG: Logger = org.slf4j.LoggerFactory.getLogger(KerberosUtils.getClass)

  val JAVA_SECURITY_KRB5_CONF = "java.security.krb5.conf"
  val JAVA_SECURITY_AUTH_LOGIN_CONFIG = "java.security.auth.login.config"

  def loginKerberos(krb5Principal: String, krb5KeytabPath: String, krb5ConfPath: String, hadoopConf: Configuration): Boolean = {
    val authType = hadoopConf.get("hadoop.security.authentication")
    if (!"kerberos".equalsIgnoreCase(authType)) {
      LOG.error(s"kerberos utils get hadoop authentication type [${authType}] ,not kerberos!")
    } else {
      LOG.info(s"kerberos utils get hadoop authentication type [${authType}]!")
    }

    UserGroupInformation.setConfiguration(hadoopConf)
    System.setProperty(JAVA_SECURITY_KRB5_CONF, krb5ConfPath)
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false")

    // 1. using SecurityUtil
    //    hadoopConf.set(SPARK_KERBEROS_PRINCIPAL,krb5Principal)
    //    hadoopConf.set(SPARK_KERBEROS_KEYTAB,krb5KeytabPath)
    //    SecurityUtil.login(hadoopConf,SPARK_KERBEROS_KEYTAB,SPARK_KERBEROS_PRINCIPAL);

    // 2. using UserGroupInformation
    UserGroupInformation.loginUserFromKeytab(krb5Principal, krb5KeytabPath)
    val user = UserGroupInformation.getLoginUser
    if (user.getAuthenticationMethod == UserGroupInformation.AuthenticationMethod.KERBEROS) {
      val usnm: String = user.getShortUserName
      LOG.info(s"kerberos utils login success, curr user: ${usnm}")
      true
    } else {
      LOG.info("kerberos utils login failed")
      false
    }

  }

  def loginKerberos(krb5Principal: String, krb5KeytabPath: String, krb5ConfPath: String): Boolean = {
    val hadoopConf = ConfigUtils.getHadoopConfig
    hadoopConf.get("hadoop.security.authentication")
    loginKerberos(krb5Principal, krb5KeytabPath, krb5ConfPath, hadoopConf)
  }

  def loginKerberos(kerberosConf: KerberosConf): Boolean = {
    loginKerberos(kerberosConf.principal, kerberosConf.keytab, kerberosConf.krb5conf)
  }

  def loginKerberos(krb5Principal: String, krb5KeytabPath: String, krb5ConfPath: String, hadoopConfDir: String): Boolean = {
    ConfigUtils.setHadoopConfDir(hadoopConfDir)
    loginKerberos(krb5Principal, krb5KeytabPath, krb5ConfPath)
  }

  def loginKerberos(): Boolean = {
    var principal: String = null
    var keytabPath: String = null
    var krb5ConfPath: String = null
    val classPath: URL = this.getClass.getResource("/")
    val classPathObj = Paths.get(classPath.toURI)
    var keytabPathList = Files.list(classPathObj).iterator().asScala.toList
    keytabPathList = keytabPathList.filter(p => p.toString.toLowerCase().endsWith(".keytab")).toList
    val krb5ConfPathList = keytabPathList.filter(p => p.toString.toLowerCase().endsWith("krb5.conf")).toList
    if (keytabPathList.nonEmpty) {
      val ktPath = keytabPathList.get(0)
      val absPath = ktPath.toAbsolutePath
      val keytab = Keytab.loadKeytab(new File(absPath.toString))
      val pri = keytab.getPrincipals.get(0).getName
      if (StringUtils.isNotEmpty(pri)) {
        principal = pri
        keytabPath = ktPath.toString
      }
    }
    if (krb5ConfPathList.nonEmpty) {
      val confPath = krb5ConfPathList.get(0)
      krb5ConfPath = confPath.toAbsolutePath.toString
    }
    if (StringUtils.isNotEmpty(principal) && StringUtils.isNotEmpty(keytabPath) && StringUtils.isNotEmpty(krb5ConfPath)) {
      ConfigUtils.configHadoop()
      // ConfigUtils.configHive()
      val hadoopConf = ConfigUtils.hadoopConfiguration
      loginKerberos(principal, keytabPath, krb5ConfPath, hadoopConf)
    } else {
      false
    }
  }


  def getCurrLoginUser(): String = {
    var usnm: String = null
    val user = UserGroupInformation.getLoginUser
    if (user.getAuthenticationMethod == UserGroupInformation.AuthenticationMethod.KERBEROS) {
      usnm = user.getShortUserName
      LOG.debug(s"Kerberos curr login user: ${usnm}")
    }
    usnm
  }


  def parseKafkaJaasFile(path: String): KerberosConf = {
    val spi = new ConfigFile.Spi(new URI(path))
    val opts = spi.engineGetAppConfigurationEntry("KafkaClient").head.getOptions
    val principal: String = opts.get("principal").toString
    val keytab: String = opts.get("keyTab").toString
    KerberosConf(principal,keytab)
  }

}
相关推荐
starzy19905 天前
Structured Streaming 模块与编程模型:引擎内部到底由什么组成
大数据·hadoop·hdfs
AI源码6 天前
基于 Hadoop 和 Hive 的旅游景区数据的分析与可视化系统
hive·hadoop·旅游
starzy19906 天前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
演艺大赏8 天前
三个坑连环套:一次 NameNode 起不来,从 JournalNode 未格式化查到配置里多了个挂载点
大数据·hadoop
starzy19908 天前
Hadoop介绍总结:一张图理清组件、生态与版本
java·hadoop
starzy19909 天前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
演艺大赏9 天前
两个 NameNode 一起起不来以及Hadoop 3.3.2 里那个认不出自家 JournalNode 的 Servlet
大数据·hadoop
演艺大赏9 天前
RESTServer 起不来,日志只有一行:headerCacheSize 65536 exceeds maximum value of 65534
大数据·hadoop·hbase
starzy199010 天前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
starzy199011 天前
深入理解Scala柯里化函数:函数链式变换
开发语言·scala