Search code examples
sessiontomcatjdbcstruts2jdbcrealm

Get session attributes in tomcat realm


I am developing an application in J2E with struts 2 and tomcat v6.

I have a login page in my application where the user will have to type his password by clicking on a virtual keyboard (made on my own).

Before the keyboard appears, i have an action to randomise the characters' . This action also encode all characters for security reasons and set the map of characters and code in session.

The authentication is done with a JDBC realm in tomcat.

What i am trying to do is to decode the user's password. I have tried a filter with the url-pattern "j_security_check" but i found it was not possible to catch this event in filter.

So I am trying to decode the password in the JDBC realm, but it is not working. I have tried to use ServletActionContext.getRequest() in the realm but I am facing a null pointer exception.

Is it possible to get the map stored in session in the realm ? If it is not, any clues of how to do this are welcome because I haven't found any solution.


Solution

  • One posible solution is writing Custom Authenticator, extending FormAuthenticator

    Eg.

    //Will expand the basic FORM authentication to include auth based on request headers
    public class CustomAuthenticator extends FormAuthenticator{
    
        public boolean authenticate(Request request, Response response, LoginConfig config) throws IOException{
            if(request.getUserPrincipal() == null){
                Realm realm = context.getRealm();
                //Pick the user name and password from the request headers
                //you can decode the password here
                if(username == null || pass ==null) return super.authenticate(....);
    
                boolean authenticated = realm.authenticate(username, pass);
                if(authenticated == false) return false;
    
                //Set the username/password on the session and set  the principal in request
                session.setNote(Constants.SESS_USERNAME_NOTE, username);
                session.setNote(Constants.SESS_PASSWORD_NOTE, password);
                request.setUserPrincipal(principal);
                register(request, response, principal, Constants.FORM_METHOD, username, pass);
            }
            return true;
        }
    }
    

    See also: http://apachecon.com/eu2007/materials/UnderstandingTomcatSecurity.pdf and http://javaevangelist.blogspot.com/2012/12/tomcat-7-custom-valve.html