使用过滤器和servlet进行身份验证

时间:2017-11-22 10:27:43

标签: authentication servlets filter

我有一个过滤器,用于拦截我的所有请求,以便在处理到目标之前检查会话中我登录用户的有效性。但问题是它在尝试登录时会不断重定向到登录页面?

使用的参考:https://stackoverflow.com/questions/13274279/authentication-filter-and-servlet-for-login

过滤

public class AuthenticationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter init method()");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("Filter doFilter method()");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        Users loggedIn = (Users) session.getAttribute("LoggedInUser");
        boolean loggedInUser = session != null && session.getAttribute("LoggedInUser") != null;
        String logInURI = req.getContextPath() + "/loginPage.jsp";
        boolean loginRequest = req.getRequestURI().equals(logInURI);
        if (loggedInUser || loginRequest) {
            chain.doFilter(request, response);
        } else {
            res.sendRedirect(logInURI);
        }
    }

    @Override
    public void destroy() {
    }

}

的web.xml

<filter>
        <filter-name>AuthenticationFilter</filter-name>
        <filter-class>AuthenticationFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>AuthenticationFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

1 个答案:

答案 0 :(得分:0)

经过更多调查后,这个解决方案对我来说很合适:

@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        /* Check if the user within the session */
        boolean loggedInUser = session.getAttribute("LoggedInUser") != null;

        /* Get the login uri, to avoid infinite loop */
        String logInURI = req.getContextPath() + "/loginPage.jsp";

        /* Current reuest */
        String currentReq = req.getRequestURI();

        /* Get LoginServlet req */
        String loginServlet = req.getContextPath() + "/LoginServlet";

        /* Check if current request is for loginServlet */
        boolean loginServletReq = currentReq.equals(loginServlet);

        /* Check if the request is equal to login page */
        boolean loginRequest = currentReq.equals(logInURI);

        if (loginRequest) {
            chain.doFilter(req, res);
        } else if (loggedInUser) {
            chain.doFilter(req, res);
        } else if (loginServletReq) {
            chain.doFilter(req, res);
        } else {
            res.sendRedirect(logInURI);
        }

    }