You forgot to check estaLoggeado
in the if()
block. In other words, you're never actually checking if the user is logged in. You're merely printing to stdout whether the user is logged in.
All in all, this filter's logic is rather clumsy. Those contains()
checks on the URI are very poor (note that indexOf(part) >= 0
is effectively exactly the same as contains(part)
). What if the part is in the beginning, middle or the ending of an URL? You should be performing exact/starts/ends matching.
Here's a rewrite:
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String loginURL = request.getContextPath() + "/pages/index.xhtml";
boolean loggedIn = (session != null) && (session.getAttribute("estaLoggeado") != null);
boolean loginRequest = request.getRequestURI().equals(loginURL);
boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER + "/");
if (loggedIn || loginRequest || resourceRequest)) {
chain.doFilter(request, response); // So, just continue request.
}
else {
response.sendRedirect(loginURL); // So, redirect to login page.
}
}
(as a side note: I recommend to replace estaLoggeado
by user
(or usuario
if you really need to make your code unreadable to non-English people) so that it represents the whole user instead of just an useless "flag")
Note that this doesn't cover ajax requests. The redirect would fail with no visual feedback when the session is expired during submitting a JSF ajax form. For a more extended filter, head to this answer: Authorization redirect on session expiration does not work on submitting a JSF form, page stays the same.