Introduction
Tomcat provides a default JAAS Realm implementation so developers may implement JAAS Login Modules and easily integrate them with the container. In this tutorial we will implement all the required components to put JAAS up and running in Tomcat web container.
This tutorial considers the following software and environment:
- Ubuntu 12.04
- JDK 1.7.0.09
- Tomcat 7.0.35
The Principals
One of the core concepts of JAAS is the existence of users and roles (roles are similar to groups in UNIX systems). Authorization may be issued to specific users or to roles. In JAAS this is concept is translated to Principals: Principals may represent users orroles independently. Let's define User and Role Principals to be used in this example:
package com.byteslounge.jaas;
import java.security.Principal;
public class UserPrincipal implements Principal {
private String name;
public UserPrincipal(String name) {
super();
this.name = name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
package com.byteslounge.jaas;
import java.security.Principal;
public class RolePrincipal implements Principal {
private String name;
public RolePrincipal(String name) {
super();
this.name = name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
Basically we are defining two simple Principals, each one of them requiring just a name so they may be promptly identified (a username or a role name). Remember that our principals must implement the java.security.Principal interface.
The Login Module
Now we need to define a Login Module that will actually implement the authentication process. The Login module must implement the javax.security.auth.spi.LoginModule interface:
package com.byteslounge.jaas;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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 BytesLoungeLoginModule implements LoginModule {
private CallbackHandler handler;
private Subject subject;
private UserPrincipal userPrincipal;
private RolePrincipal rolePrincipal;
private String login;
private List<String> userGroups;
@Override
public void initialize(Subject subject,
CallbackHandler callbackHandler,
Map<String, ?> sharedState,
Map<String, ?> options) {
handler = callbackHandler;
this.subject = subject;
}
@Override
public boolean login() throws LoginException {