jsf-2servlet-filtersshiro

How to redirect already authenticated user from login page to home page


I'm developing JSF application with Apache Shiro. I autenticate the user with Shiro and redirect her to home page there is no problem with that. After the authentication when I try to access login page, it doesn't redirect me the homepage. I can login again even when there is already loggedin user. I'm doing Programmatic Login as BalusC mentioned in his blog post.

[main]
credentialsMatcher = org.apache.shiro.authc.credential.PasswordMatcher
myRealm = com.example.security.myRealm
myRealm.credentialsMatcher = $credentialsMatcher
securityManager.realms = $myRealm
user = com.example.web.filter.FacesAjaxAwareUserFilter
user.loginUrl = /login.xhtml

[urls]
/login.xhtml = user

This filter is written from the blog post.

public class FacesAjaxAwareUserFilter extends UserFilter {

private static final String FACES_REDIRECT_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
        + "<partial-response><redirect url=\"%s\"></redirect></partial-response>";

@Override
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
    HttpServletRequest req = (HttpServletRequest) request;
    if ("partial/ajax".equals(req.getHeader("Faces-Request"))) {
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().printf(FACES_REDIRECT_XML, req.getContextPath() + getLoginUrl());
    }
    else {
        super.redirectToLogin(request, response);
    }
}

}

What is the problem and how can I redirect the user if she is already authenticated?

EDIT: For now I'm using PostConstruct annotation to redirect if the user is already authenticated. I'm open to any good solution.


Solution

  • After the authentication when I try to access login page, it doesn't redirect me the homepage. I can login again even when there is already loggedin user

    Neither Shiro nor the custom Shiro user filter are intented to prevent that. Shiro doesn't have builtin facilities for this. The custom Shiro user filter runs only when an unauthenticated user is found, not when an already authenticated user is found.

    Preventing an authenticated user from accessing the login page directly is your own responsibility. Depending on business requirements you can do the following: