KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > web > tomcat > security > authenticators > JASPIFormAuthenticator


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.web.tomcat.security.authenticators;
23
24 import java.io.IOException JavaDoc;
25 import java.security.Principal JavaDoc;
26
27 import javax.servlet.http.HttpServletResponse JavaDoc;
28
29 import org.apache.catalina.Session;
30 import org.apache.catalina.authenticator.Constants;
31 import org.apache.catalina.authenticator.FormAuthenticator;
32 import org.apache.catalina.connector.Request;
33 import org.apache.catalina.connector.Response;
34 import org.apache.catalina.deploy.LoginConfig;
35 import org.apache.tomcat.util.buf.CharChunk;
36 import org.apache.tomcat.util.buf.MessageBytes;
37 import org.jboss.logging.Logger;
38 import org.jboss.web.tomcat.security.ExtendedRealm;
39
40 //$Id: JASPIFormAuthenticator.java 45301 2006-05-26 21:31:04Z asaldhana $
41

42 /**
43  * Form Authenticator that delegates to an extended Realm
44  * @author <a HREF="mailto:Anil.Saldhana@jboss.org">Anil Saldhana</a>
45  * @since May 24, 2006
46  * @version $Revision: 45301 $
47  */

48 public class JASPIFormAuthenticator extends FormAuthenticator
49 {
50    private static Logger log = Logger.getLogger(JASPIFormAuthenticator.class);
51    
52    public JASPIFormAuthenticator()
53    {
54    }
55
56    /**
57     * @see FormAuthenticator#authenticate(org.apache.catalina.connector.Request,
58     * org.apache.catalina.connector.Response, org.apache.catalina.deploy.LoginConfig)
59     */

60    public boolean authenticate(Request request, Response JavaDoc response,
61          LoginConfig config) throws IOException JavaDoc
62    {
63       //References to objects we will need later
64
Session session = null;
65
66       // Have we already authenticated someone?
67
Principal JavaDoc principal = request.getUserPrincipal();
68       String JavaDoc ssoId = (String JavaDoc) request.getNote(Constants.REQ_SSOID_NOTE);
69       if (principal != null) {
70           if (log.isDebugEnabled())
71               log.debug("Already authenticated '" +
72                   principal.getName() + "'");
73           // Associate the session with any existing SSO session
74
if (ssoId != null)
75               associate(ssoId, request.getSessionInternal(true));
76           return (true);
77       }
78
79       // Is there an SSO session against which we can try to reauthenticate?
80
if (ssoId != null) {
81           if (log.isDebugEnabled())
82               log.debug("SSO Id " + ssoId + " set; attempting " +
83                         "reauthentication");
84           // Try to reauthenticate using data cached by SSO. If this fails,
85
// either the original SSO logon was of DIGEST or SSL (which
86
// we can't reauthenticate ourselves because there is no
87
// cached username and password), or the realm denied
88
// the user's reauthentication for some reason.
89
// In either case we have to prompt the user for a logon */
90
if (reauthenticateFromSSO(ssoId, request))
91               return true;
92       }
93
94       // Have we authenticated this user before but have caching disabled?
95
if (!cache) {
96           session = request.getSessionInternal(true);
97           if (log.isDebugEnabled())
98               log.debug("Checking for reauthenticate in session " + session);
99           String JavaDoc username =
100               (String JavaDoc) session.getNote(Constants.SESS_USERNAME_NOTE);
101           String JavaDoc password =
102               (String JavaDoc) session.getNote(Constants.SESS_PASSWORD_NOTE);
103           if ((username != null) && (password != null)) {
104               if (log.isDebugEnabled())
105                   log.debug("Reauthenticating username '" + username + "'");
106              // principal =
107
// context.getRealm().authenticate(username, password);
108
ExtendedRealm realm = (ExtendedRealm)context.getRealm();
109               try
110               {
111                  principal = realm.authenticate(request, response, config);
112               }
113               catch(Exception JavaDoc e)
114               {
115                  log.error("Exception in realm authenticate:",e);
116               }
117               if (principal != null) {
118                   session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
119                   if (!matchRequest(request)) {
120                       register(request, response, principal,
121                                Constants.FORM_METHOD,
122                                username, password);
123                       return (true);
124                   }
125               }
126               if (log.isDebugEnabled())
127                   log.debug("Reauthentication failed, proceed normally");
128           }
129       }
130
131       // Is this the re-submit of the original request URI after successful
132
// authentication? If so, forward the *original* request instead.
133
if (matchRequest(request)) {
134           session = request.getSessionInternal(true);
135           if (log.isDebugEnabled())
136               log.debug("Restore request from session '"
137                         + session.getIdInternal()
138                         + "'");
139           principal = (Principal JavaDoc)
140               session.getNote(Constants.FORM_PRINCIPAL_NOTE);
141           register(request, response, principal, Constants.FORM_METHOD,
142                    (String JavaDoc) session.getNote(Constants.SESS_USERNAME_NOTE),
143                    (String JavaDoc) session.getNote(Constants.SESS_PASSWORD_NOTE));
144           // If we're caching principals we no longer need the username
145
// and password in the session, so remove them
146
if (cache) {
147               session.removeNote(Constants.SESS_USERNAME_NOTE);
148               session.removeNote(Constants.SESS_PASSWORD_NOTE);
149           }
150           if (restoreRequest(request, session)) {
151               if (log.isDebugEnabled())
152                   log.debug("Proceed to restored request");
153               return (true);
154           } else {
155               if (log.isDebugEnabled())
156                   log.debug("Restore of original request failed");
157               response.sendError(HttpServletResponse.SC_BAD_REQUEST);
158               return (false);
159           }
160       }
161
162       // Acquire references to objects we will need to evaluate
163
MessageBytes uriMB = MessageBytes.newInstance();
164       CharChunk uriCC = uriMB.getCharChunk();
165       uriCC.setLimit(-1);
166       String JavaDoc contextPath = request.getContextPath();
167       String JavaDoc requestURI = request.getDecodedRequestURI();
168       response.setContext(request.getContext());
169
170       // Is this the action request from the login page?
171
boolean loginAction =
172           requestURI.startsWith(contextPath) &&
173           requestURI.endsWith(Constants.FORM_ACTION);
174
175       // No -- Save this request and redirect to the form login page
176
if (!loginAction) {
177           session = request.getSessionInternal(true);
178           if (log.isDebugEnabled())
179               log.debug("Save request in session '" + session.getIdInternal() + "'");
180           try {
181               saveRequest(request, session);
182           } catch (IOException JavaDoc ioe) {
183               log.debug("Request body too big to save during authentication");
184               response.sendError(HttpServletResponse.SC_FORBIDDEN,
185                       sm.getString("authenticator.requestBodyTooBig"));
186               return (false);
187           }
188           forwardToLoginPage(request, response, config);
189           return (false);
190       }
191
192       // Yes -- Validate the specified credentials and redirect
193
// to the error page if they are not correct
194
ExtendedRealm realm = (ExtendedRealm)context.getRealm();
195       if (characterEncoding != null) {
196           request.setCharacterEncoding(characterEncoding);
197       }
198       String JavaDoc username = request.getParameter(Constants.FORM_USERNAME);
199       String JavaDoc password = request.getParameter(Constants.FORM_PASSWORD);
200       if (log.isDebugEnabled())
201           log.debug("Authenticating username '" + username + "'");
202       //principal = realm.authenticate(username, password);
203
try
204       {
205          principal = realm.authenticate(request, response, config);
206       }
207       catch(Exception JavaDoc e)
208       {
209          log.error("Exception in realm authenticate:",e);
210       }
211       
212       if (principal == null) {
213           forwardToErrorPage(request, response, config);
214           return (false);
215       }
216
217       if (log.isDebugEnabled())
218           log.debug("Authentication of '" + username + "' was successful");
219
220       if (session == null)
221           session = request.getSessionInternal(false);
222       if (session == null) {
223           if (containerLog.isDebugEnabled())
224               containerLog.debug
225                   ("User took so long to log on the session expired");
226           response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
227                              sm.getString("authenticator.sessionExpired"));
228           return (false);
229       }
230
231       // Save the authenticated Principal in our session
232
session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
233
234       // Save the username and password as well
235
session.setNote(Constants.SESS_USERNAME_NOTE, username);
236       session.setNote(Constants.SESS_PASSWORD_NOTE, password);
237
238       // Redirect the user to the original request URI (which will cause
239
// the original request to be restored)
240
requestURI = savedRequestURL(session);
241       if (log.isDebugEnabled())
242           log.debug("Redirecting to original '" + requestURI + "'");
243       if (requestURI == null)
244           response.sendError(HttpServletResponse.SC_BAD_REQUEST,
245                              sm.getString("authenticator.formlogin"));
246       else
247           response.sendRedirect(response.encodeRedirectURL(requestURI));
248       return (false);
249    }
250 }
251
Popular Tags