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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
package com.prog.pro.model.security.jaas;
import com.prog.pro.common.security.jaas.SimplePrincipal;
import java.util.Map;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
public class ADLoginModule implements LoginModule {
private Subject subject;
private SimplePrincipal entity;
private CallbackHandler callbackhandler;
private static final int NOT = 0;
private static final int OK = 1;
private static final int COMMIT = 2;
private int status;
public void initialize(Subject subject, CallbackHandler callbackhandler, Map state, Map options) {
status = NOT;
entity = null;
this.subject = subject;
this.callbackhandler = callbackhandler;
}
public boolean login() throws LoginException {
if (callbackhandler == null) {
throw new LoginException("No callback handler is available");
}
Callback callbacks[] = new Callback[2];
callbacks[0] = new NameCallback("username");
callbacks[1] = new PasswordCallback("password", false);
String name = null;
String password = null;
try {
callbackhandler.handle(callbacks);
name = ((NameCallback)callbacks[0]).getName();
password = new String(((PasswordCallback)callbacks[1]).getPassword());
} catch (java.io.IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException ce) {
throw new LoginException("Error: " + ce.getCallback().toString());
}
if ((name.equals("user")) && (password.equals("pass"))) {
entity = new SimplePrincipal(name);
status = OK;
return true;
} else {
return false;
}
}
public boolean commit() throws LoginException {
if (status == NOT) {
return false;
}
if (subject == null) {
return false;
}
Set entities = subject.getPrincipals();
if (!entities.contains(entity)) {
entities.add(entity);
}
status = COMMIT;
return true;
}
public boolean abort() throws LoginException {
if ((subject != null) && (entity != null)) {
Set entities = subject.getPrincipals();
if (entities.contains(entity)) {
entities.remove(entity);
}
}
subject = null;
entity = null;
status = NOT;
return true;
}
public boolean logout() throws LoginException {
subject.getPrincipals().remove(entity);
status = NOT;
subject = null;
return true;
}
} |
Partager