1
0
mirror of synced 2026-08-05 17:57:15 +00:00

SEC-545: Added utility methods for checking if user has a particular role to existing AuthorityUtils class. Class may be renamed at some point as more functionality is added.

This commit is contained in:
Luke Taylor
2007-11-11 23:37:32 +00:00
parent 315d4a247f
commit b681952933
2 changed files with 127 additions and 1 deletions
@@ -0,0 +1,63 @@
package org.springframework.security.util;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.junit.After;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import java.util.Set;
/**
* @author Luke Taylor
* @version $Id$
*/
public class AuthorityUtilsTests {
@Before
@After
public void clearContext() {
SecurityContextHolder.clearContext();
}
@Test
public void userHasAuthorityReturnsFalseForUnauthenticatedUser() {
assertFalse(AuthorityUtils.userHasAuthority("SOME_AUTHORITY"));
}
@Test
public void userHasAuthorityReturnsFalseWhenUserHasNoAuthorities() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("user", "password"));
assertFalse(AuthorityUtils.userHasAuthority("SOME_AUTHORITY"));
}
@Test
public void userHasAuthorityReturnsTrueWhenUserHasCorrectAuthority() {
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "password",
AuthorityUtils.stringArrayToAuthorityArray(new String[] {"A", "B"})));
assertTrue(AuthorityUtils.userHasAuthority("A"));
assertTrue(AuthorityUtils.userHasAuthority("B"));
assertFalse(AuthorityUtils.userHasAuthority("C"));
}
@Test
public void commaSeparatedStringIsParsedCorrectly() {
GrantedAuthority[] authorityArray =
AuthorityUtils.commaSeparatedStringToAuthorityArray(" ROLE_A, B, C, ROLE_D, E ");
Set authorities = AuthorityUtils.authorityArrayToSet(authorityArray);
assertTrue(authorities.contains("B"));
assertTrue(authorities.contains("C"));
assertTrue(authorities.contains("E"));
assertTrue(authorities.contains("ROLE_A"));
assertTrue(authorities.contains("ROLE_D"));
}
}