Java Authentication Authorization Service(JAAS,Java验证和授权API)提供了灵活和可伸缩的机制来保证客户端或服务器端的Java程序。Java早期的安全框架强调的是通过验证代码的来源和作者,保护用户避免受到下载下来的代码的攻击。JAAS强调的是通过验证谁在运行代码以及他/她的权限来保护系统面受用户的攻击。它让你能够将一些标准的安全机制,例如SolarisNIS(网络信息服务)、WindowsNT、LDAP(轻量目录存取协议),Kerberos等通过一种通用的,可配置的方式集成到系统中。
Easy{
com.camps.jaas.EasyLoginModulerequired debug=false;
};
-Djava.security.auth.login.config=jaas.conf
jaas.conf is absolute path
public class LoginService {
public void login(String username, String pass){
LoginContextlc;
try {
lc = newLoginContext("Easy",new EasyCallbackHandler(username, pass));
lc.login();
SubjectuserSubject = lc.getSubject();
userSubject.getPrincipals();
} catch (LoginException e) {
e.printStackTrace();
}
}
}
public class EasyLoginModule implements LoginModule{
private booleanisAuth;
private Subjectsubject;
private CallbackHandlerhandler;
private Principalprincipal;
public booleanabort() throws LoginException {
returnfalse;
}
public booleancommit() throws LoginException {
if(isAuth)
subject.getPrincipals().add(principal);
returnisAuth;
}
public voidinitialize(Subject subject, CallbackHandler callbackHandler,
Map<String,?> sharedState, Map<String, ?> options) {
this.subject= subject;
this.handler= callbackHandler;
}
public booleanlogin() throws LoginException {
NameCallbacknameCallback = new NameCallback("username");
PasswordCallbackpasscallback = new PasswordCallback("password",true);
try {
handler.handle(newCallback[]{nameCallback, passcallback});
}catch (IOException e) {
e.printStackTrace();
}catch (UnsupportedCallbackExceptione) {
e.printStackTrace();
}
Stringusername = nameCallback.getName();
Stringpassword = passcallback.getPassword().toString();
if(username.equals("zz")&& password.equals("yy")){
isAuth =true;
principal =newEasyPrincipal(username);
}
returnisAuth;
}
public booleanlogout() throws LoginException {
subject.getPrincipals().remove(principal);
principal =null;
returnfalse;
}
}
public class EasyCallbackHandler implements CallbackHandler{
private Stringusername;
private Stringpassword;
public EasyCallbackHandler(String username,String password){
this.username= username;
this.password= password;
}
public voidhandle(Callback[] callbacks) throwsIOException,
UnsupportedCallbackException{
for(Callback callback:callbacks){
if(callbackinstanceofNameCallback){
((NameCallback)callback).setName(username);
}
if(callbackinstanceofPasswordCallback){
((PasswordCallback)callback).setPassword(password.toCharArray());
}
}
}
}
public class EasyPrincipal implements Principal{
privateString name;
publicEasyPrincipal(String name){
this.name= name;
}
publicString getName() {
returnthis.name;
}
}