KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > j2ee > blueprints > signon > web > SignOnFilter


1 /*
2 * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistribution in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in
13 * the documentation and/or other materials provided with the
14 * distribution.
15 *
16 * Neither the name of Sun Microsystems, Inc. or the names of
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific prior written permission.
19 *
20 * This software is provided "AS IS," without a warranty of any
21 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
22 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
24 * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
25 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
26 * DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
27 * OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
28 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
29 * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
30 * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
31 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
32 *
33 * You acknowledge that Software is not designed, licensed or intended
34 * for use in the design, construction, operation or maintenance of
35 * any nuclear facility.
36 */

37
38 package com.sun.j2ee.blueprints.signon.web;
39
40 import java.io.*;
41 import java.util.*;
42 import java.net.URL JavaDoc;
43
44 // J2EE imports
45
import javax.servlet.*;
46 import javax.servlet.http.*;
47 import javax.naming.*;
48
49 import com.sun.j2ee.blueprints.signon.SignOnFacade;
50
51
52 public class SignOnFilter implements Filter {
53
54     // these static strings define where to put/get things
55
public static final String JavaDoc FORM_SIGNON_URL = "j_signon_check";
56     public static final String JavaDoc FORM_USER_NAME = "j_username";
57     public static final String JavaDoc FORM_PASSWORD = "j_password";
58     public static final String JavaDoc REMEMBER_USERNAME = "j_remember_username";
59     public static final String JavaDoc USER_NAME = "j_signon_username";
60     public static final String JavaDoc SIGNED_ON_USER = "j_signon";
61     public static final String JavaDoc ORIGINAL_URL = "j_signon_original_url";
62     public static final String JavaDoc CREATE_USER_URL = "j_create_user";
63     public static final String JavaDoc COOKIE_NAME = "bp_signon";
64
65
66     private HashMap protectedResources;
67     private FilterConfig config = null;
68     private String JavaDoc signOnErrorPage = null;
69     private String JavaDoc signOnPage = null;
70     private String JavaDoc userCreationError = null;
71
72     public void init(FilterConfig config) throws ServletException {
73         this.config = config;
74         URL JavaDoc protectedResourcesURL = null;
75         try {
76             protectedResourcesURL = config.getServletContext().getResource("/WEB-INF/signon-config.xml");
77             ConfigFileSignOnDAO dao = new ConfigFileSignOnDAO(protectedResourcesURL);
78             signOnErrorPage = dao.getSignOnErrorPage();
79             signOnPage = dao.getSignOnPage();
80             protectedResources = dao.getProtectedResources();
81         } catch (java.net.MalformedURLException JavaDoc ex) {
82             System.err.println("SignonFilter: malformed URL exception: " + ex);
83             throw new RuntimeException JavaDoc(ex);
84         }
85     }
86
87     public void destroy() {
88         config = null;
89     }
90
91      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
92         throws IOException, ServletException {
93         HttpServletRequest hreq = (HttpServletRequest)request;
94         String JavaDoc currentURI = hreq.getRequestURL().toString();
95         String JavaDoc currentURL = hreq.getRequestURI();
96         // get everything after the context root
97
int firstSlash = currentURL.indexOf("/",1); // jump past the starting slash
98
String JavaDoc targetURL = null;
99         if (firstSlash != -1) targetURL = currentURL.substring(firstSlash + 1, currentURL.length());
100
101         if ((targetURL != null) && targetURL.equals(FORM_SIGNON_URL)) {
102             validateSignOn(request, response, chain);
103             // jump out of this method
104
return;
105         }
106
107         // check if the user is signed on
108
boolean signedOn = false;
109         if (hreq.getSession().getAttribute(SIGNED_ON_USER) != null) {
110             signedOn =((Boolean JavaDoc)hreq.getSession().getAttribute(SIGNED_ON_USER)).booleanValue();
111         } else {
112             hreq.getSession().setAttribute(SIGNED_ON_USER, new Boolean JavaDoc(false));
113         }
114         // jump to the resource if signed on
115
if (signedOn) {
116                 chain.doFilter(request,response);
117                 return;
118         }
119         // find out if the patterns match the target URL
120
Iterator it = protectedResources.keySet().iterator();
121         while (it.hasNext()) {
122             String JavaDoc protectedName = (String JavaDoc)it.next();
123             ProtectedResource resource = (ProtectedResource)protectedResources.get(protectedName);
124             String JavaDoc urlPattern = resource.getURLPattern();
125
126             // now check agains the targetURL
127
if (urlPattern.equals(targetURL)) {
128                 // put the orginal url in the session so others can access
129
hreq.getSession().setAttribute(ORIGINAL_URL, targetURL);
130                 config.getServletContext().getRequestDispatcher("/" + signOnPage).forward(request, response);
131                 // Jump out of the filter and go to the next page
132
return;
133             }
134         }
135         // No matches if we made it to here
136
chain.doFilter(request,response);
137     }
138
139      public void validateSignOn(ServletRequest request, ServletResponse response, FilterChain chain)
140         throws IOException, ServletException {
141         // convert to a http servlet request for now
142
HttpServletRequest hreq = (HttpServletRequest)request;
143         HttpServletResponse hres = (HttpServletResponse)response;
144         // get the user name
145
String JavaDoc userName = hreq.getParameter(FORM_USER_NAME);
146         // get the password
147
String JavaDoc password = hreq.getParameter(FORM_PASSWORD);
148         // check if the user wants userName set in cookie
149
String JavaDoc rememberUserName = hreq.getParameter(REMEMBER_USERNAME);
150         if (rememberUserName != null) {
151           // set a cookie with the username in it
152
Cookie userNameCookie = new Cookie(COOKIE_NAME, userName);
153           // set cookie to last for one month
154
userNameCookie.setMaxAge(2678400);
155           hres.addCookie(userNameCookie);
156         } else {
157             // see if the cookie exists and remove accordingly
158
Cookie[] cookies = hreq.getCookies();
159             if (cookies != null) {
160                 for (int loop=0; loop < cookies.length; loop++) {
161                     if (cookies[loop].getName().equals(COOKIE_NAME)) {
162                         cookies[loop].setMaxAge(0);
163                         hres.addCookie(cookies[loop]);
164                     }
165                 }
166             }
167         }
168
169         //validate against the registered users
170
try {
171             SignOnFacade signOn = new SignOnFacade();
172             boolean authenticated = signOn.authenticate(userName, password);
173             if (authenticated) {
174                 // place a true boolean in the session
175
if (hreq.getSession().getAttribute(USER_NAME) != null) {
176                     hreq.getSession().removeAttribute(USER_NAME);
177                 }
178                 hreq.getSession().setAttribute(USER_NAME, userName);
179                 // remove the sign on user key before putting it back in
180
if (hreq.getSession().getAttribute(SIGNED_ON_USER) != null) {
181                     hreq.getSession().removeAttribute(SIGNED_ON_USER);
182                 }
183                 hreq.getSession().setAttribute(SIGNED_ON_USER, new Boolean JavaDoc(true));
184                 // redirect to the original destination
185
String JavaDoc targetURL = (String JavaDoc)hreq.getSession().getAttribute(ORIGINAL_URL);
186                 hres.sendRedirect(targetURL);
187                 return;
188             } else {
189                 hres.sendRedirect(signOnErrorPage);
190                 return;
191             }
192         } catch(Exception JavaDoc e) {
193             System.out.println("SignOnFilter signOnError:::exception to:" + e);
194         }
195      }
196
197  }
198
199
Popular Tags