Saska
Saska

Reputation: 1021

How to check user authorized with filter

I have a filter and Login Servlet. How i can check - authorized user or not? and if not authorized - to redirect him to Login Servlet.

Thanks.

Upvotes: 1

Views: 7455

Answers (2)

Nishant
Nishant

Reputation: 55876

Do this:

  1. When user logs in, set User object for that user in HttpSession. This way, httpRequest.getSession().setAttribute("LOGGED_USER", userObject)

  2. Now, every time you hit the filter/security filter. The first thing you do is check for this attribute.

  3. If the attribute is not there, redirect/forward the request to login servlet.

The pseudo code would look like this:

//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;
}

Edit 1: see this http://download.oracle.com/javaee/5/tutorial/doc/bncbx.html

Upvotes: 4

lukastymo
lukastymo

Reputation: 26819

In filter: IF UserObjectInSession exists => user logged ELSE do redirect to servlet

In servlet: IF verification() will be correct => put UserObjectInSession to session

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);
    }
}

Upvotes: 2

Related Questions