【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)
  }

}
相关推荐
pale_moonlight1 天前
十、 Scala 应用实践 (上)
大数据·开发语言·scala
小坏讲微服务1 天前
SpringCloud整合Scala实现MybatisPlus实现业务增删改查
java·spring·spring cloud·scala·mybatis plus
今天没有盐2 天前
Scala Map集合完全指南:从入门到实战应用
后端·scala·编程语言
顧棟3 天前
HDFS元数据与auditlog结合Hive元数据统计分析
hive·hadoop·hdfs
z***89713 天前
【分布式】Hadoop完全分布式的搭建(零基础)
大数据·hadoop·分布式
Kevinyu_3 天前
责任链模式
java·hadoop·责任链模式
yumgpkpm3 天前
腾讯云TBDS与CDH迁移常见问题有哪些?建议由CDH迁移到CMP 7.13 平台(类Cloudera CDP,如华为鲲鹏 ARM 版)
hive·hadoop·zookeeper·flink·spark·kafka·hbase
BD_Marathon3 天前
sbt 编译打包 scala
开发语言·后端·scala
92744 天前
26 trait-多继承详解
scala
yumgpkpm4 天前
数据可视化AI、BI工具,开源适配 Cloudera CMP 7.3(或类 CDP 的 CMP 7.13 平台,如华为鲲鹏 ARM 版)值得推荐?
人工智能·hive·hadoop·信息可视化·kafka·开源·hbase