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

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 in successfully that is through login.html

This is my login.html file

<html>
<head>
<title>Login Page 122</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login User">
</form>
</body>
</html>

This is my LoginServlet which recivies the request when clicked on the submit button

package com;
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final String userID = "admin";
    private final String password = "password";

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd");

        if(userID.equals(user) && password.equals(pwd)){
            HttpSession session = request.getSession();
            session.setAttribute("user", "LoggedIN");
            response.sendRedirect("LoginSuccess.jsp");
        }else{
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
            PrintWriter out= response.getWriter();
            out.println("<font color=red>Either user name or password is wrong.</font>");
            rd.include(request, response);
        }

    }

}

This is my Filter class which protects the *.html resources

package com;
 public class AuthenticationFilter implements Filter {
    private ServletContext context;
    public void init(FilterConfig fConfig) throws ServletException {
        this.context = fConfig.getServletContext();
        this.context.log("AuthenticationFilter initialized");
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        this.context.log("Requested Resource::"+uri);
        HttpSession session = req.getSession(false);
        if(session == null || !session.getAttribute("user").toString().equals("LoggedIN")){
            this.context.log("Unauthorized access request");
            System.out.println("Into session is null condition");
            res.sendRedirect("login.html");
        }else{
           System.out.println("Into chain do filter");
            chain.doFilter(request, response);
        }
    }
    public void destroy() {
    }
}

And this is my web.xml file

<?xml version="1.0" encoding="UTF-8"?>

<web-app>
  <display-name>LoginFilter</display-name>
   <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>LogoutServlet</display-name>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>com.LogoutServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/LogoutServlet</url-pattern>
  </servlet-mapping>
  <filter>
    <display-name>AuthenticationFilter</display-name>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>com.AuthenticationFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>*.html</url-pattern>
  </filter-mapping>
</web-app>

The issue i am seeing is that

I am seeing this statement multiple times in my server console .

Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition
Into session is null condition

Solution 1:

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