更新时间:2024-05-27 GMT+08:00
分享

准备认证机制代码

场景说明

在安全集群环境下,各个组件之间的相互通信不能够简单的互通,而需要在通信之前进行相互认证,以确保通信的安全性。HBase应用开发需要进行ZooKeeper和Kerberos安全认证。用于ZooKeeper认证的文件为“jaas.conf”,用于Kerberos安全认证文件为keytab文件和krb5.conf文件。具体使用方法在样例代码的“README.md”中会有详细说明。

安全认证主要采用代码认证方式。支持Oracle JAVA平台和IBM JAVA平台。

以下代码在“com.huawei.bigdata.hbase.examples”包的“TestMain”类中。

  • 代码认证
    try {
       init();
       login();
       } 
    catch (IOException e) {
       LOG.error("Failed to login because ", e);
       return;
    }
  • 初始化配置
    private static void init() throws IOException {
            // Default load from conf directory
            conf = HBaseConfiguration.create();
            //In Windows environment
            String userdir = TestMain.class.getClassLoader().getResource("conf").getPath() + File.separator;[1]
            //In Linux environment
            //String userdir = System.getProperty("user.dir") + File.separator + "conf" + File.separator;
            conf.addResource(new Path(userdir + "core-site.xml"), false);
            conf.addResource(new Path(userdir + "hdfs-site.xml"), false);
            conf.addResource(new Path(userdir + "hbase-site.xml"), false);
    }

    [1]userdir获取的是编译后资源路径下conf目录的路径。将初始化需要的配置文件“core-site.xml”、“hdfs-site.xml”、“hbase-site.xml”和用于安全认证的用户凭证文件放置到“src/main/resources”的目录下。

  • 安全登录

    请根据实际情况,修改“userName”为实际用户名,例如developuser

    在Windows环境下和Linux环境下请使用对应的路径获取方式。

    private static void login() throws IOException {
            if (User.isHBaseSecurityEnabled(conf)) {
                userName = "hbaseuser1";
               
                //In Windows environment
                String userdir = TestMain.class.getClassLoader().getResource("conf").getPath() + File.separator;
                //In Linux environment
                //String userdir = System.getProperty("user.dir") + File.separator + "conf" + File.separator;
     
                /*
                 * if need to connect zk, please provide jaas info about zk. of course,
                 * you can do it as below:
                 * System.setProperty("java.security.auth.login.config", confDirPath +
                 * "jaas.conf"); but the demo can help you more : Note: if this process
                 * will connect more than one zk cluster, the demo may be not proper. you
                 * can contact us for more help
                 */
                LoginUtil.setJaasConf(ZOOKEEPER_DEFAULT_LOGIN_CONTEXT_NAME, userName, userKeytabFile);
                LoginUtil.login(userName, userKeytabFile, krb5File, conf);
            }
    }
分享:

    相关文档

    相关产品