Question

I have setup my web.xml to deny access to certain pages within my site and redirect a user to a login page if they are not yet logged in. And I have defined a role simply called USER It looks like this:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>mis</web-resource-name>
        <url-pattern>/secure/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>USER</role-name>
    </auth-constraint>
</security-constraint>

<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>file</realm-name>
    <form-login-config>
        <form-login-page>/signin.xhtml</form-login-page>
        <form-error-page>/error.xhtml</form-error-page>
    </form-login-config>
</login-config>

<security-role>
    <role-name>USER</role-name>
</security-role>

In my signing.xhtml page I want to check the user's credentials manually (we are using injected headers from a reverse proxy to handle the actual security) and then assign the user to a specific role based on certain conditions.

Is there a way to way to programmatically assign the current user and the roles that the user has? Or do I have to use the JBOSS/Glassfish users setup?

Was it helpful?

Solution

Seems the best way to do this is not to use the security-constraints but rather use the filter option. First create a class that implements javax.servlet.Filter and implement the doFilter method:

public class UserRoleFilter implements Filter {    
    @Override
    public void init(FilterConfig cfg) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse response, FilterChain next) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;

        //Manually check that the current user can access pages
        //I did that by storing stuff in the session which you can access by 
        //request.getSession().getAttribute(someKey);
        if(!userHasAccessToRestrictedPages) {
            HttpServletResponse r = (HttpServletResponse) response;
            r.sendRedirect(request.getContextPath() + "/signin.xhtml");
            return;
        }

        next.doFilter(req, response);
    }

    @Override
    public void destroy() {
    }
}

Then in the web.xml file remove the security-constraints, login-config and security-role and replace with (where filter-class refers to the class above):

<filter>  
    <filter-name>UserRoleFilter</filter-name>  
    <filter-class>security.UserRoleFilter</filter-class>  
</filter>  
<filter-mapping>  
    <filter-name>UserRoleFilter</filter-name>  
    <url-pattern>/secure/*</url-pattern> 
</filter-mapping>

That should do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top