KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > security > servlets > DeepCopySubjectServlet


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.test.security.servlets;
23
24 import java.io.IOException JavaDoc;
25 import java.security.Principal JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.Set JavaDoc;
30
31 import javax.management.JMException JavaDoc;
32 import javax.management.MBeanServer JavaDoc;
33 import javax.management.ObjectName JavaDoc;
34 import javax.naming.InitialContext JavaDoc;
35 import javax.security.auth.Subject JavaDoc;
36 import javax.security.auth.callback.CallbackHandler JavaDoc;
37 import javax.security.auth.login.LoginException JavaDoc;
38 import javax.security.auth.spi.LoginModule JavaDoc;
39 import javax.security.jacc.PolicyContext JavaDoc;
40 import javax.servlet.ServletException JavaDoc;
41 import javax.servlet.http.HttpServlet JavaDoc;
42 import javax.servlet.http.HttpServletRequest JavaDoc;
43 import javax.servlet.http.HttpServletResponse JavaDoc;
44
45 import org.jboss.mx.util.MBeanServerLocator;
46 import org.jboss.security.SimpleGroup;
47 import org.jboss.security.SimplePrincipal;
48 import org.jboss.security.SubjectSecurityManager;
49
50 //$Id: DeepCopySubjectServlet.java 46076 2006-07-05 18:59:22Z asaldhana $
51

52 /**
53  * JBAS-2657: Add option to deep copy the authenticated subject sets
54  * Tests the Deep Copy capability for the subject sets
55  * @author <a HREF="mailto:Anil.Saldhana@jboss.org">Anil Saldhana</a>
56  * @since Apr 5, 2006
57  * @version $Revision: 46076 $
58  */

