KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > web > tomcat > security > JBossExtendedSecurityMgrRealm


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;
23
24 import java.io.IOException JavaDoc;
25 import java.security.Principal JavaDoc;
26 import java.security.acl.Group JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Set JavaDoc;
32
33 import javax.management.JMException JavaDoc;
34 import javax.management.MBeanServer JavaDoc;
35 import javax.management.ObjectName JavaDoc;
36 import javax.security.auth.Subject JavaDoc;
37 import javax.security.auth.message.AuthParam;
38 import javax.security.auth.message.AuthStatus;
39 import javax.security.jacc.PolicyContext JavaDoc;
40 import javax.servlet.http.HttpServletResponse JavaDoc;
41
42 import org.apache.catalina.Context;
43 import org.apache.catalina.authenticator.Constants;
44 import org.apache.catalina.connector.Request;
45 import org.apache.catalina.connector.Response;
46 import org.apache.catalina.deploy.LoginConfig;
47 import org.apache.catalina.deploy.SecurityConstraint;
48 import org.apache.catalina.realm.RealmBase;
49 import org.jboss.logging.Logger;
50 import org.jboss.mx.util.MBeanServerLocator;
51 import org.jboss.security.AuthorizationManager;
52 import org.jboss.security.GeneralizedAuthenticationManager;
53 import org.jboss.security.SimplePrincipal;
54 import org.jboss.security.auth.message.HttpServletAuthParam;
55 import org.jboss.security.authorization.AuthorizationContext;
56 import org.jboss.web.tomcat.security.authorization.WebResource;
57
58 //$Id: JBossExtendedSecurityMgrRealm.java 56657 2006-09-08 19:13:03Z anil.saldhana@jboss.com $
59

60 /**
61  * Tomcat security realm that has the request/response messages
62  * available during authentication decisions
63  * @author <a HREF="mailto:Anil.Saldhana@jboss.org">Anil Saldhana</a>
64  * @since May 24, 2006
65  * @version $Revision: 56657 $
66  */

