KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > jetty > SecurityTest


1 /**
2  *
3  * Copyright 2003-2004 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 package org.apache.geronimo.jetty;
19
20 import java.io.BufferedReader JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.io.InputStreamReader JavaDoc;
23 import java.net.HttpURLConnection JavaDoc;
24 import java.net.URL JavaDoc;
25 import java.security.PermissionCollection JavaDoc;
26 import java.security.Permissions JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.HashSet JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Set JavaDoc;
32 import javax.security.auth.Subject JavaDoc;
33 import javax.security.auth.x500.X500Principal JavaDoc;
34 import javax.security.jacc.WebResourcePermission JavaDoc;
35 import javax.security.jacc.WebUserDataPermission JavaDoc;
36
37 import org.apache.geronimo.common.DeploymentException;
38 import org.apache.geronimo.security.RealmPrincipal;
39 import org.apache.geronimo.security.deploy.DefaultPrincipal;
40 import org.apache.geronimo.security.deploy.DistinguishedName;
41 import org.apache.geronimo.security.deploy.Principal;
42 import org.apache.geronimo.security.deploy.Realm;
43 import org.apache.geronimo.security.deploy.Role;
44 import org.apache.geronimo.security.deploy.Security;
45 import org.apache.geronimo.security.jacc.ComponentPermissions;
46 import org.apache.geronimo.security.util.ConfigurationUtil;
47
48
49 /**
50  * Tests the JAAC security for Jetty by using both explicit and auto role mapping
51  *
52  * @version $Rev: 161394 $ $Date: 2005-04-14 22:35:25 -0700 (Thu, 14 Apr 2005) $
53  */

