View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.realm;
20  
21  import java.security.Principal;
22  import java.util.ArrayList;
23  import java.util.Collection;
24  import java.util.HashSet;
25  import java.util.List;
26  import java.util.Set;
27  import org.apache.shiro.authc.AuthenticationException;
28  import org.apache.shiro.authc.AuthenticationInfo;
29  import org.apache.shiro.authc.AuthenticationToken;
30  import org.apache.shiro.authc.SimpleAccount;
31  import org.apache.shiro.authc.SimpleAuthenticationInfo;
32  import org.apache.shiro.authc.UsernamePasswordToken;
33  import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
34  import org.apache.shiro.authz.AuthorizationInfo;
35  import org.apache.shiro.authz.Permission;
36  import org.apache.shiro.authz.SimpleAuthorizationInfo;
37  import org.apache.shiro.authz.UnauthorizedException;
38  import org.apache.shiro.authz.permission.RolePermissionResolver;
39  import org.apache.shiro.authz.permission.WildcardPermission;
40  import org.apache.shiro.authz.permission.WildcardPermissionResolver;
41  import org.apache.shiro.subject.PrincipalCollection;
42  import org.apache.shiro.subject.SimplePrincipalCollection;
43  import org.junit.After;
44  import org.junit.Before;
45  import org.junit.Test;
46  
47  import static org.junit.Assert.assertEquals;
48  import static org.junit.Assert.assertFalse;
49  import static org.junit.Assert.assertNotNull;
50  import static org.junit.Assert.assertTrue;
51  import static org.junit.Assert.fail;
52  
53  
54  /**
55   * Simple test case for AuthorizingRealm.
56   * <p/>
57   * TODO - this could/should be expanded to be more robust end to end test for the AuthorizingRealm
58   */
59  public class AuthorizingRealmTest {
60  
61      AuthorizingRealm realm;
62  
63      private static final String USERNAME = "testuser";
64      private static final String PASSWORD = "password";
65      private static final int USER_ID = 12345;
66      private static final String ROLE = "admin";
67      private String localhost = "localhost";
68  
69      @Before
70      public void setup() {
71          realm = new AllowAllRealm();
72  
73      }
74  
75      @After
76      public void tearDown() {
77          realm = null;
78      }
79  
80      @Test
81      public void testDefaultConfig() {
82          AuthenticationInfo info = realm.getAuthenticationInfo(new UsernamePasswordToken(USERNAME, PASSWORD, localhost));
83  
84          assertNotNull(info);
85          assertTrue(realm.hasRole(info.getPrincipals(), ROLE));
86  
87          Object principal = info.getPrincipals().getPrimaryPrincipal();
88          assertTrue(principal instanceof UserIdPrincipal);
89  
90          UsernamePrincipal usernamePrincipal = info.getPrincipals().oneByType(UsernamePrincipal.class);
91          assertTrue(usernamePrincipal.getUsername().equals(USERNAME));
92  
93          UserIdPrincipal userIdPrincipal = info.getPrincipals().oneByType(UserIdPrincipal.class);
94          assertTrue(userIdPrincipal.getUserId() == USER_ID);
95  
96          String stringPrincipal = info.getPrincipals().oneByType(String.class);
97          assertTrue(stringPrincipal.equals(USER_ID + USERNAME));
98      }
99  
100     @Test
101     public void testCreateAccountOverride() {
102 
103         AuthorizingRealm realm = new AllowAllRealm() {
104             @Override
105             protected AuthenticationInfo buildAuthenticationInfo(Object principal, Object credentials) {
106                 String username = (String) principal;
107                 UsernamePrincipalernamePrincipal">UsernamePrincipal customPrincipal = new UsernamePrincipal(username);
108                 return new SimpleAccount(customPrincipal, credentials, getName());
109             }
110         };
111 
112         AuthenticationInfo info = realm.getAuthenticationInfo(new UsernamePasswordToken(USERNAME, PASSWORD, localhost));
113         assertNotNull(info);
114         assertTrue(realm.hasRole(info.getPrincipals(), ROLE));
115         Object principal = info.getPrincipals().getPrimaryPrincipal();
116         assertTrue(principal instanceof UsernamePrincipal);
117         assertEquals(USERNAME, ((UsernamePrincipal) principal).getUsername());
118 
119 
120     }
121 
122     @Test
123     public void testNullAuthzInfo() {
124 	AuthorizingRealm realm = new AuthorizingRealm() {
125             protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
126                 return null;
127             }
128 
129             protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
130                 return null;
131             }
132         };
133 
134         Principal principal = new UsernamePrincipal("blah");
135         PrincipalCollection pCollection = new SimplePrincipalCollection(principal, "nullAuthzRealm");
136         List<Permission> permList = new ArrayList<Permission>();
137         permList.add(new WildcardPermission("stringPerm1"));
138         permList.add(new WildcardPermission("stringPerm2"));
139         List<String> roleList = new ArrayList<String>();
140         roleList.add("role1");
141         roleList.add("role2");
142 
143         boolean thrown = false;
144         try {
145             realm.checkPermission(pCollection, "stringPermission");
146         } catch (UnauthorizedException e) {
147             thrown = true;
148         }
149         assertTrue(thrown);
150         thrown = false;
151 
152         try {
153             realm.checkPermission(pCollection, new WildcardPermission("stringPermission"));
154         } catch (UnauthorizedException e) {
155             thrown = true;
156         }
157         assertTrue(thrown);
158         thrown = false;
159 
160         try {
161             realm.checkPermissions(pCollection, "stringPerm1", "stringPerm2");
162         } catch (UnauthorizedException e) {
163             thrown = true;
164         }
165         assertTrue(thrown);
166         thrown = false;
167 
168         try {
169             realm.checkPermissions(pCollection, permList);
170         } catch (UnauthorizedException e) {
171             thrown = true;
172         }
173         assertTrue(thrown);
174         thrown = false;
175 
176         try {
177             realm.checkRole(pCollection, "role1");
178         } catch (UnauthorizedException e) {
179             thrown = true;
180         }
181         assertTrue(thrown);
182         thrown = false;
183 
184         try {
185             realm.checkRoles(pCollection, roleList);
186         } catch (UnauthorizedException e) {
187             thrown = true;
188         }
189         assertTrue(thrown);
190 
191         assertFalse(realm.hasAllRoles(pCollection, roleList));
192         assertFalse(realm.hasRole(pCollection, "role1"));
193         assertArrayEquals(new boolean[]{false, false}, realm.hasRoles(pCollection, roleList));
194         assertFalse(realm.isPermitted(pCollection, "perm1"));
195         assertFalse(realm.isPermitted(pCollection, new WildcardPermission("perm1")));
196         assertArrayEquals(new boolean[]{false, false}, realm.isPermitted(pCollection, "perm1", "perm2"));
197         assertArrayEquals(new boolean[]{false, false}, realm.isPermitted(pCollection, permList));
198         assertFalse(realm.isPermittedAll(pCollection, "perm1", "perm2"));
199         assertFalse(realm.isPermittedAll(pCollection, permList));
200     }
201     
202     @Test
203     public void testRealmWithRolePermissionResolver()
204     {   
205         Principal principal = new UsernamePrincipal("rolePermResolver");
206         PrincipalCollection pCollection = new SimplePrincipalCollection(principal, "testRealmWithRolePermissionResolver");
207         
208         AuthorizingRealm realm = new AllowAllRealm();
209         realm.setRolePermissionResolver( new RolePermissionResolver()
210         { 
211             public Collection<Permission> resolvePermissionsInRole( String roleString )
212             {
213                 Collection<Permission> permissions = new HashSet<Permission>();
214                 if( roleString.equals( ROLE ))
215                 {
216                     permissions.add( new WildcardPermission( ROLE + ":perm1" ) );
217                     permissions.add( new WildcardPermission( ROLE + ":perm2" ) );
218                     permissions.add( new WildcardPermission( "other:*:foo" ) );
219                 }
220                 return permissions;
221             }
222         });
223         
224         assertTrue( realm.hasRole( pCollection, ROLE ) );
225         assertTrue( realm.isPermitted( pCollection, ROLE + ":perm1" ) );
226         assertTrue( realm.isPermitted( pCollection, ROLE + ":perm2" ) );
227         assertFalse( realm.isPermitted( pCollection, ROLE + ":perm3" ) );
228         assertTrue( realm.isPermitted( pCollection, "other:bar:foo" ) );
229     }
230 
231     @Test
232     public void testRealmWithEmptyOrNullPermissions() {
233         Principal principal = new UsernamePrincipal("rolePermResolver");
234         PrincipalCollection pCollection = new SimplePrincipalCollection(principal, "testRealmWithRolePermissionResolver");
235 
236         AuthorizingRealm realm = new AllowAllRealm();
237         realm.setRolePermissionResolver( new RolePermissionResolver()
238         {
239             public Collection<Permission> resolvePermissionsInRole( String roleString )
240             {
241                 Collection<Permission> permissions = new HashSet<Permission>();
242                 if( roleString.equals( ROLE ))
243                 {
244                     permissions.add( new WildcardPermission( ROLE + ":perm1" ) );
245                     permissions.add( new WildcardPermission( ROLE + ":perm2" ) );
246                     permissions.add( new WildcardPermission( ROLE + ": " ) );
247                     permissions.add( new WildcardPermission( ROLE + ":\t" ) );
248                     permissions.add( new WildcardPermission( "other:*:foo" ) );
249                 }
250                 return permissions;
251             }
252         });
253 
254         realm.setPermissionResolver(new WildcardPermissionResolver());
255         SimpleAuthorizationInfo authorizationInfo = (SimpleAuthorizationInfo) realm.getAuthorizationInfo(pCollection);
256         assertNotNull(authorizationInfo);
257         authorizationInfo.addStringPermission("");
258         authorizationInfo.addStringPermission(" ");
259         authorizationInfo.addStringPermission("\t");
260         authorizationInfo.addStringPermission(null);
261         Collection<Permission> permissions = realm.getPermissions(authorizationInfo);
262         assertEquals(permissions.size(), 4);
263     }
264 
265     private void assertArrayEquals(boolean[] expected, boolean[] actual) {
266         if (expected.length != actual.length) {
267             fail("Expected array of length [" + expected.length + "] but received array of length [" + actual.length + "]");
268         }
269         for (int i = 0; i < expected.length; i++) {
270             if (expected[i] != actual[i]) {
271                 fail("Expected index [" + i + "] to be [" + expected[i] + "] but was [" + actual[i] + "]");
272             }
273         }
274     }
275 
276     public class AllowAllRealm extends AuthorizingRealm {
277 
278         public AllowAllRealm() {
279             super();
280             setCredentialsMatcher(new AllowAllCredentialsMatcher());
281         }
282 
283         protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
284             return buildAuthenticationInfo(token.getPrincipal(), token.getCredentials());
285         }
286 
287         protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
288             Set<String> roles = new HashSet<String>();
289             roles.add(ROLE);
290             return new SimpleAuthorizationInfo(roles);
291         }
292 
293         protected AuthenticationInfo buildAuthenticationInfo(Object principal, Object credentials) {
294             Collection<Object> principals = new ArrayList<Object>(3);
295             principals.add(new UserIdPrincipal(USER_ID));
296             principals.add(new UsernamePrincipal(USERNAME));
297             principals.add(USER_ID + USERNAME);
298             return new SimpleAuthenticationInfo(principals, PASSWORD, getName());
299         }
300 
301     }
302 
303 }