Using HTTP Request.login with JBoss/JAAS

2019-05-26 07:07发布

I have successfully setup a JBoss security domain, and can authenticate using BASIC authentication (as defined in web.xml). This all works well. I cannot however figure out how to use the http request.login method.

The following security domain (from jboss-web.xml) works for BASIC authentication:

<jboss-web>  
    <context-root>/myapp</context-root>  
    <security-domain>java:/jaas/myapp-realm</security-domain>  
</jboss-web> 

But when I use request.login as follows:

public void login() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    try {
        request.login(username, password);
    }
    catch (ServletException ex) {
        java.util.logging.Logger.getLogger(UserLogin.class.getName()).log(Level.SEVERE, null, ex);
    }
}

I get the following exception:

javax.servlet.ServletException: Failed to authenticate a principal

I know the username/pasword is fine (it worked fine using BASIC auth). I have TRACE level logging on, and it doesn't look like it is even trying to authenticate. What have I missed?

See http://java-web-development.blogspot.com/2011/07/jee-6-security-part-two-implementation.html if you need more details about my setup/config. I am using JBoss 6.

1条回答
戒情不戒烟
2楼-- · 2019-05-26 07:08

It is now working. I made sure FORM based authentication worked, and once that worked I went back to using request.login and it worked?! I use hot deployments via JRebel so it is a possibility I had authenticated with BASIC auth and it left a user principal in my session which then caused the request.login to fail (request.login throws an exception if you are already authenticated). I swear I had done a hard restart of JBoss, but this is the only logical thing I can think of.

I now have a sanity check around the login, like so:

public void login() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    try {
        Principal userPrincipal = request.getUserPrincipal();
        if (request.getUserPrincipal() != null) {
            request.logout();
        }
        request.login(username, password);
        userPrincipal = request.getUserPrincipal();
        authUser = userDao.findByLogin(userPrincipal.getName());
    }
    catch (ServletException ex) {
        java.util.logging.Logger.getLogger(UserLogin.class.getName()).log(Level.SEVERE, null, ex);
    }
查看更多
登录 后发表回答