KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > winstone > auth > FormAuthenticationHandler


1 /*
2  * Copyright 2003-2006 Rick Knowles <winstone-devel at lists sourceforge net>
3  * Distributed under the terms of either:
4  * - the common development and distribution license (CDDL), v1.0; or
5  * - the GNU Lesser General Public License, v2.1 or later
6  */

7 package winstone.auth;
8
9 import java.io.IOException JavaDoc;
10 import java.util.List JavaDoc;
11 import java.util.Set JavaDoc;
12
13 import javax.servlet.ServletException JavaDoc;
14 import javax.servlet.ServletRequest JavaDoc;
15 import javax.servlet.ServletResponse JavaDoc;
16 import javax.servlet.http.HttpServletRequest JavaDoc;
17 import javax.servlet.http.HttpServletRequestWrapper JavaDoc;
18 import javax.servlet.http.HttpServletResponse JavaDoc;
19 import javax.servlet.http.HttpSession JavaDoc;
20
21 import org.w3c.dom.Node JavaDoc;
22
23 import winstone.AuthenticationPrincipal;
24 import winstone.AuthenticationRealm;
25 import winstone.Logger;
26 import winstone.WebAppConfiguration;
27 import winstone.WinstoneRequest;
28
29 /**
30  * Handles FORM based authentication configurations. Fairly simple ... it just
31  * redirects any unauthorized requests to the login page, and any bad logins to
32  * the error page. The auth values are stored in the session in a special slot.
33  *
34  * @author <a HREF="mailto:rick_knowles@hotmail.com">Rick Knowles</a>
35  * @version $Id: FormAuthenticationHandler.java,v 1.6 2006/08/25 17:05:00 rickknowles Exp $
36  */

