Prevent accessing restricted page without login in Jsf2

That depends on how you have programmed the login. You seem to be using homegrown authentication wherein you set the logged-in user as a property of a session scoped managed bean. Because with Java EE provided container managed login, preventing access to restricted pages is already taken into account.

Assuming that you’ve all restricted pages on a certain URL pattern, like /app/*, /secured/* etc and that your session scoped bean has the managed bean name user, then you could use a filter for the job. Implement the following in doFilter() method:

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession(false);
    User user = (session != null) ? (User) session.getAttribute("user") : null;

    if (user == null || !user.isLoggedIn()) {
        response.sendRedirect("/login.xhtml"); // No logged-in user found, so redirect to login page.
    } else {
        chain.doFilter(req, res); // Logged-in user found, so just continue request.
    }
}

Map this filter on an URL pattern covering the restricted pages.

Further, you need to ensure that you’ve disabled the browser cache on those pages, otherwise the enduser will still be able to see them from browser cache after logout. You can also use a filter for this. You could even do it in the same filter. See also Browser back button doesn’t clear old backing bean values.

Leave a Comment