如何检查用户授权过滤器

时间:2011-02-13 15:52:10

标签: java servlet-filters

我有一个过滤器和登录Servlet。我如何检查 - 授权用户与否?如果没有授权 - 将他重定向到Login Servlet。

感谢。

2 个答案:

答案 0 :(得分:4)

这样做:

  1. 当用户登录时,在HttpSession中为该用户设置User对象。这样,httpRequest.getSession().setAttribute("LOGGED_USER", userObject)

  2. 现在,每次点击过滤器/安全过滤器。您要做的第一件事就是检查此属性。

  3. 如果该属性不存在,请将请求重定向/转发到登录servlet。

  4. 伪代码如下所示:

    //in your login servlet, on successful login
    request.getSession().setAttribute("LOGGED_USER", userObject);
    
    //in your security filter
    if(request.getSession().getAttribute("LOGGED_USER") == null){
    //optionally, you may like to check if that attribute has a valid userId as well
         RequestDispatcher rd = request.getRequestDispatcher("relative/path/to/login/servlet")
         rd.forward(request, response);
         return;
    }
    

    编辑1: 看到此 http://download.oracle.com/javaee/5/tutorial/doc/bncbx.html

答案 1 :(得分:2)

在过滤器中: 如果UserObjectInSession存在=>用户登录 ELSE重定向到servlet

在servlet中: 如果验证()将是正确的=>将UserObjectInSession放入会话

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {       
    HttpServletRequest httpReq = (HttpServletRequest) request; 
    HttpServletResponse httpRes = (HttpServletResponse) response;

    HttpSession session = httpReq.getSession();
    User currentUser = (User)session.getAttribute("userInSession");

    if (currentUser == null) {
        httpRes.sendRedirect("...")    //redirect to LoginServlet
    } else {        
        chain.doFilter(request, response);
    }
}