59 public class DeepCopySubjectServlet extends HttpServlet JavaDoc
60 {
61    /** The serialVersionUID */
62    private static final long serialVersionUID = -277574499645473218L;
63    
64    private Principal JavaDoc anilPrincipal = TestPrincipal.getInstance();
65    private Principal JavaDoc scottPrincipal = new SimplePrincipal("scott");
66    
67    protected void service(HttpServletRequest JavaDoc request,
68                           HttpServletResponse JavaDoc response)
69    throws ServletException JavaDoc, IOException JavaDoc
70    {
71       boolean hashCodeShouldMatch = false; //Deep Cloning case
72

73       int hashCodeOfAnilPrincipal = System.identityHashCode(anilPrincipal);
74       
75       InitialContext JavaDoc context;
76       try
77       {
78          String JavaDoc param = request.getParameter("shouldMatch");
79          log("param="+param);
80          if(param == null || param.length() == 0)
81             param = "true";
82          hashCodeShouldMatch = param.equals("true");
83          
84          log("hashCodeShouldMatch="+hashCodeShouldMatch);
85          //Flush the Cache - this should not have any adverse effect on the testSubject
86
flushAuthenticationCache("deepcopy", anilPrincipal);
87          context = new InitialContext JavaDoc();
88          SubjectSecurityManager manager = (SubjectSecurityManager)context.lookup("java:comp/env/security/securityMgr");
89          Subject JavaDoc testSubject = new Subject JavaDoc();
90          //Do a validation so that the subject gets added to the cache for the test principal
91
log("isValid="+manager.isValid(scottPrincipal,"echoman", testSubject));
92          Subject JavaDoc authSubject = this.getAuthenticatedSubject(manager);
93          log("AuthenticatedSubject["+authSubject+"]");
94          log("CopiedSubject["+testSubject+"]");
95          //Flush the Cache - this should not have any adverse effect on the testSubject
96
flushAuthenticationCache("deepcopy", anilPrincipal);
97          authSubject = this.getAuthenticatedSubject(manager);
98          log("AuthenticatedSubject after flush["+authSubject+"]");
99          log("CopiedSubject after flush["+testSubject+"]");
100          validateSubject(testSubject, hashCodeShouldMatch, hashCodeOfAnilPrincipal);
101       }
102       catch (Exception JavaDoc e)
103       {
104          throw new ServletException JavaDoc(e);
105       }
106    }
107    
108    private Subject JavaDoc getAuthenticatedSubject(SubjectSecurityManager mgr)
109    throws Exception JavaDoc
110    {
111       //First get the JACC Subject
112
String JavaDoc SUBJECT_CONTEXT_KEY = "javax.security.auth.Subject.container";
113       Subject JavaDoc subject = (Subject JavaDoc) PolicyContext.getContext(SUBJECT_CONTEXT_KEY);
114          
115       //Fallback
116
if(subject == null && mgr != null)
117       {
118          subject = mgr.getActiveSubject();
119       }
120       return subject;
121    }
122    
123    /**
124     * Validate that the subject contains the TestPrincipal and based on the
125     * passed parameter hashCodeShouldMatch, it will check the hashcode
126     * of the object to match with the one that was originally placed in the
127     * subject
128     *
129     * @param ts Subject to Test
130     * @param hashCodeShouldMatch Whether identityHashCode should match
131     * @param hashCodeValueToCheck identity hashcode of the principal inserted in subject
132     */

133    private void validateSubject(Subject JavaDoc ts, boolean hashCodeShouldMatch,
134          int hashCodeValueToCheck)
135    {
136      boolean anilFound = false;
137      
138      Set JavaDoc principalSet = ts.getPrincipals();
139      if(principalSet == null || principalSet.isEmpty())
140         throw new RuntimeException JavaDoc("Principal Set is null");
141      Iterator JavaDoc iter = principalSet.iterator();
142      while(iter.hasNext())
143      {
144         Principal JavaDoc p = (Principal JavaDoc)iter.next();
145         if(p instanceof TestPrincipal)
146         {
147            verifyTestPrincipal(p,hashCodeShouldMatch,hashCodeValueToCheck);
148            anilFound = true;
149         }
150      }
151      if(!anilFound)
152         throw new RuntimeException JavaDoc("Test Principal not found");
153    }
154    
155    /**
156     * Validate theTestPrincipal based on the
157     * passed parameters hashCodeShouldMatch
158     * @see #validateSubject(Subject, boolean, int)
159     * @param p Principal to Test
160     * @param hashCodeShouldMatch Whether identityHashCode should match
161     * @param hashCodeValueToCheck identity hashcode of the principal inserted in subject
162     */

163    private void verifyTestPrincipal(Principal JavaDoc p, boolean hashCodeShouldMatch,
164          int hashCodeValueToCheck)
165    {
166       TestPrincipal tp = (TestPrincipal)p;
167       int newHashCode = System.identityHashCode(tp);
168       log("[hashCodeShouldMatch="+hashCodeShouldMatch+"::hashCodeValueToCheck="+ hashCodeValueToCheck
169             + "::HashCode of TestPrincipal from copied subject="+ newHashCode+"]");
170       if(hashCodeShouldMatch)
171       {
172          if(hashCodeValueToCheck != newHashCode)
173             throw new RuntimeException JavaDoc("HashCodes of the TestPrincipal do not match");
174       }else
175       {
176          if(hashCodeValueToCheck == newHashCode)
177             throw new RuntimeException JavaDoc("HashCodes of the TestPrincipal are matching");
178       }
179       Map JavaDoc map = tp.getMap();
180       if(map == null || map.isEmpty())
181          throw new RuntimeException JavaDoc("Map is null");
182       String JavaDoc value = (String JavaDoc)map.get("testKey");
183       if(value == null)
184          throw new RuntimeException JavaDoc("Value is null");
185       if(!value.equals("testValue"))
186          throw new RuntimeException JavaDoc("Value is not equal to testValue");
187    }
188    
189    /**
190     * Given the security domain and the Principal,
191     * flush the authentication cache
192     *
193     * @param principal
194     * @throws JMException
195     */

196    private void flushAuthenticationCache(String JavaDoc domain, Principal JavaDoc principal) throws JMException JavaDoc
197    {
198       MBeanServer JavaDoc server = MBeanServerLocator.locateJBoss();
199       ObjectName JavaDoc on = new ObjectName JavaDoc("jboss.security:service=JaasSecurityManager");
200       Object JavaDoc[] obj = new Object JavaDoc[] {domain, principal};
201       String JavaDoc[] sig = new String JavaDoc[]{"java.lang.String", "java.security.Principal"};
202       
203       //Flush the Authentication Cache
204
server.invoke(on,"flushAuthenticationCache", obj, sig);
205    }
206    
207    /**
208     *
209     * A TestLoginModule.
210     * All it does is it inserts a TestPrincipal that is mutable into the
211     * subject
212     * @author <a HREF="anil.saldhana@jboss.com">Anil Saldhana</a>
213     * @version $Revision: 46076 $
214     */

215    public static class TestLoginModule implements LoginModule JavaDoc
216    {
217       public TestLoginModule()
218       {
219          super();
220       }
221
222       public void initialize(Subject JavaDoc subject, CallbackHandler JavaDoc callbackHandler,
223             Map JavaDoc sharedState, Map JavaDoc options)
224       {
225          TestPrincipal tp = TestPrincipal.getInstance();
226          if(subject != null)
227          {
228             subject.getPrincipals().add(tp);
229          }
230             
231          SimpleGroup sg = new SimpleGroup("Roles");
232          sg.addMember(new SimplePrincipal("Echo"));
233          subject.getPrincipals().add(sg);
234          SimpleGroup cg = new SimpleGroup("CallerPrincipal");
235          cg.addMember(tp);
236          subject.getPrincipals().add(cg);
237       }
238
239       public boolean login() throws LoginException JavaDoc
240       {
241           return true;
242       }
243
244       public boolean commit() throws LoginException JavaDoc
245       {
246           return true;
247       }
248
249       public boolean abort() throws LoginException JavaDoc
250       {
251           return true;
252       }
253
254       public boolean logout() throws LoginException JavaDoc
255       {
256          return true;
257       }
258    }
259    
260    /**
261     *
262     * A Mutable TestPrincipal.
263     *
264     * @author <a HREF="anil.saldhana@jboss.com">Anil Saldhana</a>
265     * @version $Revision: 46076 $
266     */

267    public static class TestPrincipal extends SimplePrincipal implements Cloneable JavaDoc
268    {
269       /** The serialVersionUID */
270       private static final long serialVersionUID = -6160570085301760185L;
271       
272       private HashMap JavaDoc map = new HashMap JavaDoc();
273  
274       private static TestPrincipal _instance = new TestPrincipal("anil");
275       
276       public static TestPrincipal getInstance()
277       {
278          return _instance;
279       }
280       
281       public TestPrincipal(String JavaDoc name)
282       {
283          super(name);
284          map.put("testKey","testValue");
285       }
286       
287       public Map JavaDoc getMap()
288       {
289          return map;
290       }
291       
292       public Object JavaDoc clone() throws CloneNotSupportedException JavaDoc
293       {
294          TestPrincipal tp = (TestPrincipal)super.clone();
295          tp.map = (HashMap JavaDoc)this.map.clone();
296          return tp;
297       }
298  
299       public boolean equals(Object JavaDoc another)
300       {
301          return super.equals(another);
302       }
303       
304       public String JavaDoc toString()
305       {
306          return this.getName();
307       }
308    }
309 }
310
Popular Tags