KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > server > security > JaasAuthenticator


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  * Free SoftwareFoundation, Inc.
23  * 59 Temple Place, Suite 330
24  * Boston, MA 02111-1307 USA
25  *
26  * @author Scott Ferguson
27  */

28
29 package com.caucho.server.security;
30
31 import com.caucho.config.Config;
32 import com.caucho.config.ConfigException;
33 import com.caucho.config.types.InitParam;
34
35 import javax.annotation.PostConstruct;
36 import javax.security.auth.Subject JavaDoc;
37 import javax.security.auth.callback.Callback JavaDoc;
38 import javax.security.auth.callback.CallbackHandler JavaDoc;
39 import javax.security.auth.callback.NameCallback JavaDoc;
40 import javax.security.auth.callback.PasswordCallback JavaDoc;
41 import javax.security.auth.callback.UnsupportedCallbackException JavaDoc;
42 import javax.security.auth.login.LoginException JavaDoc;
43 import javax.security.auth.spi.LoginModule JavaDoc;
44 import javax.servlet.ServletContext JavaDoc;
45 import javax.servlet.ServletException JavaDoc;
46 import javax.servlet.http.HttpServletRequest JavaDoc;
47 import javax.servlet.http.HttpServletResponse JavaDoc;
48 import java.io.IOException JavaDoc;
49 import java.lang.reflect.Method JavaDoc;
50 import java.security.Principal JavaDoc;
51 import java.util.HashMap JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.Set JavaDoc;
54 import java.util.logging.Level JavaDoc;
55
56 /**
57  * The JAAS authenticator uses an underlying JAAS.
58  */

59 public class JaasAuthenticator extends AbstractAuthenticator {
60   private Class JavaDoc _loginModuleClass;
61
62   private HashMap JavaDoc<String JavaDoc,String JavaDoc> _options =
63     new HashMap JavaDoc<String JavaDoc,String JavaDoc>();
64
65   /**
66    * Sets the JAAS spi login module class.
67    */

68   public void setLoginModule(Class JavaDoc loginModuleClass)
69     throws ConfigException
70   {
71     _loginModuleClass = loginModuleClass;
72
73     Config.checkCanInstantiate(loginModuleClass);
74
75     if (! LoginModule JavaDoc.class.isAssignableFrom(loginModuleClass))
76       throw new ConfigException(L.l("`{0}' must implement javax.security.auth.spi.LoginModule",
77                     loginModuleClass.getName()));
78   }
79
80   public void setInitParam(InitParam init)
81   {
82     _options.putAll(init.getParameters());
83   }
84
85   public void setOptions(InitParam init)
86   {
87     _options.putAll(init.getParameters());
88   }
89
90   /**
91    * Initialize the authenticator.
92    */

93   @PostConstruct
94   public synchronized void init()
95     throws ServletException JavaDoc
96   {
97     super.init();
98     
99     if (_loginModuleClass == null)
100       throw new ServletException JavaDoc(L.l("JaasAuthenticator requires login-module"));
101   }
102   
103   /**
104    * Authenticate (login) the user.
105    */

106   protected Principal JavaDoc loginImpl(HttpServletRequest JavaDoc request,
107                                 HttpServletResponse JavaDoc response,
108                                 ServletContext JavaDoc application,
109                                 String JavaDoc userName, String JavaDoc password)
110     throws ServletException JavaDoc
111   {
112     try {
113       LoginModule JavaDoc login = (LoginModule JavaDoc) _loginModuleClass.newInstance();
114       Subject JavaDoc subject = new Subject JavaDoc();
115
116       HashMap JavaDoc<String JavaDoc,String JavaDoc> state = new HashMap JavaDoc<String JavaDoc,String JavaDoc>();
117
118       state.put("javax.security.auth.login.name", userName);
119       state.put("javax.security.auth.login.password", password);
120
121       login.initialize(subject,
122                new Handler JavaDoc(userName, password),
123                state, _options);
124
125       try {
126     login.login();
127       } catch (Exception JavaDoc e) {
128     login.abort();
129       }
130
131       login.commit();
132
133       Set JavaDoc principals = subject.getPrincipals();
134
135       if (principals == null || principals.size() == 0)
136     return null;
137
138       Iterator JavaDoc iter = principals.iterator();
139       if (iter.hasNext())
140     return (Principal JavaDoc) iter.next();
141
142       return null;
143     } catch (LoginException JavaDoc e) {
144       log.log(Level.FINE, e.toString(), e);
145
146       return null;
147     } catch (Throwable JavaDoc e) {
148       log.log(Level.WARNING, e.toString(), e);
149       
150       return null;
151     }
152   }
153
154   /**
155    * Returns true if the user plays the named role.
156    *
157    * @param request the servlet request
158    * @param user the user to test
159    * @param role the role to test
160    */

161   public boolean isUserInRole(HttpServletRequest JavaDoc request,
162                               HttpServletResponse JavaDoc response,
163                               ServletContext JavaDoc application,
164                               Principal JavaDoc principal, String JavaDoc role)
165     throws ServletException JavaDoc
166   {
167     if (principal == null)
168       return false;
169
170     Class JavaDoc principalCl = principal.getClass();
171     
172     try {
173       Method JavaDoc isUserInRole = principalCl.getMethod("isUserInRole",
174                           new Class JavaDoc[] { String JavaDoc.class });
175
176       if (isUserInRole != null)
177     return Boolean.TRUE.equals(isUserInRole.invoke(principal, role));
178     } catch (Throwable JavaDoc e) {
179       log.log(Level.FINER, e.toString(), e);
180     }
181       
182     try {
183       Method JavaDoc getRoles = principalCl.getMethod("getRoles", new Class JavaDoc[] { });
184     
185       if (getRoles != null) {
186     Set JavaDoc roles = (Set JavaDoc) getRoles.invoke(principal);
187
188     return roles != null && roles.contains(role);
189       }
190     } catch (Throwable JavaDoc e) {
191       log.log(Level.FINER, e.toString(), e);
192     }
193       
194     return principal != null;
195   }
196
197   static class Handler implements CallbackHandler JavaDoc {
198     private String JavaDoc _userName;
199     private String JavaDoc _password;
200
201     Handler(String JavaDoc userName, String JavaDoc password)
202     {
203       _userName = userName;
204       _password = password;
205     }
206     
207     public void handle(Callback JavaDoc []callbacks)
208       throws IOException JavaDoc, UnsupportedCallbackException JavaDoc
209     {
210       for (int i = 0; i < callbacks.length; i++) {
211     Callback JavaDoc cb = callbacks[i];
212
213     if (cb instanceof NameCallback JavaDoc) {
214       NameCallback JavaDoc name = (NameCallback JavaDoc) cb;
215
216       name.setName(_userName);
217     }
218     else if (cb instanceof PasswordCallback JavaDoc) {
219       PasswordCallback JavaDoc password = (PasswordCallback JavaDoc) cb;
220
221       password.setPassword(_password.toCharArray());
222     }
223       }
224     }
225   }
226 }
227
Popular Tags