37 public class FormAuthenticationHandler extends BaseAuthenticationHandler {
38     private static final String JavaDoc ELEM_FORM_LOGIN_CONFIG = "form-login-config";
39     private static final String JavaDoc ELEM_FORM_LOGIN_PAGE = "form-login-page";
40     private static final String JavaDoc ELEM_FORM_ERROR_PAGE = "form-error-page";
41     private static final String JavaDoc FORM_ACTION = "j_security_check";
42     private static final String JavaDoc FORM_USER = "j_username";
43     private static final String JavaDoc FORM_PASS = "j_password";
44     private static final String JavaDoc AUTHENTICATED_USER = "winstone.auth.FormAuthenticationHandler.AUTHENTICATED_USER";
45     private static final String JavaDoc CACHED_REQUEST = "winstone.auth.FormAuthenticationHandler.CACHED_REQUEST";
46     
47     private String JavaDoc loginPage;
48     private String JavaDoc errorPage;
49
50     /**
51      * Constructor for the FORM authenticator
52      *
53      * @param realm
54      * The realm against which we are authenticating
55      * @param constraints
56      * The array of security constraints that might apply
57      * @param resources
58      * The list of resource strings for messages
59      * @param realmName
60      * The name of the realm this handler claims
61      */

62     public FormAuthenticationHandler(Node JavaDoc loginConfigNode,
63             List JavaDoc constraintNodes, Set JavaDoc rolesAllowed,
64             AuthenticationRealm realm) {
65         super(loginConfigNode, constraintNodes, rolesAllowed, realm);
66
67         for (int n = 0; n < loginConfigNode.getChildNodes().getLength(); n++) {
68             Node JavaDoc loginElm = loginConfigNode.getChildNodes().item(n);
69             if (loginElm.getNodeName().equals(ELEM_FORM_LOGIN_CONFIG)) {
70                 for (int k = 0; k < loginElm.getChildNodes().getLength(); k++) {
71                     Node JavaDoc formElm = loginElm.getChildNodes().item(k);
72                     if (formElm.getNodeType() != Node.ELEMENT_NODE)
73                         continue;
74                     else if (formElm.getNodeName().equals(ELEM_FORM_LOGIN_PAGE))
75                         loginPage = WebAppConfiguration.getTextFromNode(formElm);
76                     else if (formElm.getNodeName().equals(ELEM_FORM_ERROR_PAGE))
77                         errorPage = WebAppConfiguration.getTextFromNode(formElm);
78                 }
79             }
80         }
81         Logger.log(Logger.DEBUG, AUTH_RESOURCES,
82                 "FormAuthenticationHandler.Initialised", realmName);
83     }
84
85     /**
86      * Evaluates any authentication constraints, intercepting if auth is
87      * required. The relevant authentication handler subclass's logic is used to
88      * actually authenticate.
89      *
90      * @return A boolean indicating whether to continue after this request
91      */

92     public boolean processAuthentication(ServletRequest JavaDoc request,
93             ServletResponse JavaDoc response, String JavaDoc pathRequested) throws IOException JavaDoc,
94             ServletException JavaDoc {
95         if (pathRequested.equals(this.loginPage)
96                 || pathRequested.equals(this.errorPage))
97             return true;
98         else
99             return super
100                     .processAuthentication(request, response, pathRequested);
101     }
102
103     /**
104      * Call this once we know that we need to authenticate
105      */

106     protected void requestAuthentication(HttpServletRequest JavaDoc request,
107             HttpServletResponse JavaDoc response, String JavaDoc pathRequested)
108             throws ServletException JavaDoc, IOException JavaDoc {
109         // Save the critical details of the request into the session map
110
WinstoneRequest actualRequest = null;
111         if (request instanceof WinstoneRequest)
112             actualRequest = (WinstoneRequest) request;
113         else if (request instanceof HttpServletRequestWrapper JavaDoc) {
114             HttpServletRequestWrapper JavaDoc wrapper = (HttpServletRequestWrapper JavaDoc) request;
115             if (wrapper.getRequest() instanceof WinstoneRequest)
116                 actualRequest = (WinstoneRequest) wrapper.getRequest();
117             else
118                 Logger.log(Logger.WARNING, AUTH_RESOURCES,
119                         "FormAuthenticationHandler.CantSetUser", wrapper
120                                 .getRequest().getClass().getName());
121         } else
122             Logger.log(Logger.WARNING, AUTH_RESOURCES,
123                     "FormAuthenticationHandler.CantSetUser", request.getClass()
124                             .getName());
125
126         HttpSession JavaDoc session = actualRequest.getSession(true);
127         session.setAttribute(CACHED_REQUEST, new CachedRequest(actualRequest));
128
129         // Forward on to the login page
130
Logger.log(Logger.FULL_DEBUG, AUTH_RESOURCES,
131                 "FormAuthenticationHandler.GoToLoginPage");
132         javax.servlet.RequestDispatcher JavaDoc rd = request
133                 .getRequestDispatcher(this.loginPage);
134         setNoCache(response);
135         rd.forward(request, response);
136     }
137
138     /**
139      * Check the response - is it a response to the login page ?
140      *
141      * @return A boolean indicating whether to continue with the request or not
142      */

143     protected boolean validatePossibleAuthenticationResponse(
144             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response,
145             String JavaDoc pathRequested) throws ServletException JavaDoc, IOException JavaDoc {
146         // Check if this is a j_security_check uri
147
if (pathRequested.endsWith(FORM_ACTION)) {
148             String JavaDoc username = request.getParameter(FORM_USER);
149             String JavaDoc password = request.getParameter(FORM_PASS);
150
151             // Send to error page if invalid
152
AuthenticationPrincipal principal = this.realm
153                     .authenticateByUsernamePassword(username, password);
154             if (principal == null) {
155                 javax.servlet.RequestDispatcher JavaDoc rd = request
156                         .getRequestDispatcher(this.errorPage);
157                 rd.forward(request, response);
158             }
159
160             // Send to stashed request
161
else {
162                 // Iterate back as far as we can
163
ServletRequest JavaDoc wrapperCheck = request;
164                 while (wrapperCheck instanceof HttpServletRequestWrapper JavaDoc)
165                     wrapperCheck = ((HttpServletRequestWrapper JavaDoc) wrapperCheck)
166                             .getRequest();
167
168                 // Get the stashed request
169
WinstoneRequest actualRequest = null;
170                 if (wrapperCheck instanceof WinstoneRequest) {
171                     actualRequest = (WinstoneRequest) wrapperCheck;
172                     actualRequest.setRemoteUser(principal);
173                 } else
174                     Logger.log(Logger.WARNING, AUTH_RESOURCES,
175                             "FormAuthenticationHandler.CantSetUser",
176                             wrapperCheck.getClass().getName());
177
178                 HttpSession JavaDoc session = request.getSession(true);
179                 String JavaDoc previousLocation = this.loginPage;
180                 CachedRequest cachedRequest = (CachedRequest) session.getAttribute(CACHED_REQUEST);
181                 if ((cachedRequest != null)
182                         && (actualRequest != null)) {
183                     // Repopulate this request from the params we saved
184
cachedRequest.transferContent(actualRequest);
185                     previousLocation = request.getServletPath();
186                     // session.setCachedRequest(null); - commented out so that
187
// refreshes will work
188
} else
189                     Logger.log(Logger.DEBUG, AUTH_RESOURCES,
190                             "FormAuthenticationHandler.NoCachedRequest");
191                 
192                 // do role check, since we don't know that this user has permission
193
if (doRoleCheck(request, response, previousLocation)) {
194                     principal.setAuthType(HttpServletRequest.FORM_AUTH);
195                     session.setAttribute(AUTHENTICATED_USER, principal);
196                     javax.servlet.RequestDispatcher JavaDoc rd = request
197                             .getRequestDispatcher(previousLocation);
198                     rd.forward(request, response);
199                 } else {
200                     javax.servlet.RequestDispatcher JavaDoc rd = request
201                             .getRequestDispatcher(this.errorPage);
202                     rd.forward(request, response);
203                 }
204             }
205             return false;
206         }
207
208         // If it's not a login, get the session, and look up the auth user
209
// variable
210
else {
211             WinstoneRequest actualRequest = null;
212             if (request instanceof WinstoneRequest)
213                 actualRequest = (WinstoneRequest) request;
214             else if (request instanceof HttpServletRequestWrapper JavaDoc) {
215                 HttpServletRequestWrapper JavaDoc wrapper = (HttpServletRequestWrapper JavaDoc) request;
216                 if (wrapper.getRequest() instanceof WinstoneRequest)
217                     actualRequest = (WinstoneRequest) wrapper.getRequest();
218                 else
219                     Logger.log(Logger.WARNING, AUTH_RESOURCES,
220                             "FormAuthenticationHandler.CantSetUser", wrapper
221                                     .getRequest().getClass().getName());
222             } else
223                 Logger.log(Logger.WARNING, AUTH_RESOURCES,
224                         "FormAuthenticationHandler.CantSetUser", request
225                                 .getClass().getName());
226
227             HttpSession JavaDoc session = actualRequest.getSession(false);
228             if (session != null) {
229                 AuthenticationPrincipal authenticatedUser = (AuthenticationPrincipal)
230                         session.getAttribute(AUTHENTICATED_USER);
231                 if (authenticatedUser != null) {
232                     actualRequest.setRemoteUser(authenticatedUser);
233                     Logger.log(Logger.FULL_DEBUG, AUTH_RESOURCES,
234                             "FormAuthenticationHandler.GotUserFromSession");
235                 }
236             }
237             return true;
238         }
239     }
240 }
241
Popular Tags