Created
March 5, 2012 17:25
-
-
Save iocanel/1979614 to your computer and use it in GitHub Desktop.
A wicket jaas session example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class WicketJaasSession extends AuthenticatedWebSession { | |
public static final String ROLES_GROUP_NAME = "ROLES"; | |
public static final String ROLES_PREFIX = "ROLE_"; | |
public static final String APPLICATION_POLICY_NAME = "blog"; | |
private Subject subject; | |
private Roles roles = new Roles(); | |
@SuppressWarnings("deprecation") | |
public WicketJaasSession(AuthenticatedWebApplication app, Request request) { | |
super(app, request); | |
} | |
public WicketJaasSession(Request request) { | |
super(request); | |
} | |
public boolean authenticate(String username, String password) { | |
boolean authenticated = false; | |
LoginCallbackHandler handler = new LoginCallbackHandler(username, password); | |
try { | |
LoginContext ctx = new LoginContext(APPLICATION_POLICY_NAME, handler); | |
ctx.login(); | |
authenticated = true; | |
subject = ctx.getSubject(); | |
for (Principal p : subject.getPrincipals()) { | |
if (p.getName().startsWith(ROLES_PREFIX)) { | |
roles.add((p.getName().substring(ROLES_PREFIX.length()))); | |
} | |
} | |
} catch (LoginException e) { | |
// You'll get a LoginException on a failed username/password combo. | |
authenticated = false; | |
} | |
return authenticated; | |
} | |
protected boolean isRole(Principal p){ | |
return p.getName().startsWith(ROLES_PREFIX); | |
} | |
public Roles getRoles() { | |
return roles; | |
} | |
private class LoginCallbackHandler implements CallbackHandler { | |
private String username; | |
private String password; | |
public LoginCallbackHandler(String username, String password) { | |
this.username = username; | |
this.password = password; | |
} | |
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { | |
for (int i = 0; i < callbacks.length; i++) { | |
Callback callback = callbacks[i]; | |
if (callback instanceof NameCallback) { | |
((NameCallback) callback).setName(username); | |
} else if (callback instanceof PasswordCallback) { | |
PasswordCallback pwCallback = (PasswordCallback) callback; | |
pwCallback.setPassword(password.toCharArray()); | |
} else { | |
throw new UnsupportedCallbackException(callbacks[i], "Callback type not supported"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment