Earn Online (2) English (10) Java (7) Money (1) Money Online (1) Script (2) Trending (7)

JAAS Example


Using JAAS

Although it is possible to use JAAS within Tomcat as an authentication mechanism (JAASRealm), the flexibility of the JAAS framework is lost once the user is authenticated. This is because the principals are used to denote the concepts of "user" and "role", and are no longer available in the security context in which the webapp is executed. The result of the authentication is available only through request.getRemoteUser() and request.isUserInRole().

This reduces the JAAS framework for authorization purposes to a simple user/role system that loses its connection with the Java Security Policy. This tutorial's purpose is to put a full-blown JAAS authorisation implementation in place, using a few tricks to deal with some of Tomcat's idiosyncrasies.

Basic Design

The goal of the exercise is to be able to wrap the execution of our servlets/jsps in our own JAAS implementation, which allows us to enforce access control with a simple call in our code to AccessController.checkPermission(MyOwnPermission). We achieve this by wrapping each request in a security filter. This is configured in our web.xml. Most of this is covered in widely available JAAS tutorials on the net, so we only have some code fragments here.

web.xml file

  <filter>
    <filter-name>SecurityFilter</filter-name>
    <filter-class>security.SecurityFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>SecurityFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- Define a Security Constraint on this Application -->
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Entire Application</web-resource-name>
      <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>authenticateduser</role-name>
    </auth-constraint>
  </security-constraint>

  <!-- Define the Login Configuration for this Application -->
  <login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>My Realm</realm-name>
  </login-config>
login.conf

To start tomcat in security mode we call startup.sh with the -security flag. Furthermore we need to call our login module by setting $JVM_OPTS to something like -Djava.security.auth.login.config=/usr/local/tomcat/webapps/jaastest/WEB-INF/login.conf

Jaas {
    security.HttpLoginModule required debug=true;
};

HttpLoginModule


public class HttpLoginModule implements LoginModule {
...
    public boolean commit() throws LoginException {
        if (debug)
        System.err.println("HttpLoginModule: Commit");

        if (!succeeded) {
            // We didn't authenticate the user, but someone else did.
            // Clean up our state, but don't add our principal to
            // the subject
            userName = null;
            return false;
        }
     
        assignPrincipal(new UserPrincipal(userName));

//Based on the username, we can assign principals here
        //Some examples for test....
        assignPrincipal(new RolePrincipal("authenticateduser"));
        assignPrincipal(new RolePrincipal("administrator"));
        assignPrincipal(new CustomPrincipal("company1"));
     
        // Clean up our internal state
        userName = null;
        commitSucceeded = true;
        return true;
    }

    private void assignPrincipal(Principal p)
    {
// Make sure we dont add duplicate principals
if (!subject.getPrincipals().contains(p)) {
   subject.getPrincipals().add(p);
}
 
if(debug) System.out.println("Assigned principal "+p.getName()+" of type "+ p.getClass().getName() +" to user "+userName);
    }

HttpAuthCallbackHandler


class HttpAuthCallbackHandler implements CallbackHandler {

  private String userName;

  public HttpAuthCallbackHandler (HttpServletRequest request) {
    userName = request.getRemoteUser();
    System.out.println("Remote user is: " + request.getRemoteUser());
  }

  public void handle(Callback[] cb) throws IOException, UnsupportedCallbackException {

    for (int i = 0; i < cb.length; i++) {
      if (cb[i] instanceof NameCallback) {
        NameCallback nc = (NameCallback) cb[i];
        nc.setName(userName);
      } else throw new
        UnsupportedCallbackException(cb[i], "HttpAuthCallbackHandler");
    }
  }
}

CustomPolicy


public class CustomPolicy extends Policy {

private Policy deferredPolicy;

public CustomPolicy(Policy p) {
deferredPolicy = p;
}

public PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = deferredPolicy.getPermissions(cs);
System.out.println("getPermissions was called for codesource");
return pc;
}

public PermissionCollection getPermissions(ProtectionDomain domain) {

PermissionCollection pc = deferredPolicy.getPermissions(domain);
System.out.println("getPermissions was called for domain");
Principal[] principals = domain.getPrincipals();
System.out.println("retrieved " + principals.length + " principals");

for (int i=0; i< principals.length; i++) {

Principal p = principals[i];
System.out.println("This is principal" + p);
CustomPermission[] pms = null;
if (p instanceof CustomPrincipal ) {

System.out.println(p.getName()  + " is a CustomPrincipal");

// Get the permissions belonging to the principal here.
// Here we just add an example permission
CustomPermission[] test =  { new CustomPermission("AccessToCompany1Building") };
pms = test;
} else {
 System.out.println(p.getName()  + " is not a CustomPrincipal");
}

// Nothing to do
if (pms == null)  continue;

for(int j=0; j< pms.length; j++) {
System.out.println("Adding permission = " + pms[j]);
pc.add(pms[j]);
}

}

System.out.println(pc);
return pc;
}

public void refresh() {
deferredPolicy.refresh();
}
}


SecurityFilter


public class SecurityFilter implements Filter {

public void init(FilterConfig config) throws ServletException {
Policy orgPolicy = Policy.getPolicy();

if (orgPolicy instanceof CustomPolicy) {
// we already did this once upon a time..
System.out.println("Policy is a CustomPolicy,we already did this once upon a time");
} else {
Policy.setPolicy(new CustomPolicy(orgPolicy));
System.out.println("Policy is not a CustomPolicy");
}
}

public void destroy() {
//config = null;
}

public void doFilter(ServletRequest sreq, ServletResponse sres,
FilterChain chain) throws IOException, ServletException {
System.out.println("Starting SecurityFilter.doFilter");

HttpServletResponse response = (HttpServletResponse)sres;
HttpServletRequest request = (HttpServletRequest)sreq;

HttpSession session = request.getSession(true);
Subject subject = (Subject)session.getAttribute("javax.security.auth.subject");

if (subject == null) {
subject = new Subject();
}

session.setAttribute("javax.security.auth.subject", subject);

LoginContext lc = null;
try {
lc = new LoginContext("Jaas", subject, new HttpAuthCallbackHandler(request));
System.out.println("established new logincontext");
} catch (LoginException le) {
le.printStackTrace();
response.sendError(HttpServletResponse.SC_FORBIDDEN, request.getRequestURI());
return;
}

try {
lc.login();
// if we return with no exception, authentication succeeded
} catch (Exception e) {
System.out.println("Login failed: " + e);
response.sendError(HttpServletResponse.SC_FORBIDDEN, request.getRequestURI());
return;
}

try {
System.out.println("Subject is " + lc.getSubject());
chain.doFilter(request, response);
} catch(SecurityException se) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, request.getRequestURI());
}
}
}


Now test it

Create a jsp file with below code

<%@page import="java.security.*" %>
<%@page import="javax.security.auth.*" %>
<html>
<h1>Hello World!</h1>
<div>
<% Subject subject = Subject.getSubject(AccessController.getContext()); %>
<b>Subject</b> = <%= subject %>
-----------------------------------------------
<b>RemoteUser</b> = <%= request.getRemoteUser() %>
-----------------------------------------------
<% out.print("Is user in role \"authenticateduser\"?: "); if (request.isUserInRole("authenticateduser")) { out.println("yes"); } else { out.println("no"); } %> <b>Session Contents</b> <% java.util.Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String elem = (String)atts.nextElement(); out.println(elem + " -> " + session.getAttribute(elem)); out.println( ); } %> </div> </html>

JAAS Example JAAS Example Reviewed by Yogesh Choudhry on January 05, 2013 Rating: 5

Popular Posts