MAPREDUCE服务 MRS-配置HDFS应用安全认证:安全认证代码
安全认证代码
目前样例代码统一调用LoginUtil类进行安全认证。
在HDFS样例工程代码中,不同的样例工程,使用的认证代码不同,包括基本安全认证和带ZooKeeper认证。
- 基本安全认证:
com.huawei.bigdata.hdfs.examples包的HdfsExample类样例程序不需要访问HBase或ZooKeeper,所以使用基本的安全认证代码即可。示例代码如下:
... private static final String PATH_TO_HDFS_SITE_XML = HdfsExample.class.getClassLoader().getResource("hdfs-site.xml").getPath(); private static final String PATH_TO_CORE_SITE_XML = HdfsExample.class.getClassLoader().getResource("core-site.xml").getPath(); private static final String PRNCIPAL_NAME = "hdfsDeveloper"; private static final String PATH_TO_KEYTAB = HdfsExample.class.getClassLoader().getResource("user.keytab").getPath(); private static final String PATH_TO_KRB5_CONF = HdfsExample.class.getClassLoader().getResource("krb5.conf").getPath(); private static Configuration conf = null; } ... private static void authentication() throws IOException { // security mode if ("kerberos".equalsIgnoreCase(conf.get("hadoop.security.authentication"))) { System.setProperty("java.security.krb5.conf", PATH_TO_KRB5_CONF); LoginUtil.login(PRNCIPAL_NAME, PATH_TO_KEYTAB, PATH_TO_KRB5_CONF, conf); } }
- 带ZooKeeper认证:
com.huawei.bigdata.hdfs.examples包的“ColocationExample”类样例程序不仅需要基础安全认证,还需要添加ZooKeeper服务端Principal才能完成安全认证。示例代码如下:
... private static final String ZOOKEEPER_SERVER_PRINCIPAL_KEY = "zookeeper.server.principal"; private static final String PRINCIPAL = "username.client.kerberos.principal"; private static final String KEYTAB = "username.client.keytab.file"; private static final String PRNCIPAL_NAME = "hdfsDeveloper"; private static final String LOG IN_CONTEXT_NAME = "Client"; private static final String PATH_TO_KEYTAB = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "user.keytab"; private static final String PATH_TO_KRB5_CONF = ColocationExample.class.getClassLoader().getResource("krb5.conf") .getPath(); private static String zookeeperDefaultServerPrincipal = null; private static Configuration conf = new Configuration(); private static DFSColocationAdmin dfsAdmin; private static DFSColocationClient dfs; private static void init() throws IOException { LoginUtil.login(PRNCIPAL_NAME, PATH_TO_KEYTAB, PATH_TO_KRB5_CONF, conf); LoginUtil.setJaasConf(LOGIN_CONTEXT_NAME, PRNCIPAL_NAME, PATH_TO_KEYTAB); zookeeperDefaultServerPrincipal = "zookeeper/hadoop." + KerberosUtil.getKrb5DomainRealm().toLowerCase(); LoginUtil.setZookeeperServerPrincipal(ZOOKEEPER_SERVER_PRINCIPAL_KEY, zookeeperDefaultServerPrincipal); } ...