在 Java 代码中对 Kerberos 主体进行身份验证
转载请注明出处:http://www.cnblogs.com/xiaodf/
本文举例说明如何使用 org.apache.hadoop.security.UserGroupInformation 类在 Java 应用程序中对 Kerberos 主体进行身份验证。
以下代码段验证 user3主体(使用 user3.keytab文件):
org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration(); conf.set("hadoop.security.authentication", "Kerberos"); UserGroupInformation.setConfiguration(conf); UserGroupInformation.loginUserFromKeytab(principal,keytab); System.out.println("getting connection"); System.out.println("current user: "+UserGroupInformation.getCurrentUser()); System.out.println("login user: "+UserGroupInformation.getLoginUser());
示例代码实现的功能是:验证用户user3的keytab后,通过jdbc查询某张表的数据打印到控制台。
运行脚本hive.sh如下:
spark-submit --class iie.hadoop.permission.hive2 --master local /home/xdf/hive.jar user3 user3.keytab "select * from test1.table1"
程序完整代码如下:
import java.sql.*; import org.apache.hadoop.security.UserGroupInformation; public class hive2 { public static void main(String args[]) { String principal = args[0]; String keytab = args[1]; String sql = args[2]; try { org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration(); conf.set("hadoop.security.authentication", "Kerberos"); UserGroupInformation.setConfiguration(conf); UserGroupInformation.loginUserFromKeytab(principal,keytab); System.out.println("getting connection"); System.out.println("current user: "+UserGroupInformation.getCurrentUser()); System.out.println("login user: "+UserGroupInformation.getLoginUser()); Class.forName("org.apache.hive.jdbc.HiveDriver"); Connection con = DriverManager .getConnection("jdbc:hive2://t163:10000/;principal=hive/t163@HADOOP.COM"); System.out.println("got connection"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql);// executeQuery会返回结果的集合,否则返回空值 System.out.println("打印输出结果:"); while (rs.next()) { System.out.println(rs.getString(1));// 入如果返回的是int类型可以用getInt() } con.close(); } catch (Exception e) { e.printStackTrace(); } } }
运行结果如下:
[root@t161 xdf]# sh hive2.sh 16/10/27 15:12:15 INFO security.UserGroupInformation: Login successful for user user3 using keytab file user3.keytab getting connection current user: user3@HADOOP.COM (auth:KERBEROS) login user: user3@HADOOP.COM (auth:KERBEROS) 16/10/27 15:12:15 INFO jdbc.Utils: Supplied authorities: t163:10000 16/10/27 15:12:15 INFO jdbc.Utils: Resolved authority: t163:10000 got connection 打印输出结果: 1