54 public class SecurityTest extends AbstractWebModuleTest {
55
56     /**
57      * Test the explicit map feature. Only Alan should be able to log in.
58      *
59      * @throws Exception thrown if an error in the test occurs
60      */

61     public void testExplicitMapping() throws Exception JavaDoc {
62         Security securityConfig = new Security();
63         securityConfig.setUseContextHandler(false);
64
65         DefaultPrincipal defaultPrincipal = new DefaultPrincipal();
66         defaultPrincipal.setRealmName("demo-properties-realm");
67         Principal JavaDoc principal = new Principal JavaDoc();
68         principal.setClassName("org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal");
69         principal.setPrincipalName("izumi");
70         defaultPrincipal.setPrincipal(principal);
71
72         securityConfig.setDefaultPrincipal(defaultPrincipal);
73
74         Role role = new Role();
75         role.setRoleName("content-administrator");
76         principal = new Principal JavaDoc();
77         principal.setClassName("org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal");
78         principal.setPrincipalName("it");
79         Realm realm = new Realm();
80         realm.setRealmName("demo-properties-realm");
81         realm.getPrincipals().add(principal);
82         role.getRealms().put(realm.getRealmName(), realm);
83
84         securityConfig.getRoleMappings().put(role.getRoleName(), role);
85
86         Map JavaDoc roleDesignates = new HashMap JavaDoc();
87         Map JavaDoc principalRoleMap = new HashMap JavaDoc();
88         buildPrincipalRoleMap(securityConfig, roleDesignates, principalRoleMap);
89
90         PermissionCollection JavaDoc uncheckedPermissions = new Permissions JavaDoc();
91
92         PermissionCollection JavaDoc excludedPermissions = new Permissions JavaDoc();
93         excludedPermissions.add(new WebResourcePermission JavaDoc("/auth/login.html", ""));
94         excludedPermissions.add(new WebUserDataPermission JavaDoc("/auth/login.html", ""));
95
96         Map JavaDoc rolePermissions = new HashMap JavaDoc();
97         PermissionCollection JavaDoc permissions = new Permissions JavaDoc();
98         permissions.add(new WebUserDataPermission JavaDoc("/protected/*", ""));
99         permissions.add(new WebResourcePermission JavaDoc("/protected/*", ""));
100         rolePermissions.put("content-administrator", permissions);
101         rolePermissions.put("auto-administrator", permissions);
102
103         PermissionCollection JavaDoc checked = permissions;
104
105         Set JavaDoc securityRoles = new HashSet JavaDoc();
106         securityRoles.add("content-administrator");
107         securityRoles.add("auto-administrator");
108
109         ComponentPermissions componentPermissions = new ComponentPermissions(excludedPermissions, uncheckedPermissions, rolePermissions);
110
111         startWebApp(roleDesignates, principalRoleMap, componentPermissions, defaultPrincipal, checked, securityRoles);
112
113         HttpURLConnection JavaDoc connection = (HttpURLConnection JavaDoc) new URL JavaDoc("http://localhost:5678/test/protected/hello.txt").openConnection();
114         connection.setInstanceFollowRedirects(false);
115         assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode());
116
117         String JavaDoc cookie = connection.getHeaderField("Set-Cookie");
118         cookie = cookie.substring(0, cookie.lastIndexOf(';'));
119         String JavaDoc location = connection.getHeaderField("Location");
120
121         connection = (HttpURLConnection JavaDoc) new URL JavaDoc(location).openConnection();
122         connection.setInstanceFollowRedirects(false);
123         assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
124
125         location = location.substring(0, location.lastIndexOf('/')) + "/j_security_check?j_username=alan&j_password=starcraft";
126
127         connection = (HttpURLConnection JavaDoc) new URL JavaDoc(location).openConnection();
128         connection.setRequestMethod("POST");
129         connection.setRequestProperty("Cookie", cookie);
130         connection.setInstanceFollowRedirects(false);
131         assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode());
132
133         connection = (HttpURLConnection JavaDoc) new URL JavaDoc("http://localhost:5678/test/protected/hello.txt").openConnection();
134         connection.setRequestProperty("Cookie", cookie);
135         connection.setInstanceFollowRedirects(false);
136         BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(connection.getInputStream()));
137
138         assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
139         assertEquals("Hello World", reader.readLine());
140         connection.disconnect();
141
142         connection = (HttpURLConnection JavaDoc) new URL JavaDoc("http://localhost:5678/test/protected/hello.txt").openConnection();
143         connection.setInstanceFollowRedirects(false);
144         assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode());
145
146         cookie = connection.getHeaderField("Set-Cookie");
147         cookie = cookie.substring(0, cookie.lastIndexOf(';'));
148         location = connection.getHeaderField("Location");
149
150         connection = (HttpURLConnection JavaDoc) new URL JavaDoc(location).openConnection();
151         connection.setInstanceFollowRedirects(false);
152         assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
153
154         location = location.substring(0, location.lastIndexOf('/')) + "/j_security_check?j_username=izumi&j_password=violin";
155
156         connection = (HttpURLConnection JavaDoc) new URL JavaDoc(location).openConnection();
157         connection.setRequestMethod("POST");
158         connection.setRequestProperty("Cookie", cookie);
159         connection.setInstanceFollowRedirects(false);
160         assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode());
161
162         try {
163             connection = (HttpURLConnection JavaDoc) new URL JavaDoc("http://localhost:5678/test/protected/hello.txt").openConnection();
164             connection.setRequestProperty("Cookie", cookie);
165             connection.setInstanceFollowRedirects(false);
166             reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(connection.getInputStream()));
167
168             fail("Should throw an IOException for HTTP 403 response");
169         } catch (IOException JavaDoc e) {
170         }
171
172         assertEquals(HttpURLConnection.HTTP_FORBIDDEN, connection.getResponseCode());
173         connection.disconnect();
174
175         stopWebApp();
176     }
177
178     protected void startWebApp(Map JavaDoc roleDesignates, Map JavaDoc principalRoleMap, ComponentPermissions componentPermissions, DefaultPrincipal defaultPrincipal, PermissionCollection JavaDoc checked, Set JavaDoc securityRoles) throws Exception JavaDoc {
179         setUpSecureAppContext(roleDesignates, principalRoleMap, componentPermissions, defaultPrincipal, checked, securityRoles);
180         setUpStaticContentServlet();
181 // start(appName, app);
182
}
183
184     protected void stopWebApp() throws Exception JavaDoc {
185 // stop(appName);
186
}
187
188     protected void setUp() throws Exception JavaDoc {
189         super.setUp();
190         setUpSecurity();
191     }
192
193     protected void tearDown() throws Exception JavaDoc {
194         tearDownSecurity();
195         super.tearDown();
196     }
197
198     //copied from SecurityBuilder
199
public static void buildPrincipalRoleMap(Security security, Map JavaDoc roleDesignates, Map JavaDoc principalRoleMap) throws DeploymentException {
200          Map JavaDoc roleToPrincipalMap = new HashMap JavaDoc();
201          buildRolePrincipalMap(security, roleDesignates, roleToPrincipalMap);
202          invertMap(roleToPrincipalMap, principalRoleMap);
203      }
204
205      private static Map JavaDoc invertMap(Map JavaDoc roleToPrincipalMap, Map JavaDoc principalRoleMapping) {
206          for (Iterator JavaDoc roles = roleToPrincipalMap.entrySet().iterator(); roles.hasNext();) {
207              Map.Entry JavaDoc entry = (Map.Entry JavaDoc) roles.next();
208              String JavaDoc role = (String JavaDoc) entry.getKey();
209              Set JavaDoc principals = (Set JavaDoc) entry.getValue();
210              for (Iterator JavaDoc iter = principals.iterator(); iter.hasNext();) {
211                  java.security.Principal JavaDoc principal = (java.security.Principal JavaDoc) iter.next();
212
213                  HashSet JavaDoc roleSet = (HashSet JavaDoc) principalRoleMapping.get(principal);
214                  if (roleSet == null) {
215                      roleSet = new HashSet JavaDoc();
216                      principalRoleMapping.put(principal, roleSet);
217                  }
218                  roleSet.add(role);
219              }
220          }
221          return principalRoleMapping;
222      }
223
224      private static void buildRolePrincipalMap(Security security, Map JavaDoc roleDesignates, Map JavaDoc roleToPrincipalMap) throws DeploymentException {
225
226          Iterator JavaDoc rollMappings = security.getRoleMappings().values().iterator();
227          while (rollMappings.hasNext()) {
228              Role role = (Role) rollMappings.next();
229
230              String JavaDoc roleName = role.getRoleName();
231              Subject JavaDoc roleDesignate = new Subject JavaDoc();
232              Set JavaDoc principalSet = new HashSet JavaDoc();
233
234              Iterator JavaDoc realms = role.getRealms().values().iterator();
235              while (realms.hasNext()) {
236                  Realm realm = (Realm) realms.next();
237
238                  Iterator JavaDoc principals = realm.getPrincipals().iterator();
239                  while (principals.hasNext()) {
240                      Principal JavaDoc principal = (Principal JavaDoc) principals.next();
241
242                      RealmPrincipal realmPrincipal = ConfigurationUtil.generateRealmPrincipal(principal, realm.getRealmName());
243
244                      if (realmPrincipal == null) throw new DeploymentException("Unable to create realm principal");
245
246                      principalSet.add(realmPrincipal);
247                      if (principal.isDesignatedRunAs()) roleDesignate.getPrincipals().add(realmPrincipal);
248                  }
249              }
250
251              for (Iterator JavaDoc names = role.getDNames().iterator(); names.hasNext();) {
252                  DistinguishedName dn = (DistinguishedName) names.next();
253
254                  X500Principal JavaDoc x500Principal = ConfigurationUtil.generateX500Principal(dn.getName());
255
256                  principalSet.add(x500Principal);
257                  if (dn.isDesignatedRunAs()) {
258                      roleDesignate.getPrincipals().add(x500Principal);
259                  }
260              }
261
262              Set JavaDoc roleMapping = (Set JavaDoc) roleToPrincipalMap.get(roleName);
263              if (roleMapping == null) {
264                  roleMapping = new HashSet JavaDoc();
265                  roleToPrincipalMap.put(roleName, roleMapping);
266              }
267              roleMapping.addAll(principalSet);
268
269              if (roleDesignate.getPrincipals().size() > 0) {
270                  roleDesignates.put(roleName, roleDesignate);
271              }
272          }
273      }
274 }
275
Popular Tags