htmljsf-2authorizationuseridphaselistener

How to check authorization when HTML5 file called in JSF project


I define a PhaseListener for to check authorization in JSF project. But it doesn't work for HTML5. Even if I add to url=*.html for servlet mapping in web.exml, it doesn't work for HTML5. Because JSF2 does not support some tags of HTML5. Such as canvas etc.

What can I do to check authorization when HTML5 file called in JSF project?


Solution

  • You should in first place not have used a phase listener for the job at all, but a servlet filter. A phase listener runs only on JSF requests, i.e. only requests which matches the URL pattern of the FacesServlet. A phase listener is a clumsy approach for the sole purpose of authorization checking.

    Here's a concrete kickoff example of how such a filter could look like, assuming that you've stored the logged-in user as User object in the session:

    @WebFilter("/*")
    public class LoginFilter implements Filter {
    
        @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);
    
            User user = (session != null) ? session.getAttribute("user") : null;
            String loginURL = request.getContextPath() + "/login.xhtml";
    
            boolean loginRequest = request.getRequestURI().startsWith(loginURL);
            boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER);
    
            if (user != null || loginRequest || resourceRequest)) {
                chain.doFilter(request, response);
            } else {
                response.sendRedirect(loginURL);
            }
        }
    
        // ...
    }