A Servlet Filter for authentication  

Posted by Kishore in

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import my.com.lhdn.cms.security.base.Globals;
import my.com.lhdn.cms.security.base.util.UserLevelBean;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AuthenticationFilter implements Filter {
private static Log log = LogFactory.getLog(AuthenticationFilter.class);

private FilterConfig filterConfig = null;

private static ArrayList bypassURLs = null;

public AuthenticationFilter() {
System.out.println("--AuthenticationFilter--");
}

/**
* Called by the web container to indicate to a filter that it is being
* placed into service.
*/
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;

log.info("AuthenticationFilter init, now monitoring each request.");
}

/**
* The doFilter method of the Filter is called by the container each time a
* request/response pair is passed through the chain due to a client request
* for a resource at the end of the chain.
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {

HttpServletRequest httpRequest = null;
HttpServletResponse httpResponse = null;

try {
if (request instanceof HttpServletRequest
&& response instanceof HttpServletResponse) {
httpRequest = ((HttpServletRequest) request);
httpResponse = (HttpServletResponse) response;
System.err.println("Entering into " + httpRequest.getRequestURI().toString());

HttpSession session = httpRequest.getSession(false);
String tmpurl = null;
if (session != null) {
if (session.getAttribute(Globals.SESSION_USER) != null) {
if (VALID_USER) {
return;
}
} else {
session.invalidate();
httpResponse.sendRedirect(httpRequest.getContextPath()+"/login.do");
//GO TO LOGIN PAGE SINCE NOT AUTHENTICATED
return;
}

} else {
//GO TO LOGIN PAGE SINCE NO SESSION INITIATED
httpResponse.sendRedirect(httpRequest.getContextPath()+"/login.do");
return;

}
chain.doFilter(request, response);

return;
}
} catch (Exception ex) {
if (log.isErrorEnabled())
log.error(ex);
throw new ServletException(ex);
} finally {
System.err.println("Leaving " + httpRequest.getRequestURI().toString());
}
}

/**
* Called by the web container to indicate to a filter that it is being
* taken out of service.
*/
public void destroy() {
filterConfig = null;
}
}

This entry was posted on Aug 27, 2008 at Wednesday, August 27, 2008 and is filed under . You can follow any responses to this entry through the comments feed .

0 comments

Post a Comment