KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > security > AbstractHTTPAuthenticationModule


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.security;
21
22 import java.io.IOException JavaDoc;
23
24 import javax.servlet.http.HttpServletRequest JavaDoc;
25 import javax.servlet.http.HttpServletResponse JavaDoc;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29 import org.apache.struts.action.ActionForward;
30 import org.apache.struts.action.ActionMapping;
31
32 import com.maverick.crypto.encoders.Base64;
33 import com.sslexplorer.core.RequestParameterMap;
34 import com.sslexplorer.core.UserDatabaseManager;
35
36 /**
37  * Abstract extension of {@link com.sslexplorer.security.AbstractPasswordAuthenticationModule}
38  * that is suitable for authentication modules that use HTTP authentication. To
39  * date this includes the HTTP authentication module and WebDAV.
40  *
41  * @author Brett Smith <brett@3sp.com>
42  */

43 public abstract class AbstractHTTPAuthenticationModule extends AbstractPasswordAuthenticationModule {
44
45     final static Log log = LogFactory.getLog(AbstractHTTPAuthenticationModule.class);
46     
47     // Protected instance variables
48

49     protected String JavaDoc defaultRealm;
50
51     /**
52      * Constructor.
53      *
54      * @param module module
55      * @param required required
56      * @param defaultRealm default authentication realm
57      */

58     public AbstractHTTPAuthenticationModule(String JavaDoc module, boolean required, String JavaDoc defaultRealm) {
59         super(module, required);
60         this.defaultRealm = defaultRealm;
61     }
62
63     /*
64      * (non-Javadoc)
65      *
66      * @see com.sslexplorer.security.AuthenticationModule#startAuthentication(javax.servlet.http.HttpServletRequest,
67      * javax.servlet.http.HttpServletResponse)
68      */

69     public ActionForward startAuthentication(ActionMapping mapping, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
70                     throws SecurityErrorException {
71         // If the authentication request has already been sent then just
72
// continue to logon
73
if (request.getParameter("auth") != null) {
74             if (request.getSession().getAttribute(Constants.AUTH_SENT) == null) {
75                 boolean hasAuthorization = request.getHeader("Authorization") != null
76                                 && Boolean.TRUE.equals(request.getSession().getAttribute(Constants.AUTH_SENT));
77                 try {
78                     if (!hasAuthorization) {
79                         sendAuthorizationError(request, response, defaultRealm);
80                         return null;
81                     }
82                 } catch (Exception JavaDoc e) {
83                     throw new SecurityErrorException(SecurityErrorException.INTERNAL_ERROR, e);
84                 }
85             }
86             return new ActionForward("/logon.do", true);
87         } else {
88             return mapping.findForward("display");
89         }
90     }
91
92     /* (non-Javadoc)
93      * @see com.sslexplorer.security.AbstractPasswordAuthenticationModule#authenticate(javax.servlet.http.HttpServletRequest, com.sslexplorer.core.RequestParameterMap)
94      */

95     public Credentials authenticate(HttpServletRequest JavaDoc request, RequestParameterMap parameterMap)
96                     throws InvalidLoginCredentialsException, SecurityErrorException, AccountLockedException, InputRequiredException {
97
98         try {
99             String JavaDoc authorization = request.getHeader("Authorization");
100             if (authorization == null) {
101                 throw new SecurityErrorException(SecurityErrorException.INTERNAL_ERROR, "No credentials supplied.");
102             }
103
104             request.getSession().removeAttribute(Constants.AUTH_SENT);
105
106             int idx = authorization.indexOf(' ');
107
108             if (idx == -1 || idx == authorization.length() - 1) {
109                 throw new InvalidLoginCredentialsException("No Authorization provided.");
110             }
111
112             // Authenticate the user
113
String JavaDoc method = authorization.substring(0, idx);
114
115             if (!method.equalsIgnoreCase("basic")) {
116                 throw new InvalidLoginCredentialsException("Only HTTP Basic authentication is currently supported.");
117             }
118
119             // Extract the credentials - should be ticket:tunnel
120
String JavaDoc encoded = authorization.substring(idx + 1);
121             String JavaDoc httpCredentials = new String JavaDoc(Base64.decode(encoded));
122
123             idx = httpCredentials.indexOf(':');
124
125             if (idx == 0 || idx == -1 || idx == httpCredentials.length() - 1) {
126                 throw new InvalidLoginCredentialsException("Invalid authorization.");
127             }
128
129             // Get the user credentials
130
String JavaDoc username = httpCredentials.substring(0, idx);
131             String JavaDoc password = httpCredentials.substring(idx + 1);
132             
133             // See if there is a realm in the username
134
idx = username.indexOf('\\');
135             UserDatabase udb = null;
136             if(idx != -1) {
137                 String JavaDoc realmName = username.substring(0, idx);
138                 try {
139                     udb = UserDatabaseManager.getInstance().getUserDatabase(realmName);
140                     username = username.substring(idx + 1);
141                 }
142                 catch(Exception JavaDoc e) {
143                 }
144             } else {
145                 udb = UserDatabaseManager.getInstance().getDefaultUserDatabase();
146             }
147
148             try {
149                 User account = udb.getAccount(username);
150                 scheme.setUser(account);
151                 if (password == null || password.equals("")) {
152                     throw new InvalidLoginCredentialsException("No password supplied.");
153                 }
154                 account = doLogon(username, password, scheme.getUser().getRealm().getResourceName());
155             } catch (InvalidLoginCredentialsException ilce) {
156                 throw ilce;
157             } catch (UserNotFoundException unfe) {
158                 throw new InvalidLoginCredentialsException();
159             } catch (Exception JavaDoc e) {
160                 throw new SecurityErrorException(SecurityErrorException.INTERNAL_ERROR, e);
161             }
162             credentials = new PasswordCredentials(username, password.toCharArray());
163         } finally {
164             request.getSession().removeAttribute(Constants.AUTH_SENT);
165         }
166         return credentials;
167     }
168
169     /**
170      * @param request
171      * @param response
172      * @param realm
173      * @throws IOException
174      */

175     public static void sendAuthorizationError(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc realm)
176                     throws IOException JavaDoc {
177         if (log.isInfoEnabled())
178             log.info("Sending auth request for realm " + realm);
179         response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
180         response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
181         request.getSession().setAttribute(Constants.AUTH_SENT, Boolean.TRUE);
182     }
183
184 }
Popular Tags