LoginFilter.java
01 /**
02  *  Copyright (c) @2009  by BEA Systems, Inc. All Rights Reserved.
03  */
04 package examples.webapp.servlets.filters;
05 
06 import weblogic.servlet.annotation.WLFilter;
07 import weblogic.servlet.security.ServletAuthentication;
08 
09 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import javax.servlet.http.HttpSession;
12 import javax.servlet.*;
13 
14 /**
15  * This is a simple example of an Servlet Filter that uses the WLS extended
16  * annotation to configure the filter name and filter mapping.
17  * The LoginFilter will filter url mapping "/session".
18  */
19 @WLFilter(name = "LoginFilter", mapping = "/session")
20 public class LoginFilter implements Filter {
21   private ServletAuthentication sa_;
22 
23   public LoginFilter() {
24     sa_ = new ServletAuthentication("username""password");
25     log("LoginFilter constructed ... ");
26   }
27 
28   public void init(FilterConfig filterConfig)
29       throws ServletException {
30   }
31 
32   public void destroy() {
33   }
34 
35   public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc)
36       throws java.io.IOException, javax.servlet.ServletException {
37     log("LoginFilter invoking ... ");
38     HttpServletRequest request = (HttpServletRequestreq;
39     HttpServletResponse response = (HttpServletResponseres;
40     HttpSession sess = request.getSession(true);
41     boolean isAuthed = "true".equals(sess.getAttribute("authenticated"));
42 
43     if (!isAuthed) {
44       int authenticated = sa_.weak(request, response);
45       if (authenticated != ServletAuthentication.NEEDS_CREDENTIALS &&
46           authenticated != ServletAuthentication.FAILED_AUTHENTICATION) {
47         isAuthed = true;
48         sess.setAttribute("authenticated""true");
49       }
50       sa_.done(request);
51     }
52     if (isAuthed) {
53       /* the user is authenticated, pass request to the next filter in the list or
54       * if there are no more filters in the list, pass the request to the servlet
55       */
56       fc.doFilter(request, response);
57     else {
58       /* the user is not authorized to access the servlet
59       * redirect him to the login page
60       */
61       response.sendRedirect("loginForm.jsp");
62     }
63     log("leaving LoginFilter ...");
64   }
65 
66 
67   public void log(String s) {
68     System.out.println("[LoginFilter]: " + s);
69   }
70 }