67 public class JBossExtendedSecurityMgrRealm extends JBossSecurityMgrRealm
68 implements ExtendedRealm
69 {
70    private static Logger logger = Logger.getLogger(JBossExtendedSecurityMgrRealm.class);
71    protected ObjectName JavaDoc authenticationManagerService = null;
72    protected ObjectName JavaDoc authorizationManagerService = null;
73    
74    public JBossExtendedSecurityMgrRealm()
75    {
76       try
77       {
78          this.authenticationManagerService = new ObjectName JavaDoc("jboss.security:service=JASPISecurityManager");
79          this.authorizationManagerService = new ObjectName JavaDoc("jboss.security:service=AuthorizationManager");
80       }
81       catch(JMException JavaDoc jme)
82       {
83          log.error("Error in instantiating object names:",jme);
84       }
85    }
86    /**
87     * Allow injection of the object name for the authentication
88     * manager jmx service
89     *
90     * @param oname Object Name
91     */

92    public void setAuthenticationManagerService(String JavaDoc oname)
93    {
94       ObjectName JavaDoc temp = null;
95       try
96       {
97          temp = new ObjectName JavaDoc(oname);
98       }
99       catch(JMException JavaDoc jme)
100       {
101          log.error("Error in setAuthenticationManagerService:",jme);
102       }
103       if(temp != null)
104          this.authenticationManagerService = temp;
105    }
106    
107    /**
108     * Allow injection of the object name for the authorization
109     * manager jmx service
110     *
111     * @param oname Object Name
112     */

113    public void setAuthorizationManagerService(String JavaDoc oname)
114    {
115       ObjectName JavaDoc temp = null;
116       try
117       {
118          temp = new ObjectName JavaDoc(oname);
119       }
120       catch(JMException JavaDoc jme)
121       {
122          log.error("Error in setAuthorizationManagerService:",jme);
123       }
124       if(temp != null)
125          this.authorizationManagerService = temp;
126    }
127    
128    /**
129     * @see ExtendedRealm#authenticate(Request, Response, LoginConfig)
130     */

131    public Principal JavaDoc authenticate(Request request, Response JavaDoc response,
132          LoginConfig config) throws Exception JavaDoc
133    {
134       log.debug("ExtendedSecurityMgrRealm:authenticate");
135       AuthParam authParam = new HttpServletAuthParam(request,response);
136       GeneralizedAuthenticationManager gam = getAuthenticationManager();
137       Subject JavaDoc clientSubject = new Subject JavaDoc();
138       Subject JavaDoc serviceSubject = new Subject JavaDoc();
139       Map JavaDoc sharedState = getSharedState(request,config);
140       AuthStatus status = AuthStatus.FAIL;
141       while(!status.equals(AuthStatus.PROCEED))
142       {
143          status = gam.validateRequest(authParam, clientSubject, serviceSubject, sharedState);
144          if(status.equals(AuthStatus.FAIL))
145             throw new SecurityException JavaDoc("Authentication failed");
146       }
147       Principal JavaDoc authenticatedPrincipal = this.getAuthenticatedPrincipal(clientSubject);
148       return null;
149       /*
150       AuthorizationManager authzManager = getAuthorizationManager();
151       Principal callerPrincipal = getAuthenticationManager().getPrincipal(authenticatedPrincipal);
152       return getCachingPrincipal(authzManager, authenticatedPrincipal, callerPrincipal, null, clientSubject);
153       */

154    }
155    
156    /**
157     * @see RealmBase#hasResourcePermission(org.apache.catalina.connector.Request,
158     * org.apache.catalina.connector.Response, org.apache.catalina.deploy.SecurityConstraint[], org.apache.catalina.Context)
159     */

160    public boolean hasResourcePermission(Request request, Response JavaDoc response,
161          SecurityConstraint[] constraints, Context JavaDoc context) throws IOException JavaDoc
162    {
163       boolean isAuthorized = super.hasResourcePermission(request, response,
164                                    constraints, context);
165       log.debug("Super class has authorized="+isAuthorized);
166       AuthorizationManager authzManager = null;
167       try
168       {
169          authzManager = this.getAuthorizationManager();
170       }
171       catch(Exception JavaDoc e)
172       {
173          log.error("Error obtaining Authorization Manager:",e);
174       }
175       
176       final HashMap JavaDoc map = new HashMap JavaDoc();
177       map.put("catalina.request",request);
178       map.put("catalina.constraints",constraints);
179       map.put("catalina.context", context);
180       map.put("authorizationManager",authzManager);
181       WebResource resource = new WebResource(map);
182       try
183       {
184          int check = authzManager.authorize(resource);
185          isAuthorized = (check == AuthorizationContext.PERMIT);
186       }
187       catch (Exception JavaDoc e)
188       {
189          isAuthorized = false;
190          log.error("Error in authorization:",e);
191       }
192       log.debug("Final Authorization Result="+isAuthorized);
193       if(!isAuthorized)
194       {
195         ((HttpServletResponse JavaDoc)response).setStatus(HttpServletResponse.SC_FORBIDDEN);
196       }
197       return isAuthorized;
198    }
199    
200    private Map JavaDoc getSharedState(Request request, LoginConfig config)
201    {
202       Map JavaDoc map = new HashMap JavaDoc();
203       if(config.getAuthMethod().equals(Constants.FORM_METHOD))
204       {
205          map.put("javax.security.auth.login.name",
206                getPrincipal(request.getParameter(Constants.FORM_USERNAME)));
207          map.put("javax.security.auth.login.password",
208                request.getParameter(Constants.FORM_PASSWORD));
209       }
210       return map;
211    }
212    
213    /**
214     * Create the session principal tomcat will cache to avoid callouts to this
215     * Realm.
216     *
217     * @param authzManager - the AuthorizationManager
218     * @param authPrincipal - the principal used for authentication and stored in
219     * the security manager cache
220     * @param callerPrincipal - the possibly different caller principal
221     * representation of the authenticated principal
222     * @param credential - the credential used for authentication
223     * @return the tomcat session principal wrapper
224     */

225    protected Principal JavaDoc getCachingPrincipal(AuthorizationManager authzManager,
226       Principal JavaDoc authPrincipal, Principal JavaDoc callerPrincipal, Object JavaDoc credential,
227       Subject JavaDoc subject)
228    {
229       // Cache the user roles in the principal
230
Set JavaDoc userRoles = authzManager.getUserRoles(authPrincipal);
231       ArrayList JavaDoc roles = new ArrayList JavaDoc();
232       if (userRoles != null)
233       {
234          Iterator JavaDoc iterator = userRoles.iterator();
235          while (iterator.hasNext())
236          {
237             Principal JavaDoc role = (Principal JavaDoc) iterator.next();
238             roles.add(role.getName());
239          }
240       }
241       JBossGenericPrincipal gp = new JBossGenericPrincipal(this, subject,
242          authPrincipal, callerPrincipal, credential, roles, userRoles);
243       return gp;
244    }
245    
246    private Principal JavaDoc getAuthenticatedPrincipal(Subject JavaDoc subject)
247    {
248       if(subject == null)
249          throw new IllegalArgumentException JavaDoc("subject is null");
250       Principal JavaDoc authPrincipal = null;
251       Iterator JavaDoc iter = subject.getPrincipals(SimplePrincipal.class).iterator();
252       while(iter.hasNext())
253       {
254          authPrincipal = (Principal JavaDoc)iter.next();
255          if(authPrincipal instanceof Group JavaDoc == false)
256             break;
257       }
258       return authPrincipal;
259    }
260    
261    private GeneralizedAuthenticationManager getAuthenticationManager()
262    throws Exception JavaDoc
263    {
264       String JavaDoc contextID = PolicyContext.getContextID();
265       MBeanServer JavaDoc server = MBeanServerLocator.locateJBoss();
266       String JavaDoc securityDomain = (String JavaDoc)server.invoke(this.authenticationManagerService,
267             "getSecurityDomain",
268             new String JavaDoc[]{contextID}, new String JavaDoc[]{"java.lang.String"});
269       return (GeneralizedAuthenticationManager)server.invoke(this.authenticationManagerService,
270             "getSecurityManager",
271             new String JavaDoc[]{securityDomain}, new String JavaDoc[]{"java.lang.String"});
272    }
273    
274    private AuthorizationManager getAuthorizationManager() throws Exception JavaDoc
275    {
276       MBeanServer JavaDoc server = MBeanServerLocator.locateJBoss();
277       GeneralizedAuthenticationManager gam = this.getAuthenticationManager();
278       String JavaDoc securityDomain = gam.getSecurityDomain();
279       return (AuthorizationManager)server.invoke(this.authorizationManagerService,
280             "getAuthorizationManager",
281             new String JavaDoc[]{securityDomain}, new String JavaDoc[]{"java.lang.String"});
282    }
283 }
284
Popular Tags