What is the correct way to implement a redirected login using JSF 2.0?

Part of my site should be accessible only to authorized users. Suppose the user enters the a.html page, which belongs to only the part that is allowed only for authorization.

If I used servlets / JSP, I could write a filter that checked if the user was logged in, and if not, redirected him to the login page. After a successful login, the user will be redirected to the page that he would like to receive initially, in this case a.html. (The page address can be stored in the request).

What is the correct way to implement such a scenario in JSF 2.0?

+5
source share
1 answer

Just do the same, s Filter. It's nice to know that the beans-managed JSF session is under covers that are stored as an attribute HttpSessionwith the managed name bean as the key.

Assuming you control a bean like this:

@ManagedBean
@SessionScoped 
public class UserManager {

    private User user;

    // ...

    public boolean isLoggedIn() {
        return (user != null);
    }

}

Then you can check it in Filter#doFilter()as follows:

UserManager userManager = (UserManager) ((HttpServletRequest) request).getSession().getAttribute("userManager");

if (userManager != null && userManager.isLoggedIn()) {
    chain.doFilter(request, response);
} else {
    ((HttpServletResponse) response).sendRedirect("login.xhtml");
}
+3
source

All Articles