JAAS Authentication Example

例子程序来源于Java文档。

  1. 配置Kerberos的Server端,配置KDC(kdc.conf)和Server(krb5.conf)。
  2. 增加一个Principal,一个用于程序测试。
  3. 将JassAcn.java和Jaas.conf文件拷贝到一个文件夹。
  4. Javac编译JassAcn.java文件
  5. 用下面的命令执行class文件,替换成自己的配置
1
java -Djava.security.krb5.realm=HIGHGO.COM-Djava.security.krb5.kdc=hadooph.highgo.com-Djava.security.auth.login.config=jaas.conf JaasAcn
  1. 运行此class文件,提示输入Kerberosusername和Kerberos password,验证成功,打印Authentication succeeded!,验证失败,打印Authenticationfailed和失败原因。
  2. 也可将程序导入到Eclipse里运行,只要在运行时,在虚拟机参数里加入
    1
    2
    3
    -Djava.security.krb5.realm=HIGHGO.COM
    -Djava.security.krb5.kdc=hadooph.highgo.com
    -Djava.security.auth.login.config=jaas.conf

即可。调试什么的更方便。

Appendix

JaasAcn.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

import com.sun.security.auth.callback.TextCallbackHandler;

/**
* This JaasAcn application attempts to authenticate a user and reports whether
* ornot the authentication was successful.
*/
public class JaasAcn {
public static void main(String[] args) {
// Obtain a LoginContext,needed for authentication. Tell it
// to use the LoginModuleimplementation specified by the
// entry named"JaasSample" in the JAAS login configuration
// file and to also use thespecified CallbackHandler.
LoginContext lc = null;
try {
lc = newLoginContext("JaasSample", new TextCallbackHandler());
} catch (LoginException le) {
System.err.println("Cannot create LoginContext. " + le.getMessage());
System.exit(-1);
} catch (SecurityException se) {
System.err.println("Cannot create LoginContext. " + se.getMessage());
System.exit(-1);
}
try {
// attemptauthentication
lc.login();
} catch (LoginException le) {
System.err.println("Authentication failed:");
System.err.println(" " + le.getMessage());
System.exit(-1);
}
System.out.println("Authentication succeeded!");
}
}
Jaas.conf
1
2
3
JaasSample {
com.sun.security.auth.module.Krb5LoginModule required;
};
陈振阳 wechat
关注公众号