vrijdag 15 april 2011

Servlet filter for user authentication

Authentication is somenthing that everyone comes across, once that you work with user profiles, individual users. Basically, a user logs in (uid && pass), and gets to the pages that are ment to have access to. But the user-check is done only once, at login-time. Actually, the user should be authenticated on every post or get etc...So you can implement authentication on every jsp page or servlet or whatever. But this is not done!
A better way is to use a filter.

What is a filter?


A filter is a kind of servlet, that is called EVERY TIME BEFORE a servlet or jsp is requested. You can choose yourself for wich jsp's or servlet's the filter is triggered, trough the web.xml. So, inside that filter you can code your authentication code, as hard or as simple it is...

Example


Lets assume you have a simple servlet, called AuthExampleServlet.java. Its a servlet, one of the hundreds that may be in your projects, that needs authentication.
So we start making a filter, lets say AuthenticationFilter.java.

The code looks like this:

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

  HttpSession session = ((HttpServletRequest)request).getSession(false);
  Boolean logon = new Boolean(false);
  if (session != null)
   logon = (Boolean) session.getAttribute("LOGON");
  
  if(!logon)
  {
   request.getRequestDispatcher("./bad_auth.jsp").forward(request, response);
   return;
  }
  
  chain.doFilter(request, response);
 }

So, every time that the filter is called, it will execute this code.
Of course, we have to put those details in the web.xml.
The we say that the AuthExampleServlet servlet must be preceded by the filter



  AuthenticationFilter
  AuthenticationFilter
  com.auth.filter.AuthenticationFilter
 
 
  AuthenticationFilter
  /AuthenticationFilter
 
 
  AuthenticationFilter
  AuthExampleServlet
  REQUEST
  FORWARD
  INCLUDE
  ERROR
 


Of course, this is only a snippet of the whole web.xml. Do not forget to declare the AuthExampleServelt in it.
Now, With those bits and pieces, you can start a simple basic filter authentication.

Of course, filters can be used for other purposes too, like logging etc...
Also you can use multiple filters after each other

Here is a schema that explains a flow without and a flow with a filter:

Geen opmerkingen:

Een reactie posten