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.