Servlet filter runs in infinite redirect loop when user is not logged in

后端 未结 1 547
长情又很酷
长情又很酷 2020-12-04 03:11

I have got two HTML files

  1. login.html
  2. Test.html

My requirement is that the User shouldn\'t able to access test.html unless he logs i

1条回答
  •  無奈伤痛
    2020-12-04 03:50

    This AuthenticationFilter also runs when login.html is being requested. However, the code is redirecting to login.html once again instead of continuing the filter chain. This explains the infinite redirect loop.

    You need to let the filter just continue the request if the currently requested page is already the login page itself.

    E.g.

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession(false);
        String loginURL = req.getContextPath() + "/login.html";
    
        boolean loggedIn = session != null && session.getAttribute("user") != null;
        boolean loginRequest = loginURL.equals(req.getRequestURI());
    
        if (loggedIn || loginRequest) {
            chain.doFilter(request, response);
        } else {
            res.sendRedirect(loginURL);
        }
    }
    

    See also:

    • Authentication filter and servlet for login

    0 讨论(0)
提交回复
热议问题