Nabz Nabz - 6 months ago 11
CSS Question

Authentication Filter not loading css for 3 web pages

I have an authentication filter for my web app, and it successfulyl loads up the css for all the web pages after logging in, except for three pages the homepage(index) the about us page(about) and the register page(register). For some reason I cannot figure out why my filter is not deciding to load up the css for those three pages but for the other pages it works, I've checked the jsp files for all the pages and cant spot whats wrong.

I was told I had to fix something in my doFilter method with the excludeURLs but I'm still confused.

Here is my doFilter:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpSession session = httpReq.getSession(false); // if the fail login it doesnt create a session

if (session != null && session.getAttribute("user") == null && !excludeURLs.contains(httpReq.getServletPath()) ){
RequestDispatcher rd = httpReq.getRequestDispatcher("login.jsp");
rd.forward(request, response);
return;
}

chain.doFilter(request, response);
}


And here is the init method where I exclude specific URLs:

public void init(FilterConfig fConfig) throws ServletException {
System.out.println("AuthenticationFilter Initiated...");

//Pages/Servlet
excludeURLs.add("/login");
excludeURLs.add("/login.jsp");
excludeURLs.add("/index");
excludeURLs.add("/index.jsp");
excludeURLs.add("/about");
excludeURLs.add("/about.jsp");
excludeURLs.add("/register");
excludeURLs.add("/signup.jsp");

//Images
excludeURLs.add("/Images");
excludeURLs.add("/css");
excludeURLs.add("/js");
}

Answer

Assuming:

  1. Your css files to have the extension ".css",
  2. Unauthenticated access to css files isn't an issue for your you/your organization, a quick fix would be:

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpSession session = httpReq.getSession(false); // if the fail login it doesnt create a session
        String path= httpReq.getRequestURI();
        if(path.endsWith(".css")){
          chain.doFilter(request,response);
          return;
        }
    
    
        if (session != null && session.getAttribute("user") == null && !excludeURLs.contains(httpReq.getServletPath()) ){
            RequestDispatcher rd = httpReq.getRequestDispatcher("login.jsp");
            rd.forward(request, response);
            return;
        }
    
        chain.doFilter(request, response);
    }