SEC-1012: Refactoring of use of GrantedAuthority[] to generified collections

This commit is contained in:
Luke Taylor 2008-10-31 03:53:00 +00:00
parent e891b334e6
commit ec44f2bdfe
137 changed files with 2250 additions and 4219 deletions

View File

@ -15,6 +15,8 @@
package org.springframework.security.acls.domain; package org.springframework.security.acls.domain;
import java.util.List;
import org.springframework.security.AccessDeniedException; import org.springframework.security.AccessDeniedException;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
@ -100,10 +102,10 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
} }
// Iterate this principal's authorities to determine right // Iterate this principal's authorities to determine right
GrantedAuthority[] auths = authentication.getAuthorities(); List<GrantedAuthority> auths = authentication.getAuthorities();
for (int i = 0; i < auths.length; i++) { for (int i = 0; i < auths.size(); i++) {
if (requiredAuthority.equals(auths[i])) { if (requiredAuthority.equals(auths.get(i))) {
return; return;
} }
} }

View File

@ -15,6 +15,8 @@
package org.springframework.security.acls.sid; package org.springframework.security.acls.sid;
import java.util.List;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
@ -31,13 +33,13 @@ public class SidRetrievalStrategyImpl implements SidRetrievalStrategy {
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
public Sid[] getSids(Authentication authentication) { public Sid[] getSids(Authentication authentication) {
GrantedAuthority[] authorities = authentication.getAuthorities(); List<GrantedAuthority> authorities = authentication.getAuthorities();
Sid[] sids = new Sid[authorities.length + 1]; Sid[] sids = new Sid[authorities.size() + 1];
sids[0] = new PrincipalSid(authentication); sids[0] = new PrincipalSid(authentication);
for (int i = 1; i <= authorities.length; i++) { for (int i = 1; i <= authorities.size(); i++) {
sids[i] = new GrantedAuthoritySid(authorities[i - 1]); sids[i] = new GrantedAuthoritySid(authorities.get(i - 1));
} }
return sids; return sids;

View File

@ -4,13 +4,11 @@ import junit.framework.Assert;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.TestingAuthenticationToken; import org.springframework.security.providers.TestingAuthenticationToken;
/** /**
* Tests for {@link SidRetrievalStrategyImpl} * Tests for {@link SidRetrievalStrategyImpl}
* *
* @author Andrei Stefan * @author Andrei Stefan
*/ */
public class SidRetrievalStrategyTests extends TestCase { public class SidRetrievalStrategyTests extends TestCase {
@ -18,8 +16,7 @@ public class SidRetrievalStrategyTests extends TestCase {
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
public void testSidsRetrieval() throws Exception { public void testSidsRetrieval() throws Exception {
Authentication authentication = new TestingAuthenticationToken("scott", "password", new GrantedAuthority[] { Authentication authentication = new TestingAuthenticationToken("scott", "password", "ROLE_1", "ROLE_2", "ROLE_3");
new GrantedAuthorityImpl("ROLE_1"), new GrantedAuthorityImpl("ROLE_2"), new GrantedAuthorityImpl("ROLE_3") });
SidRetrievalStrategy retrStrategy = new SidRetrievalStrategyImpl(); SidRetrievalStrategy retrStrategy = new SidRetrievalStrategyImpl();
Sid[] sids = retrStrategy.getSids(authentication); Sid[] sids = retrStrategy.getSids(authentication);

View File

@ -23,6 +23,8 @@ import org.springframework.security.providers.AbstractAuthenticationToken;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import java.io.Serializable; import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/** /**
* Represents a successful CAS <code>Authentication</code>. * Represents a successful CAS <code>Authentication</code>.
@ -43,7 +45,15 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
//~ Constructors =================================================================================================== //~ Constructors ===================================================================================================
/** /**
* @deprecated
*/
public CasAuthenticationToken(final String key, final Object principal, final Object credentials,
final GrantedAuthority[] authorities, final UserDetails userDetails, final Assertion assertion) {
this(key, principal, credentials, Arrays.asList(authorities), userDetails, assertion);
}
/**
* Constructor. * Constructor.
* *
* @param key to identify if this object made by a given {@link * @param key to identify if this object made by a given {@link
@ -61,7 +71,7 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
* @throws IllegalArgumentException if a <code>null</code> was passed * @throws IllegalArgumentException if a <code>null</code> was passed
*/ */
public CasAuthenticationToken(final String key, final Object principal, final Object credentials, public CasAuthenticationToken(final String key, final Object principal, final Object credentials,
final GrantedAuthority[] authorities, final UserDetails userDetails, final Assertion assertion) { final List<GrantedAuthority> authorities, final UserDetails userDetails, final Assertion assertion) {
super(authorities); super(authorities);
if ((key == null) || ("".equals(key)) || (principal == null) || "".equals(principal) || (credentials == null) if ((key == null) || ("".equals(key)) || (principal == null) || "".equals(principal) || (credentials == null)
@ -86,9 +96,9 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
if (obj instanceof CasAuthenticationToken) { if (obj instanceof CasAuthenticationToken) {
CasAuthenticationToken test = (CasAuthenticationToken) obj; CasAuthenticationToken test = (CasAuthenticationToken) obj;
if (!this.assertion.equals(test.getAssertion())) { if (!this.assertion.equals(test.getAssertion())) {
return false; return false;
} }
if (this.getKeyHash() != test.getKeyHash()) { if (this.getKeyHash() != test.getKeyHash()) {

View File

@ -61,13 +61,13 @@ public class CasAuthenticationProviderTests {
return new User("user", "password", true, true, true, true, return new User("user", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B")}); new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B")});
} }
private ServiceProperties makeServiceProperties() { private ServiceProperties makeServiceProperties() {
final ServiceProperties serviceProperties = new ServiceProperties(); final ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setSendRenew(false); serviceProperties.setSendRenew(false);
serviceProperties.setService("http://test.com"); serviceProperties.setService("http://test.com");
return serviceProperties; return serviceProperties;
} }
@Test @Test
@ -79,7 +79,7 @@ public class CasAuthenticationProviderTests {
StatelessTicketCache cache = new MockStatelessTicketCache(); StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache); cap.setStatelessTicketCache(cache);
cap.setServiceProperties(makeServiceProperties()); cap.setServiceProperties(makeServiceProperties());
cap.setTicketValidator(new MockTicketValidator(true)); cap.setTicketValidator(new MockTicketValidator(true));
cap.afterPropertiesSet(); cap.afterPropertiesSet();
@ -99,8 +99,8 @@ public class CasAuthenticationProviderTests {
CasAuthenticationToken casResult = (CasAuthenticationToken) result; CasAuthenticationToken casResult = (CasAuthenticationToken) result;
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), casResult.getPrincipal()); assertEquals(makeUserDetailsFromAuthoritiesPopulator(), casResult.getPrincipal());
assertEquals("ST-123", casResult.getCredentials()); assertEquals("ST-123", casResult.getCredentials());
assertEquals(new GrantedAuthorityImpl("ROLE_A"), casResult.getAuthorities()[0]); assertEquals(new GrantedAuthorityImpl("ROLE_A"), casResult.getAuthorities().get(0));
assertEquals(new GrantedAuthorityImpl("ROLE_B"), casResult.getAuthorities()[1]); assertEquals(new GrantedAuthorityImpl("ROLE_B"), casResult.getAuthorities().get(1));
assertEquals(cap.getKey().hashCode(), casResult.getKeyHash()); assertEquals(cap.getKey().hashCode(), casResult.getKeyHash());
assertEquals("details", casResult.getDetails()); assertEquals("details", casResult.getDetails());
@ -171,7 +171,7 @@ public class CasAuthenticationProviderTests {
@Test(expected = BadCredentialsException.class) @Test(expected = BadCredentialsException.class)
public void invalidKeyIsDetected() throws Exception { public void invalidKeyIsDetected() throws Exception {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationProvider cap = new CasAuthenticationProvider(); CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator()); cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty"); cap.setKey("qwerty");
@ -322,11 +322,11 @@ public class CasAuthenticationProviderTests {
} }
public Assertion validate(final String ticket, final String service) public Assertion validate(final String ticket, final String service)
throws TicketValidationException { throws TicketValidationException {
if (returnTicket) { if (returnTicket) {
return new AssertionImpl("rod"); return new AssertionImpl("rod");
} }
throw new BadCredentialsException("As requested from mock"); throw new BadCredentialsException("As requested from mock");
} }
} }
} }

View File

@ -64,7 +64,7 @@ public class CasAuthenticationTokenTests extends TestCase {
} }
public void testConstructorRejectsNulls() { public void testConstructorRejectsNulls() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
try { try {
new CasAuthenticationToken(null, makeUserDetails(), "Password", new CasAuthenticationToken(null, makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
@ -92,13 +92,6 @@ public class CasAuthenticationTokenTests extends TestCase {
assertTrue(true); assertTrue(true);
} }
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", null, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try { try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
@ -116,7 +109,7 @@ public class CasAuthenticationTokenTests extends TestCase {
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertTrue(true); assertTrue(true);
} }
try { try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", new CasAuthenticationToken("key", makeUserDetails(), "Password",
@ -129,7 +122,7 @@ public class CasAuthenticationTokenTests extends TestCase {
} }
public void testEqualsWhenEqual() { public void testEqualsWhenEqual() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
@ -144,15 +137,15 @@ public class CasAuthenticationTokenTests extends TestCase {
public void testGetters() { public void testGetters() {
// Build the proxy list returned in the ticket from CAS // Build the proxy list returned in the ticket from CAS
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion); makeUserDetails(), assertion);
assertEquals("key".hashCode(), token.getKeyHash()); assertEquals("key".hashCode(), token.getKeyHash());
assertEquals(makeUserDetails(), token.getPrincipal()); assertEquals(makeUserDetails(), token.getPrincipal());
assertEquals("Password", token.getCredentials()); assertEquals("Password", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority()); assertEquals("ROLE_ONE", token.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority()); assertEquals("ROLE_TWO", token.getAuthorities().get(1).getAuthority());
assertEquals(assertion, token.getAssertion()); assertEquals(assertion, token.getAssertion());
assertEquals(makeUserDetails().getUsername(), token.getUserDetails().getUsername()); assertEquals(makeUserDetails().getUsername(), token.getUserDetails().getUsername());
} }
@ -169,7 +162,7 @@ public class CasAuthenticationTokenTests extends TestCase {
} }
public void testNotEqualsDueToAbstractParentEqualsCheck() { public void testNotEqualsDueToAbstractParentEqualsCheck() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
@ -183,7 +176,7 @@ public class CasAuthenticationTokenTests extends TestCase {
} }
public void testNotEqualsDueToDifferentAuthenticationClass() { public void testNotEqualsDueToDifferentAuthenticationClass() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
@ -196,7 +189,7 @@ public class CasAuthenticationTokenTests extends TestCase {
} }
public void testNotEqualsDueToKey() { public void testNotEqualsDueToKey() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
@ -210,8 +203,8 @@ public class CasAuthenticationTokenTests extends TestCase {
} }
public void testNotEqualsDueToAssertion() { public void testNotEqualsDueToAssertion() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
final Assertion assertion2 = new AssertionImpl("test"); final Assertion assertion2 = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
@ -225,7 +218,7 @@ public class CasAuthenticationTokenTests extends TestCase {
} }
public void testSetAuthenticated() { public void testSetAuthenticated() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion); makeUserDetails(), assertion);
@ -235,7 +228,7 @@ public class CasAuthenticationTokenTests extends TestCase {
} }
public void testToString() { public void testToString() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion); makeUserDetails(), assertion);

View File

@ -18,6 +18,7 @@ package org.springframework.security;
import java.io.Serializable; import java.io.Serializable;
import java.security.Principal; import java.security.Principal;
import java.util.List;
/** /**
@ -46,7 +47,7 @@ public interface Authentication extends Principal, Serializable {
* *
* @return the authorities granted to the principal, or <code>null</code> if authentication has not been completed * @return the authorities granted to the principal, or <code>null</code> if authentication has not been completed
*/ */
GrantedAuthority[] getAuthorities(); List<GrantedAuthority> getAuthorities();
/** /**
* The credentials that prove the principal is correct. This is usually a password, but could be anything * The credentials that prove the principal is correct. This is usually a password, but could be anything

View File

@ -26,17 +26,20 @@ public interface AuthenticationManager {
/** /**
* Attempts to authenticate the passed {@link Authentication} object, returning a fully populated * Attempts to authenticate the passed {@link Authentication} object, returning a fully populated
* <code>Authentication</code> object (including granted authorities) if successful.<p>An * <code>Authentication</code> object (including granted authorities) if successful.
* <code>AuthenticationManager</code> must honour the following contract concerning exceptions:</p> * <p>
* <p>A {@link DisabledException} must be thrown if an account is disabled and the * An <code>AuthenticationManager</code> must honour the following contract concerning exceptions:
* <code>AuthenticationManager</code> can test for this state.</p> * <ul>
* <p>A {@link LockedException} must be thrown if an account is locked and the * <li>A {@link DisabledException} must be thrown if an account is disabled and the
* <code>AuthenticationManager</code> can test for account locking.</p> * <code>AuthenticationManager</code> can test for this state.</li>
* <p>A {@link BadCredentialsException} must be thrown if incorrect credentials are presented. Whilst the * <li>A {@link LockedException} must be thrown if an account is locked and the
* above exceptions are optional, an <code>AuthenticationManager</code> must <B>always</B> test credentials.</p> * <code>AuthenticationManager</code> can test for account locking.</li>
* <p>Exceptions should be tested for and if applicable thrown in the order expressed above (ie if an * <li>A {@link BadCredentialsException} must be thrown if incorrect credentials are presented. Whilst the
* above exceptions are optional, an <code>AuthenticationManager</code> must <B>always</B> test credentials.</li>
* </ul>
* Exceptions should be tested for and if applicable thrown in the order expressed above (i.e. if an
* account is disabled or locked, the authentication request is immediately rejected and the credentials testing * account is disabled or locked, the authentication request is immediately rejected and the credentials testing
* process is not performed). This prevents credentials being tested against disabled or locked accounts.</p> * process is not performed). This prevents credentials being tested against disabled or locked accounts.
* *
* @param authentication the authentication request object * @param authentication the authentication request object
* *
@ -44,6 +47,5 @@ public interface AuthenticationManager {
* *
* @throws AuthenticationException if authentication fails * @throws AuthenticationException if authentication fails
*/ */
Authentication authenticate(Authentication authentication) Authentication authenticate(Authentication authentication) throws AuthenticationException;
throws AuthenticationException;
} }

View File

@ -1,6 +1,7 @@
package org.springframework.security; package org.springframework.security;
import java.io.Serializable; import java.io.Serializable;
import java.util.List;
/** /**
* Indicates that a object stores GrantedAuthority objects. * Indicates that a object stores GrantedAuthority objects.
@ -13,5 +14,5 @@ import java.io.Serializable;
* @since 2.0 * @since 2.0
*/ */
public interface GrantedAuthoritiesContainer extends Serializable { public interface GrantedAuthoritiesContainer extends Serializable {
GrantedAuthority[] getGrantedAuthorities(); List<GrantedAuthority> getGrantedAuthorities();
} }

View File

@ -1,27 +1,25 @@
package org.springframework.security; package org.springframework.security;
import java.util.ArrayList; import java.util.Collections;
import java.util.Arrays;
import java.util.List; import java.util.List;
import org.springframework.util.Assert; import org.springframework.util.Assert;
public class GrantedAuthoritiesContainerImpl implements MutableGrantedAuthoritiesContainer { public class GrantedAuthoritiesContainerImpl implements MutableGrantedAuthoritiesContainer {
private List authorities; private List<GrantedAuthority> authorities;
public void setGrantedAuthorities(GrantedAuthority[] newAuthorities) { public void setGrantedAuthorities(List<GrantedAuthority> newAuthorities) {
this.authorities = new ArrayList(newAuthorities.length); authorities = Collections.unmodifiableList(newAuthorities);
authorities.addAll(Arrays.asList(newAuthorities)); }
}
public GrantedAuthority[] getGrantedAuthorities() { public List<GrantedAuthority> getGrantedAuthorities() {
Assert.notNull(authorities, "Granted authorities have not been set"); Assert.notNull(authorities, "Granted authorities have not been set");
return (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]); return authorities;
} }
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append("Authorities: ").append(authorities); sb.append("Authorities: ").append(authorities);
return sb.toString(); return sb.toString();
} }
} }

View File

@ -34,7 +34,6 @@ public class MockAuthenticationManager extends AbstractAuthenticationManager {
} }
public MockAuthenticationManager() { public MockAuthenticationManager() {
super();
} }
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================

View File

@ -1,5 +1,7 @@
package org.springframework.security; package org.springframework.security;
import java.util.List;
/** /**
* Indicates that a object can be used to store and retrieve GrantedAuthority objects. * Indicates that a object can be used to store and retrieve GrantedAuthority objects.
* <p> * <p>
@ -14,5 +16,5 @@ public interface MutableGrantedAuthoritiesContainer extends GrantedAuthoritiesCo
/** /**
* Used to store authorities in the containing object. * Used to store authorities in the containing object.
*/ */
void setGrantedAuthorities(GrantedAuthority[] authorities); void setGrantedAuthorities(List<GrantedAuthority> authorities);
} }

View File

@ -34,8 +34,9 @@ import java.util.Vector;
* "recipient" types presented in a <code>BasicAclEntry</code> because it merely delegates to the detected {@link * "recipient" types presented in a <code>BasicAclEntry</code> because it merely delegates to the detected {@link
* Authentication#getPrincipal()} or {@link Authentication#getAuthorities()}. The principal object or granted * Authentication#getPrincipal()} or {@link Authentication#getAuthorities()}. The principal object or granted
* authorities object has its <code>Object.equals(recipient)</code> method called to make the decision as to whether * authorities object has its <code>Object.equals(recipient)</code> method called to make the decision as to whether
* the recipient in the <code>BasicAclEntry</code> is the same as the principal or granted authority.</p> * the recipient in the <code>BasicAclEntry</code> is the same as the principal or granted authority.
* <P>This class should prove an adequate ACLs resolver if you're using standard Spring Security classes. This is * <p>
* This class should prove an adequate ACLs resolver if you're using standard Spring Security classes. This is
* because the typical <code>Authentication</code> token is <code>UsernamePasswordAuthenticationToken</code>, which * because the typical <code>Authentication</code> token is <code>UsernamePasswordAuthenticationToken</code>, which
* for its <code>principal</code> is usually a <code>String</code>. The <code>GrantedAuthorityImpl</code> is typically * for its <code>principal</code> is usually a <code>String</code>. The <code>GrantedAuthorityImpl</code> is typically
* used for granted authorities, which tests for equality based on a <code>String</code>. This means * used for granted authorities, which tests for equality based on a <code>String</code>. This means
@ -93,9 +94,9 @@ public class GrantedAuthorityEffectiveAclsResolver implements EffectiveAclsResol
// As with the principal, allow each of the Authentication's // As with the principal, allow each of the Authentication's
// granted authorities to decide whether the presented // granted authorities to decide whether the presented
// recipient is "equal" // recipient is "equal"
GrantedAuthority[] authorities = filteredBy.getAuthorities(); List<GrantedAuthority >authorities = filteredBy.getAuthorities();
if ((authorities == null) || (authorities.length == 0)) { if ((authorities == null) || (authorities.size() == 0)) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Did not match principal and there are no granted authorities, " logger.debug("Did not match principal and there are no granted authorities, "
+ "so cannot compare with recipient: " + recipient); + "so cannot compare with recipient: " + recipient);
@ -104,10 +105,10 @@ public class GrantedAuthorityEffectiveAclsResolver implements EffectiveAclsResol
continue; continue;
} }
for (int k = 0; k < authorities.length; k++) { for (int k = 0; k < authorities.size(); k++) {
if (authorities[k].equals(recipient)) { if (authorities.get(k).equals(recipient)) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("GrantedAuthority: " + authorities[k] + " matches recipient: " + recipient); logger.debug("GrantedAuthority: " + authorities.get(k) + " matches recipient: " + recipient);
} }
list.add(allAcls[i]); list.add(allAcls[i]);

View File

@ -1,5 +1,8 @@
package org.springframework.security.authoritymapping; package org.springframework.security.authoritymapping;
import java.util.Collection;
import java.util.List;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
/** /**
@ -20,5 +23,5 @@ public interface Attributes2GrantedAuthoritiesMapper {
* @param attribute the attributes to be mapped * @param attribute the attributes to be mapped
* @return the list of mapped GrantedAuthorities * @return the list of mapped GrantedAuthorities
*/ */
public GrantedAuthority[] getGrantedAuthorities(String[] attributes); public List<GrantedAuthority> getGrantedAuthorities(Collection<String> attributes);
} }

View File

@ -16,152 +16,152 @@ import org.springframework.util.StringUtils;
/** /**
* <p>
* This class implements the Attributes2GrantedAuthoritiesMapper and * This class implements the Attributes2GrantedAuthoritiesMapper and
* MappableAttributesRetriever interfaces based on the supplied Map. * MappableAttributesRetriever interfaces based on the supplied Map.
* It supports both one-to-one and one-to-many mappings. The granted * It supports both one-to-one and one-to-many mappings. The granted
* authorities to map to can be supplied either as a String or as a * authorities to map to can be supplied either as a String or as a
* GrantedAuthority object. * GrantedAuthority object.
* </p> *
* @author Ruud Senden * @author Ruud Senden
*/ */
public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2GrantedAuthoritiesMapper, MappableAttributesRetriever, InitializingBean { public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2GrantedAuthoritiesMapper, MappableAttributesRetriever, InitializingBean {
private Map attributes2grantedAuthoritiesMap = null; private Map<String, Collection<GrantedAuthority>> attributes2grantedAuthoritiesMap = null;
private String stringSeparator = ","; private String stringSeparator = ",";
private String[] mappableAttributes = null; private String[] mappableAttributes = null;
/**
* Check whether all properties have been set to correct values, and do some preprocessing.
*/
public void afterPropertiesSet() {
Assert.notEmpty(attributes2grantedAuthoritiesMap,"A non-empty attributes2grantedAuthoritiesMap must be supplied");
attributes2grantedAuthoritiesMap = preProcessMap(attributes2grantedAuthoritiesMap);
try {
mappableAttributes = (String[])attributes2grantedAuthoritiesMap.keySet().toArray(new String[]{});
} catch ( ArrayStoreException ase ) {
throw new IllegalArgumentException("attributes2grantedAuthoritiesMap contains non-String objects as keys");
}
}
/** public void afterPropertiesSet() throws Exception {
* Preprocess the given map Assert.notNull(attributes2grantedAuthoritiesMap, "attributes2grantedAuthoritiesMap must be set");
* @param orgMap The map to process }
* @return the processed Map
*/
private Map preProcessMap(Map orgMap) {
Map result = new HashMap(orgMap.size());
Iterator it = orgMap.entrySet().iterator();
while ( it.hasNext() ) {
Map.Entry entry = (Map.Entry)it.next();
result.put(entry.getKey(),getGrantedAuthorityCollection(entry.getValue()));
}
return result;
}
/** /**
* Convert the given value to a collection of Granted Authorities * Map the given array of attributes to Spring Security GrantedAuthorities.
* */
* @param value public List<GrantedAuthority> getGrantedAuthorities(Collection<String> attributes) {
* The value to convert to a GrantedAuthority Collection ArrayList<GrantedAuthority> gaList = new ArrayList<GrantedAuthority>();
* @return Collection containing the GrantedAuthority Collection for (String attribute : attributes) {
*/ Collection<GrantedAuthority> c = attributes2grantedAuthoritiesMap.get(attribute);
private Collection getGrantedAuthorityCollection(Object value) { if ( c != null ) { gaList.addAll(c); }
Collection result = new ArrayList(); }
addGrantedAuthorityCollection(result,value); gaList.trimToSize();
return result;
}
/** return gaList;
* Convert the given value to a collection of Granted Authorities, }
* adding the result to the given result collection.
*
* @param value
* The value to convert to a GrantedAuthority Collection
* @return Collection containing the GrantedAuthority Collection
*/
private void addGrantedAuthorityCollection(Collection result, Object value) {
if ( value != null ) {
if ( value instanceof Collection ) {
addGrantedAuthorityCollection(result,(Collection)value);
} else if ( value instanceof Object[] ) {
addGrantedAuthorityCollection(result,(Object[])value);
} else if ( value instanceof String ) {
addGrantedAuthorityCollection(result,(String)value);
} else if ( value instanceof GrantedAuthority ) {
result.add(value);
} else {
throw new IllegalArgumentException("Invalid object type: "+value.getClass().getName());
}
}
}
private void addGrantedAuthorityCollection(Collection result, Collection value) { /**
Iterator it = value.iterator(); * @return Returns the attributes2grantedAuthoritiesMap.
while ( it.hasNext() ) { */
addGrantedAuthorityCollection(result,it.next()); public Map getAttributes2grantedAuthoritiesMap() {
} return attributes2grantedAuthoritiesMap;
} }
/**
* @param attributes2grantedAuthoritiesMap The attributes2grantedAuthoritiesMap to set.
*/
public void setAttributes2grantedAuthoritiesMap(final Map<String, Object> attributes2grantedAuthoritiesMap) {
Assert.notEmpty(attributes2grantedAuthoritiesMap,"A non-empty attributes2grantedAuthoritiesMap must be supplied");
this.attributes2grantedAuthoritiesMap = preProcessMap(attributes2grantedAuthoritiesMap);
private void addGrantedAuthorityCollection(Collection result, Object[] value) { try {
for ( int i = 0 ; i < value.length ; i++ ) { mappableAttributes = (String[])this.attributes2grantedAuthoritiesMap.keySet().toArray(new String[]{});
addGrantedAuthorityCollection(result,value[i]); } catch ( ArrayStoreException ase ) {
} throw new IllegalArgumentException("attributes2grantedAuthoritiesMap contains non-String objects as keys");
} }
}
private void addGrantedAuthorityCollection(Collection result, String value) { /**
StringTokenizer st = new StringTokenizer(value,stringSeparator,false); * Preprocess the given map to convert all the values to GrantedAuthority collections
while ( st.hasMoreTokens() ) { *
String nextToken = st.nextToken(); * @param orgMap The map to process
if ( StringUtils.hasText(nextToken) ) { * @return the processed Map
result.add(new GrantedAuthorityImpl(nextToken)); */
} private Map<String, Collection<GrantedAuthority>> preProcessMap(Map<String, Object> orgMap) {
} Map result = new HashMap(orgMap.size());
}
/** for(Map.Entry entry : orgMap.entrySet()) {
* Map the given array of attributes to Spring Security GrantedAuthorities. result.put(entry.getKey(),getGrantedAuthorityCollection(entry.getValue()));
*/ }
public GrantedAuthority[] getGrantedAuthorities(String[] attributes) { return result;
List gaList = new ArrayList(); }
for (int i = 0; i < attributes.length; i++) {
Collection c = (Collection)attributes2grantedAuthoritiesMap.get(attributes[i]);
if ( c != null ) { gaList.addAll(c); }
}
GrantedAuthority[] result = new GrantedAuthority[gaList.size()];
result = (GrantedAuthority[])gaList.toArray(result);
return result;
}
/** /**
* @return Returns the attributes2grantedAuthoritiesMap. * Convert the given value to a collection of Granted Authorities
*/ *
public Map getAttributes2grantedAuthoritiesMap() { * @param value
return attributes2grantedAuthoritiesMap; * The value to convert to a GrantedAuthority Collection
} * @return Collection containing the GrantedAuthority Collection
/** */
* @param attributes2grantedAuthoritiesMap The attributes2grantedAuthoritiesMap to set. private Collection getGrantedAuthorityCollection(Object value) {
*/ Collection result = new ArrayList();
public void setAttributes2grantedAuthoritiesMap(Map attributes2grantedAuthoritiesMap) { addGrantedAuthorityCollection(result,value);
this.attributes2grantedAuthoritiesMap = attributes2grantedAuthoritiesMap; return result;
} }
/**
* Convert the given value to a collection of Granted Authorities,
* adding the result to the given result collection.
*
* @param value
* The value to convert to a GrantedAuthority Collection
* @return Collection containing the GrantedAuthority Collection
*/
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Object value) {
if ( value == null ) {
return;
}
if ( value instanceof Collection ) {
addGrantedAuthorityCollection(result,(Collection)value);
} else if ( value instanceof Object[] ) {
addGrantedAuthorityCollection(result,(Object[])value);
} else if ( value instanceof String ) {
addGrantedAuthorityCollection(result,(String)value);
} else if ( value instanceof GrantedAuthority ) {
result.add((GrantedAuthority) value);
} else {
throw new IllegalArgumentException("Invalid object type: "+value.getClass().getName());
}
}
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Collection value) {
Iterator it = value.iterator();
while ( it.hasNext() ) {
addGrantedAuthorityCollection(result,it.next());
}
}
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Object[] value) {
for ( int i = 0 ; i < value.length ; i++ ) {
addGrantedAuthorityCollection(result,value[i]);
}
}
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, String value) {
StringTokenizer st = new StringTokenizer(value,stringSeparator,false);
while ( st.hasMoreTokens() ) {
String nextToken = st.nextToken();
if ( StringUtils.hasText(nextToken) ) {
result.add(new GrantedAuthorityImpl(nextToken));
}
}
}
/**
*
* @see org.springframework.security.authoritymapping.MappableAttributesRetriever#getMappableAttributes()
*/
public String[] getMappableAttributes() {
return mappableAttributes;
}
/**
* @return Returns the stringSeparator.
*/
public String getStringSeparator() {
return stringSeparator;
}
/**
* @param stringSeparator The stringSeparator to set.
*/
public void setStringSeparator(String stringSeparator) {
this.stringSeparator = stringSeparator;
}
/**
*
* @see org.springframework.security.authoritymapping.MappableAttributesRetriever#getMappableAttributes()
*/
public String[] getMappableAttributes() {
return mappableAttributes;
}
/**
* @return Returns the stringSeparator.
*/
public String getStringSeparator() {
return stringSeparator;
}
/**
* @param stringSeparator The stringSeparator to set.
*/
public void setStringSeparator(String stringSeparator) {
this.stringSeparator = stringSeparator;
}
} }

View File

@ -3,6 +3,9 @@ package org.springframework.security.authoritymapping;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.GrantedAuthorityImpl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
@ -41,10 +44,10 @@ public class SimpleAttributes2GrantedAuthoritiesMapper implements Attributes2Gra
/** /**
* Map the given list of string attributes one-to-one to Spring Security GrantedAuthorities. * Map the given list of string attributes one-to-one to Spring Security GrantedAuthorities.
*/ */
public GrantedAuthority[] getGrantedAuthorities(String[] attributes) { public List<GrantedAuthority> getGrantedAuthorities(Collection<String> attributes) {
GrantedAuthority[] result = new GrantedAuthority[attributes.length]; List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(attributes.size());
for (int i = 0; i < attributes.length; i++) { for (String attribute : attributes) {
result[i] = getGrantedAuthority(attributes[i]); result.add(getGrantedAuthority(attribute));
} }
return result; return result;
} }

View File

@ -70,7 +70,7 @@ public class MethodInvocationPrivilegeEvaluator implements InitializingBean {
} }
if ((authentication == null) || (authentication.getAuthorities() == null) if ((authentication == null) || (authentication.getAuthorities() == null)
|| (authentication.getAuthorities().length == 0)) { || (authentication.getAuthorities().isEmpty())) {
return false; return false;
} }

View File

@ -62,7 +62,7 @@ public class WebInvocationPrivilegeEvaluator implements InitializingBean {
} }
if ((authentication == null) || (authentication.getAuthorities() == null) if ((authentication == null) || (authentication.getAuthorities() == null)
|| (authentication.getAuthorities().length == 0)) { || authentication.getAuthorities().isEmpty()) {
return false; return false;
} }

View File

@ -15,6 +15,8 @@
package org.springframework.security.ldap; package org.springframework.security.ldap;
import java.util.List;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.DirContextOperations;
@ -41,5 +43,5 @@ public interface LdapAuthoritiesPopulator {
* @return the granted authorities for the given user. * @return the granted authorities for the given user.
* *
*/ */
GrantedAuthority[] getGrantedAuthorities(DirContextOperations userData, String username); List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username);
} }

View File

@ -27,8 +27,11 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import javax.naming.directory.SearchControls; import javax.naming.directory.SearchControls;
import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Set; import java.util.Set;
@ -158,7 +161,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @return the extra roles which will be merged with those returned by the group search * @return the extra roles which will be merged with those returned by the group search
*/ */
protected Set getAdditionalRoles(DirContextOperations user, String username) { protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user, String username) {
return null; return null;
} }
@ -169,14 +172,14 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @param user the user who's authorities are required * @param user the user who's authorities are required
* @return the set of roles granted to the user. * @return the set of roles granted to the user.
*/ */
public final GrantedAuthority[] getGrantedAuthorities(DirContextOperations user, String username) { public final List<GrantedAuthority> getGrantedAuthorities(DirContextOperations user, String username) {
String userDn = user.getNameInNamespace(); String userDn = user.getNameInNamespace();
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Getting authorities for user " + userDn); logger.debug("Getting authorities for user " + userDn);
} }
Set roles = getGroupMembershipRoles(userDn, username); Set<GrantedAuthority> roles = getGroupMembershipRoles(userDn, username);
Set extraRoles = getAdditionalRoles(user, username); Set extraRoles = getAdditionalRoles(user, username);
@ -188,10 +191,13 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
roles.add(defaultRole); roles.add(defaultRole);
} }
return (GrantedAuthority[]) roles.toArray(new GrantedAuthority[roles.size()]); List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(roles.size());
result.addAll(roles);
return result;
} }
public Set getGroupMembershipRoles(String userDn, String username) { public Set<GrantedAuthority> getGroupMembershipRoles(String userDn, String username) {
Set authorities = new HashSet(); Set authorities = new HashSet();
if (getGroupSearchBase() == null) { if (getGroupSearchBase() == null) {

View File

@ -1,5 +1,7 @@
package org.springframework.security.ldap.populator; package org.springframework.security.ldap.populator;
import java.util.List;
import org.springframework.security.ldap.LdapAuthoritiesPopulator; import org.springframework.security.ldap.LdapAuthoritiesPopulator;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UserDetailsService;
@ -23,7 +25,7 @@ public class UserDetailsServiceLdapAuthoritiesPopulator implements LdapAuthoriti
this.userDetailsService = userService; this.userDetailsService = userService;
} }
public GrantedAuthority[] getGrantedAuthorities(DirContextOperations userData, String username) { public List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
return userDetailsService.loadUserByUsername(username).getAuthorities(); return userDetailsService.loadUserByUsername(username).getAuthorities();
} }
} }

View File

@ -16,15 +16,18 @@
package org.springframework.security.providers; package org.springframework.security.providers;
import java.security.Principal; import java.security.Principal;
import java.util.Collections;
import java.util.List;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import org.springframework.util.Assert;
/** /**
* Base class for <code>Authentication</code> objects.<p>Implementations which use this class should be immutable.</p> * Base class for <code>Authentication</code> objects.
* <p>
* Implementations which use this class should be immutable.
* *
* @author Ben Alex * @author Ben Alex
* @author Luke Taylor * @author Luke Taylor
@ -34,22 +37,11 @@ public abstract class AbstractAuthenticationToken implements Authentication {
//~ Instance fields ================================================================================================ //~ Instance fields ================================================================================================
private Object details; private Object details;
private GrantedAuthority[] authorities; private List<GrantedAuthority> authorities;
private boolean authenticated = false; private boolean authenticated = false;
//~ Constructors =================================================================================================== //~ Constructors ===================================================================================================
/**
* Retained for compatibility with subclasses written before the
* <tt>AbstractAuthenticationToken(GrantedAuthority[])</tt> constructor
* was introduced.
*
* @deprecated in favour of the constructor which takes a
* <code>GrantedAuthority[]</code> argument.
*/
public AbstractAuthenticationToken() {
}
/** /**
* Creates a token with the supplied array of authorities. * Creates a token with the supplied array of authorities.
* *
@ -60,82 +52,70 @@ public abstract class AbstractAuthenticationToken implements Authentication {
* Authentication#getAuthorities()}<code>null</code> should only be * Authentication#getAuthorities()}<code>null</code> should only be
* presented if the principal has not been authenticated). * presented if the principal has not been authenticated).
*/ */
public AbstractAuthenticationToken(GrantedAuthority[] authorities) { public AbstractAuthenticationToken(List<GrantedAuthority> authorities) {
if (authorities != null) { if (authorities != null) {
for (int i = 0; i < authorities.length; i++) { for (int i = 0; i < authorities.size(); i++) {
Assert.notNull(authorities[i], if(authorities.get(i) == null) {
"Granted authority element " + i + " is null - GrantedAuthority[] cannot contain any null elements"); throw new IllegalArgumentException("Granted authority element " + i
+ " is null - GrantedAuthority[] cannot contain any null elements");
}
} }
this.authorities = Collections.unmodifiableList(authorities);
} }
this.authorities = authorities;
} }
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof AbstractAuthenticationToken) { if (!(obj instanceof AbstractAuthenticationToken)) {
AbstractAuthenticationToken test = (AbstractAuthenticationToken) obj; return false;
if (!((this.getAuthorities() == null) && (test.getAuthorities() == null))) {
if ((this.getAuthorities() == null) || (test.getAuthorities() == null)) {
return false;
}
if (this.getAuthorities().length != test.getAuthorities().length) {
return false;
}
for (int i = 0; i < this.getAuthorities().length; i++) {
if (!this.getAuthorities()[i].equals(test.getAuthorities()[i])) {
return false;
}
}
}
if ((this.details == null) && (test.getDetails() != null)) {
return false;
}
if ((this.details != null) && (test.getDetails() == null)) {
return false;
}
if ((this.details != null) && (!this.details.equals(test.getDetails()))) {
return false;
}
if ((this.getCredentials() == null) && (test.getCredentials() != null)) {
return false;
}
if ((this.getCredentials() != null) && !this.getCredentials().equals(test.getCredentials())) {
return false;
}
if (this.getPrincipal() == null && test.getPrincipal() != null) {
return false;
}
if (this.getPrincipal() != null && !this.getPrincipal().equals(test.getPrincipal())) {
return false;
}
return this.isAuthenticated() == test.isAuthenticated();
} }
return false; AbstractAuthenticationToken test = (AbstractAuthenticationToken) obj;
if (!(authorities == null && test.authorities == null)) {
// Not both null
if (authorities == null || test.authorities == null) {
return false;
}
if(!authorities.equals(test.authorities)) {
return false;
}
}
if ((this.details == null) && (test.getDetails() != null)) {
return false;
}
if ((this.details != null) && (test.getDetails() == null)) {
return false;
}
if ((this.details != null) && (!this.details.equals(test.getDetails()))) {
return false;
}
if ((this.getCredentials() == null) && (test.getCredentials() != null)) {
return false;
}
if ((this.getCredentials() != null) && !this.getCredentials().equals(test.getCredentials())) {
return false;
}
if (this.getPrincipal() == null && test.getPrincipal() != null) {
return false;
}
if (this.getPrincipal() != null && !this.getPrincipal().equals(test.getPrincipal())) {
return false;
}
return this.isAuthenticated() == test.isAuthenticated();
} }
public GrantedAuthority[] getAuthorities() { public List<GrantedAuthority> getAuthorities() {
if (authorities == null) { return authorities;
return null;
}
GrantedAuthority[] copy = new GrantedAuthority[authorities.length];
System.arraycopy(authorities, 0, copy, 0, authorities.length);
return copy;
} }
public Object getDetails() { public Object getDetails() {
@ -146,7 +126,7 @@ public abstract class AbstractAuthenticationToken implements Authentication {
if (this.getPrincipal() instanceof UserDetails) { if (this.getPrincipal() instanceof UserDetails) {
return ((UserDetails) this.getPrincipal()).getUsername(); return ((UserDetails) this.getPrincipal()).getUsername();
} }
if (getPrincipal() instanceof Principal) { if (getPrincipal() instanceof Principal) {
return ((Principal)getPrincipal()).getName(); return ((Principal)getPrincipal()).getName();
} }
@ -157,12 +137,9 @@ public abstract class AbstractAuthenticationToken implements Authentication {
public int hashCode() { public int hashCode() {
int code = 31; int code = 31;
// Copy authorities to local variable for performance (SEC-223)
GrantedAuthority[] authorities = this.getAuthorities();
if (authorities != null) { if (authorities != null) {
for (int i = 0; i < authorities.length; i++) { for (GrantedAuthority authority : authorities) {
code ^= authorities[i].hashCode(); code ^= authority.hashCode();
} }
} }
@ -205,15 +182,16 @@ public abstract class AbstractAuthenticationToken implements Authentication {
sb.append("Authenticated: ").append(this.isAuthenticated()).append("; "); sb.append("Authenticated: ").append(this.isAuthenticated()).append("; ");
sb.append("Details: ").append(this.getDetails()).append("; "); sb.append("Details: ").append(this.getDetails()).append("; ");
if (this.getAuthorities() != null) { if (authorities != null) {
sb.append("Granted Authorities: "); sb.append("Granted Authorities: ");
for (int i = 0; i < this.getAuthorities().length; i++) { int i = 0;
if (i > 0) { for (GrantedAuthority authority: authorities) {
if (i++ > 0) {
sb.append(", "); sb.append(", ");
} }
sb.append(this.getAuthorities()[i].toString()); sb.append(authority);
} }
} else { } else {
sb.append("Not granted any authorities"); sb.append("Not granted any authorities");

View File

@ -15,6 +15,9 @@
package org.springframework.security.providers; package org.springframework.security.providers;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.util.AuthorityUtils; import org.springframework.security.util.AuthorityUtils;
@ -44,10 +47,14 @@ public class TestingAuthenticationToken extends AbstractAuthenticationToken {
public TestingAuthenticationToken(Object principal, Object credentials, String... authorities) { public TestingAuthenticationToken(Object principal, Object credentials, String... authorities) {
this(principal, credentials, AuthorityUtils.stringArrayToAuthorityArray(authorities)); this(principal, credentials, AuthorityUtils.createAuthorityList(authorities));
} }
public TestingAuthenticationToken(Object principal, Object credentials, GrantedAuthority[] authorities) { public TestingAuthenticationToken(Object principal, Object credentials, GrantedAuthority[] authorities) {
this(principal, credentials, Arrays.asList(authorities));
}
public TestingAuthenticationToken(Object principal, Object credentials, List<GrantedAuthority> authorities) {
super(authorities); super(authorities);
this.principal = principal; this.principal = principal;
this.credentials = credentials; this.credentials = credentials;

View File

@ -15,6 +15,9 @@
package org.springframework.security.providers; package org.springframework.security.providers;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
@ -51,6 +54,13 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
setAuthenticated(false); setAuthenticated(false);
} }
/**
* @deprecated use the list of authorities version
*/
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, GrantedAuthority[] authorities) {
this(principal, credentials, Arrays.asList(authorities));
}
/** /**
* This constructor should only be used by <code>AuthenticationManager</code> or <code>AuthenticationProvider</code> * This constructor should only be used by <code>AuthenticationManager</code> or <code>AuthenticationProvider</code>
* implementations that are satisfied with producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>) * implementations that are satisfied with producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
@ -60,13 +70,14 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
* @param credentials * @param credentials
* @param authorities * @param authorities
*/ */
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, GrantedAuthority[] authorities) { public UsernamePasswordAuthenticationToken(Object principal, Object credentials, List<GrantedAuthority> authorities) {
super(authorities); super(authorities);
this.principal = principal; this.principal = principal;
this.credentials = credentials; this.credentials = credentials;
super.setAuthenticated(true); // must use super, as we override super.setAuthenticated(true); // must use super, as we override
} }
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
public Object getCredentials() { public Object getCredentials() {

View File

@ -20,6 +20,8 @@ import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.AbstractAuthenticationToken; import org.springframework.security.providers.AbstractAuthenticationToken;
import java.io.Serializable; import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/** /**
@ -37,7 +39,11 @@ public class AnonymousAuthenticationToken extends AbstractAuthenticationToken im
//~ Constructors =================================================================================================== //~ Constructors ===================================================================================================
/** public AnonymousAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) {
this(key, principal, Arrays.asList(authorities));
}
/**
* Constructor. * Constructor.
* *
* @param key to identify if this object made by an authorised client * @param key to identify if this object made by an authorised client
@ -46,11 +52,11 @@ public class AnonymousAuthenticationToken extends AbstractAuthenticationToken im
* *
* @throws IllegalArgumentException if a <code>null</code> was passed * @throws IllegalArgumentException if a <code>null</code> was passed
*/ */
public AnonymousAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) { public AnonymousAuthenticationToken(String key, Object principal, List<GrantedAuthority> authorities) {
super(authorities); super(authorities);
if ((key == null) || ("".equals(key)) || (principal == null) || "".equals(principal) || (authorities == null) if ((key == null) || ("".equals(key)) || (principal == null) || "".equals(principal) || (authorities == null)
|| (authorities.length == 0)) { || (authorities.isEmpty())) {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor"); throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
} }

View File

@ -153,12 +153,12 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
Assert.notNull(loginConfig, "loginConfig must be set on " + getClass()); Assert.notNull(loginConfig, "loginConfig must be set on " + getClass());
Assert.hasLength(loginContextName, "loginContextName must be set on " + getClass()); Assert.hasLength(loginContextName, "loginContextName must be set on " + getClass());
configureJaas(loginConfig); configureJaas(loginConfig);
Assert.notNull(Configuration.getConfiguration(), Assert.notNull(Configuration.getConfiguration(),
"As per http://java.sun.com/j2se/1.5.0/docs/api/javax/security/auth/login/Configuration.html " "As per http://java.sun.com/j2se/1.5.0/docs/api/javax/security/auth/login/Configuration.html "
+ "\"If a Configuration object was set via the Configuration.setConfiguration method, then that object is " + "\"If a Configuration object was set via the Configuration.setConfiguration method, then that object is "
@ -190,10 +190,10 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
loginContext.login(); loginContext.login();
//create a set to hold the authorities, and add any that have already been applied. //create a set to hold the authorities, and add any that have already been applied.
Set authorities = new HashSet(); Set<GrantedAuthority> authorities = new HashSet();
if (request.getAuthorities() != null) { if (request.getAuthorities() != null) {
authorities.addAll(Arrays.asList(request.getAuthorities())); authorities.addAll(request.getAuthorities());
} }
//get the subject principals and pass them to each of the AuthorityGranters //get the subject principals and pass them to each of the AuthorityGranters
@ -219,7 +219,7 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
//Convert the authorities set back to an array and apply it to the token. //Convert the authorities set back to an array and apply it to the token.
JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(), JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(),
request.getCredentials(), request.getCredentials(),
(GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]), loginContext); (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[0]), loginContext);
//Publish the success event //Publish the success event
publishSuccessEvent(result); publishSuccessEvent(result);
@ -379,7 +379,7 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
*/ */
protected void publishSuccessEvent(UsernamePasswordAuthenticationToken token) { protected void publishSuccessEvent(UsernamePasswordAuthenticationToken token) {
if (applicationEventPublisher != null) { if (applicationEventPublisher != null) {
applicationEventPublisher.publishEvent(new JaasAuthenticationSuccessEvent(token)); applicationEventPublisher.publishEvent(new JaasAuthenticationSuccessEvent(token));
} }
} }

View File

@ -15,6 +15,8 @@
package org.springframework.security.providers.ldap; package org.springframework.security.providers.ldap;
import java.util.List;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException; import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationServiceException; import org.springframework.security.AuthenticationServiceException;
@ -28,6 +30,7 @@ import org.springframework.security.providers.UsernamePasswordAuthenticationToke
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.ldap.LdapUserDetailsMapper; import org.springframework.security.userdetails.ldap.LdapUserDetailsMapper;
import org.springframework.security.userdetails.ldap.UserDetailsContextMapper; import org.springframework.security.userdetails.ldap.UserDetailsContextMapper;
import org.springframework.security.util.AuthorityUtils;
import org.springframework.context.support.MessageSourceAccessor; import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.ldap.NamingException; import org.springframework.ldap.NamingException;
import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.DirContextOperations;
@ -228,7 +231,7 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
try { try {
DirContextOperations userData = getAuthenticator().authenticate(authentication); DirContextOperations userData = getAuthenticator().authenticate(authentication);
GrantedAuthority[] extraAuthorities = loadUserAuthorities(userData, username, password); List<GrantedAuthority> extraAuthorities = loadUserAuthorities(userData, username, password);
UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, username, extraAuthorities); UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, username, extraAuthorities);
@ -239,7 +242,7 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
} }
} }
protected GrantedAuthority[] loadUserAuthorities(DirContextOperations userData, String username, String password) { protected List<GrantedAuthority> loadUserAuthorities(DirContextOperations userData, String username, String password) {
return getAuthoritiesPopulator().getGrantedAuthorities(userData, username); return getAuthoritiesPopulator().getGrantedAuthorities(userData, username);
} }
@ -257,8 +260,8 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
//~ Inner Classes ================================================================================================== //~ Inner Classes ==================================================================================================
private static class NullAuthoritiesPopulator implements LdapAuthoritiesPopulator { private static class NullAuthoritiesPopulator implements LdapAuthoritiesPopulator {
public GrantedAuthority[] getGrantedAuthorities(DirContextOperations userDetails, String username) { public List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userDetails, String username) {
return new GrantedAuthority[0]; return AuthorityUtils.NO_AUTHORITIES;
} }
} }
} }

View File

@ -1,9 +1,12 @@
package org.springframework.security.providers.preauth; package org.springframework.security.providers.preauth;
import java.util.Arrays;
import org.springframework.security.providers.AuthenticationProvider; import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException; import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException; import org.springframework.security.BadCredentialsException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.AuthenticationUserDetailsService; import org.springframework.security.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsChecker; import org.springframework.security.userdetails.UserDetailsChecker;
@ -34,7 +37,7 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
private static final Log logger = LogFactory.getLog(PreAuthenticatedAuthenticationProvider.class); private static final Log logger = LogFactory.getLog(PreAuthenticatedAuthenticationProvider.class);
private AuthenticationUserDetailsService preAuthenticatedUserDetailsService = null; private AuthenticationUserDetailsService preAuthenticatedUserDetailsService = null;
private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker(); private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
private boolean throwExceptionWhenTokenRejected = false; private boolean throwExceptionWhenTokenRejected = false;
private int order = -1; // default: same as non-ordered private int order = -1; // default: same as non-ordered
@ -63,7 +66,7 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
if (authentication.getPrincipal() == null) { if (authentication.getPrincipal() == null) {
logger.debug("No pre-authenticated principal found in request."); logger.debug("No pre-authenticated principal found in request.");
if (throwExceptionWhenTokenRejected) { if (throwExceptionWhenTokenRejected) {
throw new BadCredentialsException("No pre-authenticated principal found in request."); throw new BadCredentialsException("No pre-authenticated principal found in request.");
} }
@ -75,16 +78,17 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
if (throwExceptionWhenTokenRejected) { if (throwExceptionWhenTokenRejected) {
throw new BadCredentialsException("No pre-authenticated credentials found in request."); throw new BadCredentialsException("No pre-authenticated credentials found in request.");
} }
return null; return null;
} }
UserDetails ud = preAuthenticatedUserDetailsService.loadUserDetails(authentication); UserDetails ud = preAuthenticatedUserDetailsService.loadUserDetails(authentication);
userDetailsChecker.check(ud); userDetailsChecker.check(ud);
PreAuthenticatedAuthenticationToken result = PreAuthenticatedAuthenticationToken result =
new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(), ud.getAuthorities()); new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(),
ud.getAuthorities().toArray(new GrantedAuthority[0]));
result.setDetails(authentication.getDetails()); result.setDetails(authentication.getDetails());
return result; return result;
@ -114,22 +118,22 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
order = i; order = i;
} }
/** /**
* If true, causes the provider to throw a BadCredentialsException if the presented authentication * If true, causes the provider to throw a BadCredentialsException if the presented authentication
* request is invalid (contains a null principal or credentials). Otherwise it will just return * request is invalid (contains a null principal or credentials). Otherwise it will just return
* null. Defaults to false. * null. Defaults to false.
*/ */
public void setThrowExceptionWhenTokenRejected(boolean throwExceptionWhenTokenRejected) { public void setThrowExceptionWhenTokenRejected(boolean throwExceptionWhenTokenRejected) {
this.throwExceptionWhenTokenRejected = throwExceptionWhenTokenRejected; this.throwExceptionWhenTokenRejected = throwExceptionWhenTokenRejected;
} }
/** /**
* Sets the strategy which will be used to validate the loaded <tt>UserDetails</tt> object * Sets the strategy which will be used to validate the loaded <tt>UserDetails</tt> object
* for the user. Defaults to an {@link AccountStatusUserDetailsChecker}. * for the user. Defaults to an {@link AccountStatusUserDetailsChecker}.
* @param userDetailsChecker * @param userDetailsChecker
*/ */
public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) { public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) {
Assert.notNull(userDetailsChecker, "userDetailsChacker cannot be null"); Assert.notNull(userDetailsChecker, "userDetailsChacker cannot be null");
this.userDetailsChecker = userDetailsChecker; this.userDetailsChecker = userDetailsChecker;
} }
} }

View File

@ -1,5 +1,8 @@
package org.springframework.security.providers.preauth; package org.springframework.security.providers.preauth;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.providers.AbstractAuthenticationToken; import org.springframework.security.providers.AbstractAuthenticationToken;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
@ -37,6 +40,14 @@ public class PreAuthenticatedAuthenticationToken extends AbstractAuthenticationT
this.credentials = aCredentials; this.credentials = aCredentials;
} }
/**
*
* @deprecated
*/
public PreAuthenticatedAuthenticationToken(Object aPrincipal, Object aCredentials, GrantedAuthority[] anAuthorities) {
this(aPrincipal, aCredentials, Arrays.asList(anAuthorities));
}
/** /**
* Constructor used for an authentication response. The {@link * Constructor used for an authentication response. The {@link
* org.springframework.security.Authentication#isAuthenticated()} will return * org.springframework.security.Authentication#isAuthenticated()} will return
@ -47,7 +58,7 @@ public class PreAuthenticatedAuthenticationToken extends AbstractAuthenticationT
* @param anAuthorities * @param anAuthorities
* The granted authorities * The granted authorities
*/ */
public PreAuthenticatedAuthenticationToken(Object aPrincipal, Object aCredentials, GrantedAuthority[] anAuthorities) { public PreAuthenticatedAuthenticationToken(Object aPrincipal, Object aCredentials, List<GrantedAuthority> anAuthorities) {
super(anAuthorities); super(anAuthorities);
this.principal = aPrincipal; this.principal = aPrincipal;
this.credentials = aCredentials; this.credentials = aCredentials;

View File

@ -1,5 +1,7 @@
package org.springframework.security.providers.preauth; package org.springframework.security.providers.preauth;
import java.util.List;
import org.springframework.security.userdetails.AuthenticationUserDetailsService; import org.springframework.security.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.User;
@ -20,7 +22,7 @@ import org.springframework.util.Assert;
* PreAuthenticatedAuthenticationProvider anyway), and the Granted Authorities * PreAuthenticatedAuthenticationProvider anyway), and the Granted Authorities
* are retrieved from the details object as returned by * are retrieved from the details object as returned by
* PreAuthenticatedAuthenticationToken.getDetails(). * PreAuthenticatedAuthenticationToken.getDetails().
* *
* <p> * <p>
* The details object as returned by PreAuthenticatedAuthenticationToken.getDetails() must implement the * The details object as returned by PreAuthenticatedAuthenticationToken.getDetails() must implement the
* {@link GrantedAuthoritiesContainer} interface for this implementation to work. * {@link GrantedAuthoritiesContainer} interface for this implementation to work.
@ -29,27 +31,27 @@ import org.springframework.util.Assert;
* @since 2.0 * @since 2.0
*/ */
public class PreAuthenticatedGrantedAuthoritiesUserDetailsService implements AuthenticationUserDetailsService { public class PreAuthenticatedGrantedAuthoritiesUserDetailsService implements AuthenticationUserDetailsService {
/** /**
* Get a UserDetails object based on the user name contained in the given * Get a UserDetails object based on the user name contained in the given
* token, and the GrantedAuthorities as returned by the * token, and the GrantedAuthorities as returned by the
* GrantedAuthoritiesContainer implementation as returned by * GrantedAuthoritiesContainer implementation as returned by
* the token.getDetails() method. * the token.getDetails() method.
*/ */
public final UserDetails loadUserDetails(Authentication token) throws AuthenticationException { public final UserDetails loadUserDetails(Authentication token) throws AuthenticationException {
Assert.notNull(token.getDetails()); Assert.notNull(token.getDetails());
Assert.isInstanceOf(GrantedAuthoritiesContainer.class, token.getDetails()); Assert.isInstanceOf(GrantedAuthoritiesContainer.class, token.getDetails());
GrantedAuthority[] authorities = ((GrantedAuthoritiesContainer) token.getDetails()).getGrantedAuthorities(); List<GrantedAuthority> authorities = ((GrantedAuthoritiesContainer) token.getDetails()).getGrantedAuthorities();
UserDetails ud = createuserDetails(token, authorities); UserDetails ud = createuserDetails(token, authorities);
return ud; return ud;
} }
/** /**
* Creates the final <tt>UserDetails</tt> object. Can be overridden to customize the contents. * Creates the final <tt>UserDetails</tt> object. Can be overridden to customize the contents.
* *
* @param token the authentication request token * @param token the authentication request token
* @param authorities the pre-authenticated authorities. * @param authorities the pre-authenticated authorities.
*/ */
protected UserDetails createuserDetails(Authentication token, GrantedAuthority[] authorities) { protected UserDetails createuserDetails(Authentication token, List<GrantedAuthority> authorities) {
return new User(token.getName(), "N/A", true, true, true, true, authorities); return new User(token.getName(), "N/A", true, true, true, true, authorities);
} }
} }

View File

@ -15,6 +15,8 @@
package org.springframework.security.providers.rcp; package org.springframework.security.providers.rcp;
import java.util.List;
import org.springframework.security.AuthenticationException; import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager; import org.springframework.security.AuthenticationManager;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
@ -27,9 +29,10 @@ import org.springframework.util.Assert;
/** /**
* Server-side processor of a remote authentication request.<P>This bean requires no security interceptor to * Server-side processor of a remote authentication request.
* protect it. Instead, the bean uses the configured <code>AuthenticationManager</code> to resolve an authentication * <p>
* request.</p> * This bean requires no security interceptor to protect it. Instead, the bean uses the configured
* <code>AuthenticationManager</code> to resolve an authentication request.
* *
* @author Ben Alex * @author Ben Alex
* @version $Id$ * @version $Id$
@ -46,11 +49,13 @@ public class RemoteAuthenticationManagerImpl implements RemoteAuthenticationMana
} }
public GrantedAuthority[] attemptAuthentication(String username, String password) public GrantedAuthority[] attemptAuthentication(String username, String password)
throws RemoteAuthenticationException { throws RemoteAuthenticationException {
UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken(username, password); UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken(username, password);
try { try {
return authenticationManager.authenticate(request).getAuthorities(); List<GrantedAuthority> authorities = authenticationManager.authenticate(request).getAuthorities();
return authorities == null ? null : authorities.toArray(new GrantedAuthority[authorities.size()]);
} catch (AuthenticationException authEx) { } catch (AuthenticationException authEx) {
throw new RemoteAuthenticationException(authEx.getMessage()); throw new RemoteAuthenticationException(authEx.getMessage());
} }

View File

@ -16,6 +16,8 @@
package org.springframework.security.providers.rememberme; package org.springframework.security.providers.rememberme;
import java.io.Serializable; import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.AbstractAuthenticationToken; import org.springframework.security.providers.AbstractAuthenticationToken;
@ -37,6 +39,10 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken i
//~ Constructors =================================================================================================== //~ Constructors ===================================================================================================
public RememberMeAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) {
this(key, principal, Arrays.asList(authorities));
}
/** /**
* Constructor. * Constructor.
* *
@ -46,7 +52,7 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken i
* *
* @throws IllegalArgumentException if a <code>null</code> was passed * @throws IllegalArgumentException if a <code>null</code> was passed
*/ */
public RememberMeAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) { public RememberMeAuthenticationToken(String key, Object principal, List<GrantedAuthority> authorities) {
super(authorities); super(authorities);
if ((key == null) || ("".equals(key)) || (principal == null) || "".equals(principal)) { if ((key == null) || ("".equals(key)) || (principal == null) || "".equals(principal)) {

View File

@ -1,133 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.providers.x509.cache.NullX509UserCache;
import org.springframework.security.userdetails.UserDetails;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;
import java.security.cert.X509Certificate;
/**
* Processes an X.509 authentication request.<p>The request will typically originate from {@link
* org.springframework.security.ui.x509.X509ProcessingFilter}).</p>
*
* @author Luke Taylor
* @deprecated superceded by the preauth provider. Use the X.509 authentication support in org.springframework.security.ui.preauth.x509 instead
* or namespace support via the &lt;x509 /&gt; element.
* @version $Id$
*/
public class X509AuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(X509AuthenticationProvider.class);
//~ Instance fields ================================================================================================
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private X509AuthoritiesPopulator x509AuthoritiesPopulator;
private X509UserCache userCache = new NullX509UserCache();
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.notNull(userCache, "An x509UserCache must be set");
Assert.notNull(x509AuthoritiesPopulator, "An X509AuthoritiesPopulator must be set");
Assert.notNull(this.messages, "A message source must be set");
}
/**
* If the supplied authentication token contains a certificate then this will be passed to the configured
* {@link X509AuthoritiesPopulator} to obtain the user details and authorities for the user identified by the
* certificate.<p>If no certificate is present (for example, if the filter is applied to an HttpRequest for
* which client authentication hasn't been configured in the container) then a BadCredentialsException will be
* raised.</p>
*
* @param authentication the authentication request.
*
* @return an X509AuthenticationToken containing the authorities of the principal represented by the certificate.
*
* @throws AuthenticationException if the {@link X509AuthoritiesPopulator} rejects the certficate.
* @throws BadCredentialsException if no certificate was presented in the authentication request.
*/
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
if (logger.isDebugEnabled()) {
logger.debug("X509 authentication request: " + authentication);
}
X509Certificate clientCertificate = (X509Certificate) authentication.getCredentials();
if (clientCertificate == null) {
throw new BadCredentialsException(messages.getMessage("X509AuthenticationProvider.certificateNull",
"Certificate is null"));
}
UserDetails user = userCache.getUserFromCache(clientCertificate);
if (user == null) {
if (logger.isDebugEnabled()) {
logger.debug("Authenticating with certificate " + clientCertificate);
}
user = x509AuthoritiesPopulator.getUserDetails(clientCertificate);
userCache.putUserInCache(clientCertificate, user);
}
X509AuthenticationToken result = new X509AuthenticationToken(user, clientCertificate, user.getAuthorities());
result.setDetails(authentication.getDetails());
return result;
}
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
public void setX509AuthoritiesPopulator(X509AuthoritiesPopulator x509AuthoritiesPopulator) {
this.x509AuthoritiesPopulator = x509AuthoritiesPopulator;
}
public void setX509UserCache(X509UserCache cache) {
this.userCache = cache;
}
public boolean supports(Class authentication) {
return X509AuthenticationToken.class.isAssignableFrom(authentication);
}
}

View File

@ -1,77 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.AbstractAuthenticationToken;
import java.security.cert.X509Certificate;
/**
* <code>Authentication</code> implementation for X.509 client-certificate authentication.
*
* @author Luke Taylor
* @deprecated superceded by the preauth provider. Use the X.509 authentication support in org.springframework.security.ui.preauth.x509 instead.
* @version $Id$
*/
public class X509AuthenticationToken extends AbstractAuthenticationToken {
//~ Instance fields ================================================================================================
private static final long serialVersionUID = 1L;
private Object principal;
private X509Certificate credentials;
//~ Constructors ===================================================================================================
/**
* Used for an authentication request. The {@link org.springframework.security.Authentication#isAuthenticated()} will return
* <code>false</code>.
*
* @param credentials the certificate
*/
public X509AuthenticationToken(X509Certificate credentials) {
super(null);
this.credentials = credentials;
}
/**
* Used for an authentication response object. The {@link org.springframework.security.Authentication#isAuthenticated()}
* will return <code>true</code>.
*
* @param principal the principal, which is generally a
* <code>UserDetails</code>
* @param credentials the certificate
* @param authorities the authorities
*/
public X509AuthenticationToken(Object principal, X509Certificate credentials, GrantedAuthority[] authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
setAuthenticated(true);
}
//~ Methods ========================================================================================================
public Object getCredentials() {
return credentials;
}
public Object getPrincipal() {
return principal;
}
}

View File

@ -1,55 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509;
import org.springframework.security.AuthenticationException;
import org.springframework.security.userdetails.UserDetails;
import java.security.cert.X509Certificate;
/**
* Populates the <code>UserDetails</code> associated with the X.509
* certificate presented by a client.
* <p>
* Although the certificate will already have been validated by the web container,
* implementations may choose to perform additional application-specific checks on
* the certificate content here. If an implementation chooses to reject the certificate,
* it should throw a {@link org.springframework.security.BadCredentialsException}.
* </p>
*
* @author Luke Taylor
* @deprecated
* @version $Id$
*/
public interface X509AuthoritiesPopulator {
//~ Methods ========================================================================================================
/**
* Obtains the granted authorities for the specified user.<p>May throw any
* <code>AuthenticationException</code> or return <code>null</code> if the authorities are unavailable.</p>
*
* @param userCertificate the X.509 certificate supplied
*
* @return the details of the indicated user (at minimum the granted authorities and the username)
*
* @throws AuthenticationException if the user details are not available or the certificate isn't valid for the
* application's purpose.
*/
UserDetails getUserDetails(X509Certificate userCertificate)
throws AuthenticationException;
}

View File

@ -1,44 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509;
import org.springframework.security.userdetails.UserDetails;
import java.security.cert.X509Certificate;
/**
* Provides a cache of {@link UserDetails} objects for the
* {@link X509AuthenticationProvider}.
* <p>
* Similar in function to the {@link org.springframework.security.providers.dao.UserCache}
* used by the Dao provider, but the cache is keyed with the user's certificate
* rather than the user name.
* </p>
*
* @author Luke Taylor
* @deprecated
* @version $Id$
*/
public interface X509UserCache {
//~ Methods ========================================================================================================
UserDetails getUserFromCache(X509Certificate userCertificate);
void putUserInCache(X509Certificate key, UserDetails user);
void removeUserFromCache(X509Certificate key);
}

View File

@ -1,109 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509.cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.Element;
import net.sf.ehcache.Ehcache;
import org.springframework.security.providers.x509.X509UserCache;
import org.springframework.security.userdetails.UserDetails;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.util.Assert;
import java.security.cert.X509Certificate;
/**
* Caches <code>User</code> objects using a Spring IoC defined <a
* href="http://ehcache.sourceforge.net">EHCACHE</a>.
*
* @author Luke Taylor
* @author Ben Alex
* @deprecated use the X509 preauthenticated
* @version $Id$
*/
public class EhCacheBasedX509UserCache implements X509UserCache, InitializingBean {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(EhCacheBasedX509UserCache.class);
//~ Instance fields ================================================================================================
private Ehcache cache;
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, "cache is mandatory");
}
public UserDetails getUserFromCache(X509Certificate userCert) {
Element element = null;
try {
element = cache.get(userCert);
} catch (CacheException cacheException) {
throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage());
}
if (logger.isDebugEnabled()) {
String subjectDN = "unknown";
if ((userCert != null) && (userCert.getSubjectDN() != null)) {
subjectDN = userCert.getSubjectDN().toString();
}
logger.debug("X.509 Cache hit. SubjectDN: " + subjectDN);
}
if (element == null) {
return null;
} else {
return (UserDetails) element.getValue();
}
}
public void putUserInCache(X509Certificate userCert, UserDetails user) {
Element element = new Element(userCert, user);
if (logger.isDebugEnabled()) {
logger.debug("Cache put: " + userCert.getSubjectDN());
}
cache.put(element);
}
public void removeUserFromCache(X509Certificate userCert) {
if (logger.isDebugEnabled()) {
logger.debug("Cache remove: " + userCert.getSubjectDN());
}
cache.remove(userCert);
}
public void setCache(Ehcache cache) {
this.cache = cache;
}
}

View File

@ -1,42 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509.cache;
import org.springframework.security.providers.x509.X509UserCache;
import org.springframework.security.userdetails.UserDetails;
import java.security.cert.X509Certificate;
/**
* "Cache" that doesn't do any caching.
*
* @author Luke Taylor
* @deprecated
* @version $Id$
*/
public class NullX509UserCache implements X509UserCache {
//~ Methods ========================================================================================================
public UserDetails getUserFromCache(X509Certificate certificate) {
return null;
}
public void putUserInCache(X509Certificate certificate, UserDetails user) {}
public void removeUserFromCache(X509Certificate certificate) {}
}

View File

@ -1,5 +0,0 @@
<html>
<body>
Deprecated and will be removed in a future version. Use a caching UserDetailsService instead.
</body>
</html>

View File

@ -1,6 +0,0 @@
<html>
<body>
This package is now deprecated and will be removed in a future version.
Use the X.509 authentication support in org.springframework.security.ui.preauth.x509 instead.
</body>
</html>

View File

@ -1,119 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509.populator;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.AuthenticationServiceException;
import org.springframework.security.providers.x509.X509AuthoritiesPopulator;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;
import java.security.cert.X509Certificate;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* Populates the X509 authorities via an {@link org.springframework.security.userdetails.UserDetailsService}.
*
* @author Luke Taylor
* @deprecated This package is now deprecated. Use the X.509 authentication support in
* org.springframework.security.ui.preauth.x509 instead.
* @version $Id$
*/
public class DaoX509AuthoritiesPopulator implements X509AuthoritiesPopulator, InitializingBean, MessageSourceAware {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(DaoX509AuthoritiesPopulator.class);
//~ Instance fields ================================================================================================
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private Pattern subjectDNPattern;
private String subjectDNRegex = "CN=(.*?),";
private UserDetailsService userDetailsService;
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.notNull(userDetailsService, "An authenticationDao must be set");
Assert.notNull(this.messages, "A message source must be set");
subjectDNPattern = Pattern.compile(subjectDNRegex, Pattern.CASE_INSENSITIVE);
}
public UserDetails getUserDetails(X509Certificate clientCert) throws AuthenticationException {
String subjectDN = clientCert.getSubjectDN().getName();
Matcher matcher = subjectDNPattern.matcher(subjectDN);
if (!matcher.find()) {
throw new BadCredentialsException(messages.getMessage("DaoX509AuthoritiesPopulator.noMatching",
new Object[] {subjectDN}, "No matching pattern was found in subjectDN: {0}"));
}
if (matcher.groupCount() != 1) {
throw new IllegalArgumentException("Regular expression must contain a single group ");
}
String userName = matcher.group(1);
UserDetails user = this.userDetailsService.loadUserByUsername(userName);
if (user == null) {
throw new AuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
return user;
}
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the regular expression which will by used to extract the user name from the certificate's Subject
* DN.
* <p>It should contain a single group; for example the default expression "CN=(.?)," matches the common
* name field. So "CN=Jimi Hendrix, OU=..." will give a user name of "Jimi Hendrix".</p>
* <p>The matches are case insensitive. So "emailAddress=(.?)," will match "EMAILADDRESS=jimi@hendrix.org,
* CN=..." giving a user name "jimi@hendrix.org"</p>
*
* @param subjectDNRegex the regular expression to find in the subject
*/
public void setSubjectDNRegex(String subjectDNRegex) {
this.subjectDNRegex = subjectDNRegex;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
}

View File

@ -1,7 +0,0 @@
<html>
<body>
This package is now deprecated and will be removed in a future version.
Use the X.509 authentication support in org.springframework.security.ui.preauth.x509 instead.
Authorities are loaded by a UserDetailsService.
</body>
</html>

View File

@ -15,8 +15,8 @@
package org.springframework.security.runas; package org.springframework.security.runas;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Vector;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
@ -28,22 +28,23 @@ import org.springframework.util.Assert;
/** /**
* Basic concrete implementation of a {@link RunAsManager}.<p>Is activated if any {@link * Basic concrete implementation of a {@link RunAsManager}.
* ConfigAttribute#getAttribute()} is prefixed with <Code>RUN_AS_</code>. If found, it generates a new {@link * <p>
* RunAsUserToken} containing the same principal, credentials and granted authorities as the original {@link * Is activated if any {@link ConfigAttribute#getAttribute()} is prefixed with <Code>RUN_AS_</code>.
* Authentication} object, along with {@link GrantedAuthorityImpl}s for each <code>RUN_AS_</code> indicated. The * If found, it generates a new {@link RunAsUserToken} containing the same principal, credentials and granted
* created <code>GrantedAuthorityImpl</code>s will be prefixed with a special prefix indicating that it is a role * authorities as the original {@link Authentication} object, along with {@link GrantedAuthorityImpl}s for each
* (default prefix value is <code>ROLE_</code>), and then the remainder of the <code>RUN_AS_</code> keyword. For * <code>RUN_AS_</code> indicated. The created <code>GrantedAuthorityImpl</code>s will be prefixed with a special
* example, <code>RUN_AS_FOO</code> will result in the creation of a granted authority of * prefix indicating that it is a role (default prefix value is <code>ROLE_</code>), and then the remainder of the
* <code>ROLE_RUN_AS_FOO</code>. * <code>RUN_AS_</code> keyword. For example, <code>RUN_AS_FOO</code> will result in the creation of a granted
* authority of <code>ROLE_RUN_AS_FOO</code>.
* <p> * <p>
* The role prefix may be overriden from the default, to match that used elsewhere, for example when using an * The role prefix may be overriden from the default, to match that used elsewhere, for example when using an
* existing role database with another prefix. An empty role prefix may also be specified. Note however that there are * existing role database with another prefix. An empty role prefix may also be specified. Note however that there are
* potential issues with using an empty role prefix since different categories of {@link * potential issues with using an empty role prefix since different categories of {@link ConfigAttribute} can not be
* org.springframework.security.ConfigAttribute} can not be properly discerned based on the prefix, with possible consequences * properly discerned based on the prefix, with possible consequences when performing voting and other actions.
* when performing voting and other actions. However, this option may be of some use when using preexisting role names * However, this option may be of some use when using preexisting role names without a prefix, and no ability exists to
* without a prefix, and no ability exists to prefix them with a role prefix on reading them in, such as provided for * prefix them with a role prefix on reading them in, such as provided for example in
* example in {@link org.springframework.security.userdetails.jdbc.JdbcDaoImpl}. * {@link org.springframework.security.userdetails.jdbc.JdbcDaoImpl}.
* *
* @author Ben Alex * @author Ben Alex
* @author colin sampaleanu * @author colin sampaleanu
@ -62,12 +63,11 @@ public class RunAsManagerImpl implements RunAsManager, InitializingBean {
} }
public Authentication buildRunAs(Authentication authentication, Object object, List<ConfigAttribute> config) { public Authentication buildRunAs(Authentication authentication, Object object, List<ConfigAttribute> config) {
List newAuthorities = new Vector(); List<GrantedAuthority> newAuthorities = new ArrayList();
for(ConfigAttribute attribute : config) { for(ConfigAttribute attribute : config) {
if (this.supports(attribute)) { if (this.supports(attribute)) {
GrantedAuthorityImpl extraAuthority = new GrantedAuthorityImpl(getRolePrefix() GrantedAuthority extraAuthority = new GrantedAuthorityImpl(getRolePrefix() + attribute.getAttribute());
+ attribute.getAttribute());
newAuthorities.add(extraAuthority); newAuthorities.add(extraAuthority);
} }
} }
@ -76,16 +76,14 @@ public class RunAsManagerImpl implements RunAsManager, InitializingBean {
return null; return null;
} }
// Add existing authorities
newAuthorities.addAll(authentication.getAuthorities());
for (int i = 0; i < authentication.getAuthorities().length; i++) { // GrantedAuthority[] resultType = {new GrantedAuthorityImpl("holder")};
newAuthorities.add(authentication.getAuthorities()[i]); GrantedAuthority[] newAuthoritiesAsArray = newAuthorities.toArray(new GrantedAuthority[0]);
}
GrantedAuthority[] resultType = {new GrantedAuthorityImpl("holder")};
GrantedAuthority[] newAuthoritiesAsArray = (GrantedAuthority[]) newAuthorities.toArray(resultType);
return new RunAsUserToken(this.key, authentication.getPrincipal(), authentication.getCredentials(), return new RunAsUserToken(this.key, authentication.getPrincipal(), authentication.getCredentials(),
newAuthoritiesAsArray, authentication.getClass()); newAuthoritiesAsArray, authentication.getClass());
} }
public String getKey() { public String getKey() {

View File

@ -15,6 +15,8 @@
package org.springframework.security.runas; package org.springframework.security.runas;
import java.util.Arrays;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.AbstractAuthenticationToken; import org.springframework.security.providers.AbstractAuthenticationToken;
@ -38,8 +40,8 @@ public class RunAsUserToken extends AbstractAuthenticationToken {
//~ Constructors =================================================================================================== //~ Constructors ===================================================================================================
public RunAsUserToken(String key, Object principal, Object credentials, GrantedAuthority[] authorities, public RunAsUserToken(String key, Object principal, Object credentials, GrantedAuthority[] authorities,
Class originalAuthentication) { Class originalAuthentication) {
super(authorities); super(Arrays.asList(authorities));
this.keyHash = key.hashCode(); this.keyHash = key.hashCode();
this.principal = principal; this.principal = principal;
this.credentials = credentials; this.credentials = credentials;

View File

@ -1,6 +1,7 @@
package org.springframework.security.ui.preauth; package org.springframework.security.ui.preauth;
import java.util.Arrays; import java.util.Collections;
import java.util.List;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.MutableGrantedAuthoritiesContainer; import org.springframework.security.MutableGrantedAuthoritiesContainer;
@ -10,46 +11,44 @@ import org.springframework.util.Assert;
/** /**
* This AuthenticationDetails implementation allows for storing a list of * This AuthenticationDetails implementation allows for storing a list of
* pre-authenticated Granted Authorities. * pre-authenticated Granted Authorities.
* *
* @author Ruud Senden * @author Ruud Senden
* @since 2.0 * @since 2.0
*/ */
public class PreAuthenticatedGrantedAuthoritiesAuthenticationDetails extends AuthenticationDetails implements public class PreAuthenticatedGrantedAuthoritiesAuthenticationDetails extends AuthenticationDetails implements
MutableGrantedAuthoritiesContainer { MutableGrantedAuthoritiesContainer {
public static final long serialVersionUID = 1L; public static final long serialVersionUID = 1L;
private GrantedAuthority[] preAuthenticatedGrantedAuthorities = null; private List<GrantedAuthority> preAuthenticatedGrantedAuthorities = null;
public PreAuthenticatedGrantedAuthoritiesAuthenticationDetails(Object context) { public PreAuthenticatedGrantedAuthoritiesAuthenticationDetails(Object context) {
super(context); super(context);
} }
/** /**
* @return The String representation of this object. * @return The String representation of this object.
*/ */
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append(super.toString() + "; "); sb.append(super.toString() + "; ");
sb.append("preAuthenticatedGrantedAuthorities: " + Arrays.asList(preAuthenticatedGrantedAuthorities)); sb.append("preAuthenticatedGrantedAuthorities: " + preAuthenticatedGrantedAuthorities);
return sb.toString(); return sb.toString();
} }
/** /**
* *
* @see org.springframework.security.GrantedAuthoritiesContainer#getGrantedAuthorities() * @see org.springframework.security.GrantedAuthoritiesContainer#getGrantedAuthorities()
*/ */
public GrantedAuthority[] getGrantedAuthorities() { public List<GrantedAuthority> getGrantedAuthorities() {
Assert.notNull(preAuthenticatedGrantedAuthorities, "Pre-authenticated granted authorities have not been set"); Assert.notNull(preAuthenticatedGrantedAuthorities, "Pre-authenticated granted authorities have not been set");
GrantedAuthority[] result = new GrantedAuthority[preAuthenticatedGrantedAuthorities.length];
System.arraycopy(preAuthenticatedGrantedAuthorities, 0, result, 0, result.length);
return result;
}
/** return preAuthenticatedGrantedAuthorities;
* @see org.springframework.security.MutableGrantedAuthoritiesContainer#setGrantedAuthorities() }
*/
public void setGrantedAuthorities(GrantedAuthority[] aJ2eeBasedGrantedAuthorities) { /**
this.preAuthenticatedGrantedAuthorities = new GrantedAuthority[aJ2eeBasedGrantedAuthorities.length]; * @see org.springframework.security.MutableGrantedAuthoritiesContainer#setGrantedAuthorities()
System.arraycopy(aJ2eeBasedGrantedAuthorities, 0, preAuthenticatedGrantedAuthorities, 0, preAuthenticatedGrantedAuthorities.length); */
} public void setGrantedAuthorities(List<GrantedAuthority> aJ2eeBasedGrantedAuthorities) {
this.preAuthenticatedGrantedAuthorities = Collections.unmodifiableList(aJ2eeBasedGrantedAuthorities);
}
} }

View File

@ -1,5 +1,7 @@
package org.springframework.security.ui.preauth; package org.springframework.security.ui.preauth;
import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.springframework.security.ui.WebAuthenticationDetails; import org.springframework.security.ui.WebAuthenticationDetails;
@ -25,11 +27,11 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails extends
super(request); super(request);
} }
public GrantedAuthority[] getGrantedAuthorities() { public List<GrantedAuthority> getGrantedAuthorities() {
return authoritiesContainer.getGrantedAuthorities(); return authoritiesContainer.getGrantedAuthorities();
} }
public void setGrantedAuthorities(GrantedAuthority[] authorities) { public void setGrantedAuthorities(List<GrantedAuthority> authorities) {
this.authoritiesContainer.setGrantedAuthorities(authorities); this.authoritiesContainer.setGrantedAuthorities(authorities);
} }

View File

@ -1,6 +1,8 @@
package org.springframework.security.ui.preauth.j2ee; package org.springframework.security.ui.preauth.j2ee;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -14,18 +16,18 @@ import org.springframework.util.Assert;
/** /**
* Base implementation for classes scenarios where the authentication details object is used * Base implementation for classes scenarios where the authentication details object is used
* to store a list of authorities obtained from the context object (such as an HttpServletRequest) * to store a list of authorities obtained from the context object (such as an HttpServletRequest)
* passed to {@link #buildDetails(Object)}. * passed to {@link #buildDetails(Object)}.
* <p> * <p>
* *
* *
* @author Luke Taylor * @author Luke Taylor
* @since 2.0 * @since 2.0
*/ */
public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extends AuthenticationDetailsSourceImpl { public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extends AuthenticationDetailsSourceImpl {
protected final Log logger = LogFactory.getLog(getClass()); protected final Log logger = LogFactory.getLog(getClass());
protected String[] j2eeMappableRoles; protected String[] j2eeMappableRoles;
protected Attributes2GrantedAuthoritiesMapper j2eeUserRoles2GrantedAuthoritiesMapper = protected Attributes2GrantedAuthoritiesMapper j2eeUserRoles2GrantedAuthoritiesMapper =
new SimpleAttributes2GrantedAuthoritiesMapper(); new SimpleAttributes2GrantedAuthoritiesMapper();
public AbstractPreAuthenticatedAuthenticationDetailsSource() { public AbstractPreAuthenticatedAuthenticationDetailsSource() {
@ -49,29 +51,28 @@ public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extend
*/ */
public Object buildDetails(Object context) { public Object buildDetails(Object context) {
Object result = super.buildDetails(context); Object result = super.buildDetails(context);
if (result instanceof MutableGrantedAuthoritiesContainer) { if (result instanceof MutableGrantedAuthoritiesContainer) {
String[] j2eeUserRoles = getUserRoles(context, j2eeMappableRoles); Collection<String> j2eeUserRoles = getUserRoles(context, j2eeMappableRoles);
GrantedAuthority[] userGas = j2eeUserRoles2GrantedAuthoritiesMapper.getGrantedAuthorities(j2eeUserRoles); List<GrantedAuthority> userGas = j2eeUserRoles2GrantedAuthoritiesMapper.getGrantedAuthorities(j2eeUserRoles);
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("J2EE user roles [" + Arrays.asList(j2eeUserRoles) + "] mapped to Granted Authorities: [" logger.debug("J2EE roles [" + j2eeUserRoles + "] mapped to Granted Authorities: [" + userGas + "]");
+ Arrays.asList(userGas) + "]");
} }
((MutableGrantedAuthoritiesContainer) result).setGrantedAuthorities(userGas); ((MutableGrantedAuthoritiesContainer) result).setGrantedAuthorities(userGas);
} }
return result; return result;
} }
/** /**
* Allows the roles of the current user to be determined from the context object * Allows the roles of the current user to be determined from the context object
* *
* @param context the context object (an HttpRequest, PortletRequest etc) * @param context the context object (an HttpRequest, PortletRequest etc)
* @param mappableRoles the possible roles as determined by the MappableAttributesRetriever * @param mappableRoles the possible roles as determined by the MappableAttributesRetriever
* @return the subset of mappable roles which the current user has. * @return the subset of mappable roles which the current user has.
*/ */
protected abstract String[] getUserRoles(Object context, String[] mappableRoles); protected abstract Collection<String> getUserRoles(Object context, String[] mappableRoles);
/** /**
* @param aJ2eeMappableRolesRetriever * @param aJ2eeMappableRolesRetriever
@ -88,4 +89,4 @@ public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extend
public void setUserRoles2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) { public void setUserRoles2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) {
j2eeUserRoles2GrantedAuthoritiesMapper = mapper; j2eeUserRoles2GrantedAuthoritiesMapper = mapper;
} }
} }

View File

@ -4,6 +4,7 @@ import org.springframework.security.ui.preauth.PreAuthenticatedGrantedAuthoritie
import org.springframework.security.authoritymapping.SimpleAttributes2GrantedAuthoritiesMapper; import org.springframework.security.authoritymapping.SimpleAttributes2GrantedAuthoritiesMapper;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -12,7 +13,7 @@ import org.springframework.beans.factory.InitializingBean;
/** /**
* Implementation of AuthenticationDetailsSource which converts the user's J2EE roles (as obtained by calling * Implementation of AuthenticationDetailsSource which converts the user's J2EE roles (as obtained by calling
* {@link HttpServletRequest#isUserInRole(String)}) into GrantedAuthoritys and stores these in the authentication * {@link HttpServletRequest#isUserInRole(String)}) into GrantedAuthoritys and stores these in the authentication
* details object (. * details object (.
* *
* @author Ruud Senden * @author Ruud Senden
* @since 2.0 * @since 2.0
@ -24,7 +25,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs
*/ */
public J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource() { public J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource() {
super.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class); super.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class);
j2eeUserRoles2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper(); j2eeUserRoles2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper();
} }
@ -32,10 +33,10 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs
* Obtains the list of user roles based on the current user's J2EE roles. * Obtains the list of user roles based on the current user's J2EE roles.
* *
* @param request The request against which <tt>isUserInRole</tt> will be called for each role name * @param request The request against which <tt>isUserInRole</tt> will be called for each role name
* returned by the MappableAttributesRetriever. * returned by the MappableAttributesRetriever.
* @return GrantedAuthority[] mapped from the user's J2EE roles. * @return GrantedAuthority[] mapped from the user's J2EE roles.
*/ */
protected String[] getUserRoles(Object context, String[] mappableRoles) { protected Collection<String> getUserRoles(Object context, String[] mappableRoles) {
ArrayList j2eeUserRolesList = new ArrayList(); ArrayList j2eeUserRolesList = new ArrayList();
for (int i = 0; i < mappableRoles.length; i++) { for (int i = 0; i < mappableRoles.length; i++) {
@ -43,7 +44,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs
j2eeUserRolesList.add(mappableRoles[i]); j2eeUserRolesList.add(mappableRoles[i]);
} }
} }
return (String[]) j2eeUserRolesList.toArray(new String[j2eeUserRolesList.size()]); return j2eeUserRolesList;
} }
} }

View File

@ -1,6 +1,7 @@
package org.springframework.security.ui.preauth.websphere; package org.springframework.security.ui.preauth.websphere;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -17,70 +18,70 @@ import org.springframework.util.Assert;
* This AuthenticationDetailsSource implementation, when configured with a MutableGrantedAuthoritiesContainer, * This AuthenticationDetailsSource implementation, when configured with a MutableGrantedAuthoritiesContainer,
* will set the pre-authenticated granted authorities based on the WebSphere groups for the current WebSphere * will set the pre-authenticated granted authorities based on the WebSphere groups for the current WebSphere
* user, mapped using the configured Attributes2GrantedAuthoritiesMapper. * user, mapped using the configured Attributes2GrantedAuthoritiesMapper.
* *
* By default, this class is configured to build instances of the * By default, this class is configured to build instances of the
* PreAuthenticatedGrantedAuthoritiesAuthenticationDetails class. * PreAuthenticatedGrantedAuthoritiesAuthenticationDetails class.
* *
* @author Ruud Senden * @author Ruud Senden
*/ */
public class WebSpherePreAuthenticatedAuthenticationDetailsSource extends AuthenticationDetailsSourceImpl implements InitializingBean { public class WebSpherePreAuthenticatedAuthenticationDetailsSource extends AuthenticationDetailsSourceImpl implements InitializingBean {
private static final Log LOG = LogFactory.getLog(WebSpherePreAuthenticatedAuthenticationDetailsSource.class); private final Log logger = LogFactory.getLog(getClass());
private Attributes2GrantedAuthoritiesMapper webSphereGroups2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper(); private Attributes2GrantedAuthoritiesMapper webSphereGroups2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper();
/** /**
* Public constructor which overrides the default AuthenticationDetails * Public constructor which overrides the default AuthenticationDetails
* class to be used. * class to be used.
*/ */
public WebSpherePreAuthenticatedAuthenticationDetailsSource() { public WebSpherePreAuthenticatedAuthenticationDetailsSource() {
super.setClazz(PreAuthenticatedGrantedAuthoritiesAuthenticationDetails.class); super.setClazz(PreAuthenticatedGrantedAuthoritiesAuthenticationDetails.class);
} }
/** /**
* Check that all required properties have been set. * Check that all required properties have been set.
*/ */
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
Assert.notNull(webSphereGroups2GrantedAuthoritiesMapper, "WebSphere groups to granted authorities mapper not set"); Assert.notNull(webSphereGroups2GrantedAuthoritiesMapper, "WebSphere groups to granted authorities mapper not set");
} }
/** /**
* Build the authentication details object. If the speficied authentication * Build the authentication details object. If the specified authentication
* details class implements the PreAuthenticatedGrantedAuthoritiesSetter, a * details class implements the PreAuthenticatedGrantedAuthoritiesSetter, a
* list of pre-authenticated Granted Authorities will be set based on the * list of pre-authenticated Granted Authorities will be set based on the
* WebSphere groups for the current user. * WebSphere groups for the current user.
* *
* @see org.springframework.security.ui.AuthenticationDetailsSource#buildDetails(Object) * @see org.springframework.security.ui.AuthenticationDetailsSource#buildDetails(Object)
*/ */
public Object buildDetails(Object context) { public Object buildDetails(Object context) {
Object result = super.buildDetails(context); Object result = super.buildDetails(context);
if (result instanceof MutableGrantedAuthoritiesContainer) { if (result instanceof MutableGrantedAuthoritiesContainer) {
((MutableGrantedAuthoritiesContainer) result) ((MutableGrantedAuthoritiesContainer) result)
.setGrantedAuthorities(getWebSphereGroupsBasedGrantedAuthorities()); .setGrantedAuthorities(getWebSphereGroupsBasedGrantedAuthorities());
} }
return result; return result;
} }
/** /**
* Get a list of Granted Authorities based on the current user's WebSphere groups. * Get a list of Granted Authorities based on the current user's WebSphere groups.
* *
* @return GrantedAuthority[] mapped from the user's WebSphere groups. * @return GrantedAuthority[] mapped from the user's WebSphere groups.
*/ */
private GrantedAuthority[] getWebSphereGroupsBasedGrantedAuthorities() { private List<GrantedAuthority> getWebSphereGroupsBasedGrantedAuthorities() {
String[] webSphereGroups = WASSecurityHelper.getGroupsForCurrentUser(); List<String> webSphereGroups = Arrays.asList(WASSecurityHelper.getGroupsForCurrentUser());
GrantedAuthority[] userGas = webSphereGroups2GrantedAuthoritiesMapper.getGrantedAuthorities(webSphereGroups); List<GrantedAuthority> userGas = webSphereGroups2GrantedAuthoritiesMapper.getGrantedAuthorities(webSphereGroups);
if (LOG.isDebugEnabled()) { if (logger.isDebugEnabled()) {
LOG.debug("WebSphere groups: " + Arrays.asList(webSphereGroups) + " mapped to Granted Authorities: " logger.debug("WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: "
+ Arrays.asList(userGas)); + Arrays.asList(userGas));
} }
return userGas; return userGas;
} }
/** /**
* @param mapper * @param mapper
* The Attributes2GrantedAuthoritiesMapper to use * The Attributes2GrantedAuthoritiesMapper to use
*/ */
public void setWebSphereGroups2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) { public void setWebSphereGroups2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) {
webSphereGroups2GrantedAuthoritiesMapper = mapper; webSphereGroups2GrantedAuthoritiesMapper = mapper;
} }
} }

View File

@ -240,7 +240,7 @@ public class SwitchUserProcessingFilter extends SpringSecurityFilter implements
GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_PREVIOUS_ADMINISTRATOR, currentAuth); GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_PREVIOUS_ADMINISTRATOR, currentAuth);
// get the original authorities // get the original authorities
List orig = Arrays.asList(targetUser.getAuthorities()); List orig = targetUser.getAuthorities();
// Allow subclasses to change the authorities to be granted // Allow subclasses to change the authorities to be granted
if (switchUserAuthorityChanger != null) { if (switchUserAuthorityChanger != null) {
@ -251,11 +251,8 @@ public class SwitchUserProcessingFilter extends SpringSecurityFilter implements
List newAuths = new ArrayList(orig); List newAuths = new ArrayList(orig);
newAuths.add(switchAuthority); newAuths.add(switchAuthority);
GrantedAuthority[] authorities =
(GrantedAuthority[]) newAuths.toArray(new GrantedAuthority[newAuths.size()]);
// create the new authentication token // create the new authentication token
targetUserRequest = new UsernamePasswordAuthenticationToken(targetUser, targetUser.getPassword(), authorities); targetUserRequest = new UsernamePasswordAuthenticationToken(targetUser, targetUser.getPassword(), newAuths);
// set details // set details
targetUserRequest.setDetails(authenticationDetailsSource.buildDetails(request)); targetUserRequest.setDetails(authenticationDetailsSource.buildDetails(request));
@ -304,7 +301,7 @@ public class SwitchUserProcessingFilter extends SpringSecurityFilter implements
logger.debug("Switch User failed", failed); logger.debug("Switch User failed", failed);
if (switchFailureUrl != null) { if (switchFailureUrl != null) {
sendRedirect(request, response, switchFailureUrl); sendRedirect(request, response, switchFailureUrl);
} else { } else {
response.getWriter().print("Switch user failed: " + failed.getMessage()); response.getWriter().print("Switch user failed: " + failed.getMessage());
response.flushBuffer(); response.flushBuffer();
@ -330,12 +327,12 @@ public class SwitchUserProcessingFilter extends SpringSecurityFilter implements
Authentication original = null; Authentication original = null;
// iterate over granted authorities and find the 'switch user' authority // iterate over granted authorities and find the 'switch user' authority
GrantedAuthority[] authorities = current.getAuthorities(); List<GrantedAuthority> authorities = current.getAuthorities();
for (int i = 0; i < authorities.length; i++) { for (GrantedAuthority auth : authorities) {
// check for switch user type of authority // check for switch user type of authority
if (authorities[i] instanceof SwitchUserGrantedAuthority) { if (auth instanceof SwitchUserGrantedAuthority) {
original = ((SwitchUserGrantedAuthority) authorities[i]).getSource(); original = ((SwitchUserGrantedAuthority) auth).getSource();
logger.debug("Found original switch user granted authority [" + original + "]"); logger.debug("Found original switch user granted authority [" + original + "]");
} }
} }

View File

@ -1,210 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.ui.x509;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.event.authentication.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.providers.x509.X509AuthenticationToken;
import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.security.ui.AuthenticationDetailsSource;
import org.springframework.security.ui.WebAuthenticationDetailsSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.util.Assert;
import java.io.IOException;
import java.security.cert.X509Certificate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.Filter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletException;
import javax.servlet.FilterChain;
import javax.servlet.ServletResponse;
import javax.servlet.FilterConfig;
/**
* Processes the X.509 certificate submitted by a client browser when HTTPS is used with client-authentication
* enabled.<p>An {@link X509AuthenticationToken} is created with the certificate as the credentials.</p>
* <p>The configured authentication manager is expected to supply a provider which can handle this token (usually
* an instance of {@link org.springframework.security.providers.x509.X509AuthenticationProvider}).</p>
* <p>If authentication is successful, an {@link
* org.springframework.security.event.authentication.InteractiveAuthenticationSuccessEvent} will be published to the application
* context. No events will be published if authentication was unsuccessful, because this would generally be recorded
* via an <code>AuthenticationManager</code>-specific application event.</p>
*
* @author Luke Taylor
* @deprecated Use <tt>X509PreAuthenticatedProcessingFilter</tt> from the preauth.x509 package instead
* @version $Id$
*/
public class X509ProcessingFilter implements Filter, InitializingBean, ApplicationEventPublisherAware {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(X509ProcessingFilter.class);
//~ Instance fields ================================================================================================
private ApplicationEventPublisher eventPublisher;
private AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource();
private AuthenticationManager authenticationManager;
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.notNull(authenticationManager, "An AuthenticationManager must be set");
}
public void destroy() {}
/**
* This method first checks for an existing, non-null authentication in the secure context. If one is found
* it does nothing.<p>If no authentication object exists, it attempts to obtain the client authentication
* certificate from the request. If there is no certificate present then authentication is skipped. Otherwise a
* new authentication request containing the certificate will be passed to the configured {@link
* AuthenticationManager}.</p>
* <p>If authentication is successful the returned token will be stored in the secure context. Otherwise
* it will be set to null. In either case, the request proceeds through the filter chain.</p>
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
* @param filterChain DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
* @throws javax.servlet.ServletException DOCUMENT ME!
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest");
}
if (!(response instanceof HttpServletResponse)) {
throw new ServletException("Can only process HttpServletResponse");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (logger.isDebugEnabled()) {
logger.debug("Checking secure context token: " + SecurityContextHolder.getContext().getAuthentication());
}
if (SecurityContextHolder.getContext().getAuthentication() == null) {
Authentication authResult = null;
X509Certificate clientCertificate = extractClientCertificate(httpRequest);
try {
X509AuthenticationToken authRequest = new X509AuthenticationToken(clientCertificate);
authRequest.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request));
authResult = authenticationManager.authenticate(authRequest);
successfulAuthentication(httpRequest, httpResponse, authResult);
} catch (AuthenticationException failed) {
unsuccessfulAuthentication(httpRequest, httpResponse, failed);
}
}
filterChain.doFilter(request, response);
}
private X509Certificate extractClientCertificate(HttpServletRequest request) {
X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
if ((certs != null) && (certs.length > 0)) {
return certs[0];
}
if (logger.isDebugEnabled()) {
logger.debug("No client certificate found in request.");
}
return null;
}
public void init(FilterConfig ignored) throws ServletException {}
public void setApplicationEventPublisher(ApplicationEventPublisher context) {
this.eventPublisher = context;
}
public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
this.authenticationDetailsSource = authenticationDetailsSource;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/**
* Puts the <code>Authentication</code> instance returned by the authentication manager into the secure
* context.
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
* @param authResult DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
*/
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authResult);
}
SecurityContextHolder.getContext().setAuthentication(authResult);
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
}
}
/**
* Ensures the authentication object in the secure context is set to null when authentication fails.
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
* @param failed DOCUMENT ME!
*/
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) {
SecurityContextHolder.getContext().setAuthentication(null);
if (logger.isDebugEnabled()) {
logger.debug("Updated SecurityContextHolder to contain null Authentication");
}
request.getSession().setAttribute(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, failed);
}
}

View File

@ -1,77 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.ui.x509;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.AuthenticationException;
import org.springframework.security.ui.AuthenticationEntryPoint;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* In the X.509 authentication case (unlike CAS, for example) the certificate
* will already have been extracted from the request and a secure context
* established by the time the security-enforcement filter is invoked.
* <p>
* Therefore this class isn't actually responsible for the commencement of
* authentication, as it is in the case of other providers. It will be called if
* the certificate was rejected by Spring Security's X509AuthenticationProvider, resulting
* in a null authentication.
* </p>
* The <code>commence</code> method will always return an
* <code>HttpServletResponse.SC_FORBIDDEN</code> (403 error).
*
* @author Luke Taylor
* @deprecated Use the preauth package instead
* @version $Id$
*
* @see org.springframework.security.ui.ExceptionTranslationFilter
*/
public class X509ProcessingFilterEntryPoint implements AuthenticationEntryPoint {
// ~ Static fields/initializers
// =====================================================================================
private static final Log logger = LogFactory.getLog(X509ProcessingFilterEntryPoint.class);
// ~ Methods
// ========================================================================================================
/**
* Returns a 403 error code to the client.
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
* @param authException DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
* @throws ServletException DOCUMENT ME!
*/
public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.debug("X509 entry point called. Rejecting access");
}
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
}
}

View File

@ -1,6 +0,0 @@
<html>
<body>
This package is now deprecated and will be removed in a future version.
Use the X.509 authentication support in org.springframework.security.ui.preauth.x509 instead.
</body>
</html>

View File

@ -1,5 +1,7 @@
package org.springframework.security.userdetails; package org.springframework.security.userdetails;
import java.util.List;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
/** /**
@ -36,7 +38,7 @@ public interface GroupManager {
* @param groupName the name for the new group * @param groupName the name for the new group
* @param authorities the authorities which are to be allocated to this group. * @param authorities the authorities which are to be allocated to this group.
*/ */
void createGroup(String groupName, GrantedAuthority[] authorities); void createGroup(String groupName, List<GrantedAuthority> authorities);
/** /**
* Removes a group, including all members and authorities. * Removes a group, including all members and authorities.
@ -69,7 +71,7 @@ public interface GroupManager {
/** /**
* Obtains the list of authorities which are assigned to a group. * Obtains the list of authorities which are assigned to a group.
*/ */
GrantedAuthority[] findGroupAuthorities(String groupName); List<GrantedAuthority> findGroupAuthorities(String groupName);
/** /**
* Assigns a new authority to a group. * Assigns a new authority to a group.

View File

@ -15,13 +15,16 @@
package org.springframework.security.userdetails; package org.springframework.security.userdetails;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* Models core user information retieved by an {@link UserDetailsService}.<p>Implemented with value object * Models core user information retieved by an {@link UserDetailsService}.<p>Implemented with value object
* semantics (immutable after construction, like a <code>String</code>). Developers may use this class directly, * semantics (immutable after construction, like a <code>String</code>). Developers may use this class directly,
@ -36,7 +39,7 @@ public class User implements UserDetails {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String password; private String password;
private String username; private String username;
private GrantedAuthority[] authorities; private List<GrantedAuthority> authorities;
private boolean accountNonExpired; private boolean accountNonExpired;
private boolean accountNonLocked; private boolean accountNonLocked;
private boolean credentialsNonExpired; private boolean credentialsNonExpired;
@ -45,58 +48,12 @@ public class User implements UserDetails {
//~ Constructors =================================================================================================== //~ Constructors ===================================================================================================
/** /**
* Construct the <code>User</code> with the details required by * @deprecated
* {@link org.springframework.security.providers.dao.DaoAuthenticationProvider}.
*
* @param username the username presented to the
* <code>DaoAuthenticationProvider</code>
* @param password the password that should be presented to the
* <code>DaoAuthenticationProvider</code>
* @param enabled set to <code>true</code> if the user is enabled
* @param authorities the authorities that should be granted to the caller
* if they presented the correct username and password and the user
* is enabled
*
* @throws IllegalArgumentException if a <code>null</code> value was passed
* either as a parameter or as an element in the
* <code>GrantedAuthority[]</code> array
*
* @deprecated use new constructor with extended properties (this
* constructor will be removed from release 1.0.0)
*/
public User(String username, String password, boolean enabled, GrantedAuthority[] authorities)
throws IllegalArgumentException {
this(username, password, enabled, true, true, authorities);
}
/**
* Construct the <code>User</code> with the details required by
* {@link org.springframework.security.providers.dao.DaoAuthenticationProvider}.
*
* @param username the username presented to the
* <code>DaoAuthenticationProvider</code>
* @param password the password that should be presented to the
* <code>DaoAuthenticationProvider</code>
* @param enabled set to <code>true</code> if the user is enabled
* @param accountNonExpired set to <code>true</code> if the account has not
* expired
* @param credentialsNonExpired set to <code>true</code> if the credentials
* have not expired
* @param authorities the authorities that should be granted to the caller
* if they presented the correct username and password and the user
* is enabled
*
* @throws IllegalArgumentException if a <code>null</code> value was passed
* either as a parameter or as an element in the
* <code>GrantedAuthority[]</code> array
*
* @deprecated use new constructor with extended properties (this
* constructor will be removed from release 1.0.0)
*/ */
public User(String username, String password, boolean enabled, boolean accountNonExpired, public User(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, GrantedAuthority[] authorities) boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities) {
throws IllegalArgumentException { this(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
this(username, password, enabled, accountNonExpired, credentialsNonExpired, true, authorities); authorities == null ? null : Arrays.asList(authorities));
} }
/** /**
@ -123,8 +80,8 @@ public class User implements UserDetails {
* <code>GrantedAuthority[]</code> array * <code>GrantedAuthority[]</code> array
*/ */
public User(String username, String password, boolean enabled, boolean accountNonExpired, public User(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities) boolean credentialsNonExpired, boolean accountNonLocked, List<GrantedAuthority> authorities) {
throws IllegalArgumentException {
if (((username == null) || "".equals(username)) || (password == null)) { if (((username == null) || "".equals(username)) || (password == null)) {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor"); throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
} }
@ -149,16 +106,10 @@ public class User implements UserDetails {
// We rely on constructor to guarantee any User has non-null and >0 // We rely on constructor to guarantee any User has non-null and >0
// authorities // authorities
if (user.getAuthorities().length != this.getAuthorities().length) { if (!authorities.equals(user.authorities)) {
return false; return false;
} }
for (int i = 0; i < this.getAuthorities().length; i++) {
if (!this.getAuthorities()[i].equals(user.getAuthorities()[i])) {
return false;
}
}
// We rely on constructor to guarantee non-null username and password // We rely on constructor to guarantee non-null username and password
return (this.getPassword().equals(user.getPassword()) && this.getUsername().equals(user.getUsername()) return (this.getPassword().equals(user.getPassword()) && this.getUsername().equals(user.getUsername())
&& (this.isAccountNonExpired() == user.isAccountNonExpired()) && (this.isAccountNonExpired() == user.isAccountNonExpired())
@ -167,7 +118,7 @@ public class User implements UserDetails {
&& (this.isEnabled() == user.isEnabled())); && (this.isEnabled() == user.isEnabled()));
} }
public GrantedAuthority[] getAuthorities() { public List<GrantedAuthority> getAuthorities() {
return authorities; return authorities;
} }
@ -183,8 +134,8 @@ public class User implements UserDetails {
int code = 9792; int code = 9792;
if (this.getAuthorities() != null) { if (this.getAuthorities() != null) {
for (int i = 0; i < this.getAuthorities().length; i++) { for (int i = 0; i < this.getAuthorities().size(); i++) {
code = code * (this.getAuthorities()[i].hashCode() % 7); code = code * (authorities.get(i).hashCode() % 7);
} }
} }
@ -231,17 +182,20 @@ public class User implements UserDetails {
return enabled; return enabled;
} }
protected void setAuthorities(GrantedAuthority[] authorities) { protected void setAuthorities(List<GrantedAuthority> authorities) {
Assert.notNull(authorities, "Cannot pass a null GrantedAuthority array"); Assert.notNull(authorities, "Cannot pass a null GrantedAuthority array");
// Ensure array iteration order is predictable (as per UserDetails.getAuthorities() contract and SEC-xxx) // Ensure array iteration order is predictable (as per UserDetails.getAuthorities() contract and SEC-xxx)
SortedSet sorter = new TreeSet(); SortedSet<GrantedAuthority> sorter = new TreeSet<GrantedAuthority>();
for (int i = 0; i < authorities.length; i++) {
Assert.notNull(authorities[i], for (GrantedAuthority grantedAuthority : authorities) {
"Granted authority element " + i + " is null - GrantedAuthority[] cannot contain any null elements"); Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");
sorter.add(authorities[i]); sorter.add(grantedAuthority);
} }
this.authorities = (GrantedAuthority[]) sorter.toArray(new GrantedAuthority[sorter.size()]); List<GrantedAuthority> sortedAuthorities = new ArrayList<GrantedAuthority>(sorter.size());
sortedAuthorities.addAll(sorter);
this.authorities = Collections.unmodifiableList(sortedAuthorities);
} }
public String toString() { public String toString() {
@ -257,12 +211,12 @@ public class User implements UserDetails {
if (this.getAuthorities() != null) { if (this.getAuthorities() != null) {
sb.append("Granted Authorities: "); sb.append("Granted Authorities: ");
for (int i = 0; i < this.getAuthorities().length; i++) { for (int i = 0; i < authorities.size(); i++) {
if (i > 0) { if (i > 0) {
sb.append(", "); sb.append(", ");
} }
sb.append(this.getAuthorities()[i].toString()); sb.append(authorities.get(i));
} }
} else { } else {
sb.append("Not granted any authorities"); sb.append("Not granted any authorities");

View File

@ -19,6 +19,7 @@ import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import java.io.Serializable; import java.io.Serializable;
import java.util.List;
/** /**
@ -56,7 +57,7 @@ public interface UserDetails extends Serializable {
* *
* @return the authorities, sorted by natural key (never <code>null</code>) * @return the authorities, sorted by natural key (never <code>null</code>)
*/ */
GrantedAuthority[] getAuthorities(); List<GrantedAuthority> getAuthorities();
/** /**
* Returns the password used to authenticate the user. Cannot return <code>null</code>. * Returns the password used to authenticate the user. Cannot return <code>null</code>.

View File

@ -14,6 +14,8 @@
package org.springframework.security.userdetails.hierarchicalroles; package org.springframework.security.userdetails.hierarchicalroles;
import java.util.List;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
/** /**
@ -37,6 +39,6 @@ public interface RoleHierarchy {
* @param authorities - Array of the directly assigned authorities. * @param authorities - Array of the directly assigned authorities.
* @return Array of all reachable authorities given the assigned authorities. * @return Array of all reachable authorities given the assigned authorities.
*/ */
public GrantedAuthority[] getReachableGrantedAuthorities(GrantedAuthority[] authorities); public List<GrantedAuthority> getReachableGrantedAuthorities(List<GrantedAuthority> authorities);
} }

View File

@ -98,27 +98,30 @@ public class RoleHierarchyImpl implements RoleHierarchy {
buildRolesReachableInOneOrMoreStepsMap(); buildRolesReachableInOneOrMoreStepsMap();
} }
public GrantedAuthority[] getReachableGrantedAuthorities(GrantedAuthority[] authorities) { public List<GrantedAuthority> getReachableGrantedAuthorities(List<GrantedAuthority> authorities) {
if (authorities == null || authorities.length == 0) { if (authorities == null || authorities.isEmpty()) {
return null; return null;
} }
Set reachableRoles = new HashSet(); Set<GrantedAuthority> reachableRoles = new HashSet<GrantedAuthority>();
for (int i = 0; i < authorities.length; i++) { for (GrantedAuthority authority : authorities) {
reachableRoles.add(authorities[i]); reachableRoles.add(authority);
Set additionalReachableRoles = (Set) rolesReachableInOneOrMoreStepsMap.get(authorities[i]); Set additionalReachableRoles = (Set) rolesReachableInOneOrMoreStepsMap.get(authority);
if (additionalReachableRoles != null) { if (additionalReachableRoles != null) {
reachableRoles.addAll(additionalReachableRoles); reachableRoles.addAll(additionalReachableRoles);
} }
} }
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("getReachableGrantedAuthorities() - From the roles " + Arrays.asList(authorities) logger.debug("getReachableGrantedAuthorities() - From the roles " + authorities
+ " one can reach " + reachableRoles + " in zero or more steps."); + " one can reach " + reachableRoles + " in zero or more steps.");
} }
return (GrantedAuthority[]) reachableRoles.toArray(new GrantedAuthority[reachableRoles.size()]); List<GrantedAuthority> reachableRoleList = new ArrayList<GrantedAuthority>(reachableRoles.size());
reachableRoleList.addAll(reachableRoles);
return reachableRoleList;
} }
/** /**

View File

@ -14,6 +14,8 @@
package org.springframework.security.userdetails.hierarchicalroles; package org.springframework.security.userdetails.hierarchicalroles;
import java.util.List;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
@ -46,7 +48,7 @@ public class UserDetailsWrapper implements UserDetails {
return userDetails.isAccountNonLocked(); return userDetails.isAccountNonLocked();
} }
public GrantedAuthority[] getAuthorities() { public List<GrantedAuthority> getAuthorities() {
return roleHierarchy.getReachableGrantedAuthorities(userDetails.getAuthorities()); return roleHierarchy.getReachableGrantedAuthorities(userDetails.getAuthorities());
} }

View File

@ -134,12 +134,12 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
public void createUser(final UserDetails user) { public void createUser(final UserDetails user) {
validateUserDetails(user); validateUserDetails(user);
getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() { getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, user.getUsername()); ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword()); ps.setString(2, user.getPassword());
ps.setBoolean(3, user.isEnabled()); ps.setBoolean(3, user.isEnabled());
} }
}); });
insertUserAuthorities(user); insertUserAuthorities(user);
@ -148,11 +148,11 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
public void updateUser(final UserDetails user) { public void updateUser(final UserDetails user) {
validateUserDetails(user); validateUserDetails(user);
getJdbcTemplate().update(updateUserSql, new PreparedStatementSetter() { getJdbcTemplate().update(updateUserSql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, user.getPassword()); ps.setString(1, user.getPassword());
ps.setBoolean(2, user.isEnabled()); ps.setBoolean(2, user.isEnabled());
ps.setString(3, user.getUsername()); ps.setString(3, user.getUsername());
} }
}); });
deleteUserAuthorities(user.getUsername()); deleteUserAuthorities(user.getUsername());
@ -162,9 +162,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
} }
private void insertUserAuthorities(UserDetails user) { private void insertUserAuthorities(UserDetails user) {
for (int i=0; i < user.getAuthorities().length; i++) { for (int i=0; i < user.getAuthorities().size(); i++) {
getJdbcTemplate().update(createAuthoritySql, getJdbcTemplate().update(createAuthoritySql,
new Object[] {user.getUsername(), user.getAuthorities()[i].getAuthority()}); new Object[] {user.getUsername(), user.getAuthorities().get(i).getAuthority()});
} }
} }
@ -173,9 +173,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
getJdbcTemplate().update(deleteUserSql, new Object[] {username}); getJdbcTemplate().update(deleteUserSql, new Object[] {username});
userCache.removeUserFromCache(username); userCache.removeUserFromCache(username);
} }
private void deleteUserAuthorities(String username) { private void deleteUserAuthorities(String username) {
getJdbcTemplate().update(deleteUserAuthoritiesSql, new Object[] {username}); getJdbcTemplate().update(deleteUserAuthoritiesSql, new Object[] {username});
} }
public void changePassword(String oldPassword, String newPassword) throws AuthenticationException { public void changePassword(String oldPassword, String newPassword) throws AuthenticationException {
@ -218,7 +218,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
} }
public boolean userExists(String username) { public boolean userExists(String username) {
List users = getJdbcTemplate().queryForList(userExistsSql, new Object[] {username}); List users = getJdbcTemplate().queryForList(userExistsSql, new Object[] {username});
if (users.size() > 1) { if (users.size() > 1) {
throw new IncorrectResultSizeDataAccessException("More than one user found with name '" + username + "'", 1); throw new IncorrectResultSizeDataAccessException("More than one user found with name '" + username + "'", 1);
@ -238,25 +238,25 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
return (String[]) getJdbcTemplate().queryForList(findUsersInGroupSql, new String[] {groupName}, String.class).toArray(new String[0]); return (String[]) getJdbcTemplate().queryForList(findUsersInGroupSql, new String[] {groupName}, String.class).toArray(new String[0]);
} }
public void createGroup(final String groupName, final GrantedAuthority[] authorities) { public void createGroup(final String groupName, final List<GrantedAuthority> authorities) {
Assert.hasText(groupName); Assert.hasText(groupName);
Assert.notNull(authorities); Assert.notNull(authorities);
logger.debug("Creating new group '" + groupName + "' with authorities " + logger.debug("Creating new group '" + groupName + "' with authorities " +
AuthorityUtils.authorityArrayToSet(authorities)); AuthorityUtils.authorityArrayToSet(authorities));
getJdbcTemplate().update(insertGroupSql, new String[] {groupName}); getJdbcTemplate().update(insertGroupSql, new String[] {groupName});
final int groupId = findGroupId(groupName); final int groupId = findGroupId(groupName);
for (int i=0; i < authorities.length; i++) { for (int i=0; i < authorities.size(); i++) {
final String authority = authorities[i].getAuthority(); final String authority = authorities.get(i).getAuthority();
getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() { getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, groupId); ps.setInt(1, groupId);
ps.setString(2, authority); ps.setString(2, authority);
} }
}); });
} }
} }
@ -266,9 +266,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
PreparedStatementSetter groupIdPSS = new PreparedStatementSetter() { PreparedStatementSetter groupIdPSS = new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id); ps.setInt(1, id);
} }
}; };
getJdbcTemplate().update(deleteGroupMembersSql, groupIdPSS); getJdbcTemplate().update(deleteGroupMembersSql, groupIdPSS);
getJdbcTemplate().update(deleteGroupAuthoritiesSql, groupIdPSS); getJdbcTemplate().update(deleteGroupAuthoritiesSql, groupIdPSS);
@ -290,10 +290,10 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
getJdbcTemplate().update(insertGroupMemberSql, new PreparedStatementSetter() { getJdbcTemplate().update(insertGroupMemberSql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id); ps.setInt(1, id);
ps.setString(2, username); ps.setString(2, username);
} }
}); });
userCache.removeUserFromCache(username); userCache.removeUserFromCache(username);
@ -307,29 +307,29 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
getJdbcTemplate().update(deleteGroupMemberSql, new PreparedStatementSetter() { getJdbcTemplate().update(deleteGroupMemberSql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id); ps.setInt(1, id);
ps.setString(2, username); ps.setString(2, username);
} }
}); });
userCache.removeUserFromCache(username); userCache.removeUserFromCache(username);
} }
public GrantedAuthority[] findGroupAuthorities(String groupName) { public List<GrantedAuthority> findGroupAuthorities(String groupName) {
logger.debug("Loading authorities for group '" + groupName + "'"); logger.debug("Loading authorities for group '" + groupName + "'");
Assert.hasText(groupName); Assert.hasText(groupName);
List authorities = getJdbcTemplate().query(groupAuthoritiesSql, new String[] {groupName}, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
String roleName = getRolePrefix() + rs.getString(3);
GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
return authority; List<GrantedAuthority> authorities = getJdbcTemplate().query(groupAuthoritiesSql, new String[] {groupName}, new RowMapper() {
} public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
String roleName = getRolePrefix() + rs.getString(3);
GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
return authority;
}
}); });
return (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[0]); return authorities;
} }
public void removeGroupAuthority(String groupName, final GrantedAuthority authority) { public void removeGroupAuthority(String groupName, final GrantedAuthority authority) {
@ -338,13 +338,13 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
Assert.notNull(authority); Assert.notNull(authority);
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
getJdbcTemplate().update(deleteGroupAuthoritySql, new PreparedStatementSetter() { getJdbcTemplate().update(deleteGroupAuthoritySql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id); ps.setInt(1, id);
ps.setString(2, authority.getAuthority()); ps.setString(2, authority.getAuthority());
} }
}); });
} }
@ -355,15 +355,15 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() { getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id); ps.setInt(1, id);
ps.setString(2, authority.getAuthority()); ps.setString(2, authority.getAuthority());
} }
}); });
} }
private int findGroupId(String group) { private int findGroupId(String group) {
return getJdbcTemplate().queryForInt(findGroupIdSql, new Object[] {group}); return getJdbcTemplate().queryForInt(findGroupIdSql, new Object[] {group});
} }
public void setAuthenticationManager(AuthenticationManager authenticationManager) { public void setAuthenticationManager(AuthenticationManager authenticationManager) {
@ -425,12 +425,12 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
validateAuthorities(user.getAuthorities()); validateAuthorities(user.getAuthorities());
} }
private void validateAuthorities(GrantedAuthority[] authorities) { private void validateAuthorities(List<GrantedAuthority> authorities) {
Assert.notNull(authorities, "Authorities list must not be null"); Assert.notNull(authorities, "Authorities list must not be null");
for (int i=0; i < authorities.length; i++) { for (int i=0; i < authorities.size(); i++) {
Assert.notNull(authorities[i], "Authorities list contains a null entry"); Assert.notNull(authorities.get(i), "Authorities list contains a null entry");
Assert.hasText(authorities[i].getAuthority(), "getAuthority() method must return a non-empty string"); Assert.hasText(authorities.get(i).getAuthority(), "getAuthority() method must return a non-empty string");
} }
} }
} }

View File

@ -14,6 +14,8 @@
*/ */
package org.springframework.security.userdetails.ldap; package org.springframework.security.userdetails.ldap;
import java.util.List;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.DirContextOperations;
@ -27,7 +29,7 @@ import org.springframework.util.Assert;
*/ */
public class InetOrgPersonContextMapper implements UserDetailsContextMapper { public class InetOrgPersonContextMapper implements UserDetailsContextMapper {
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, GrantedAuthority[] authorities) { public UserDetails mapUserFromContext(DirContextOperations ctx, String username, List<GrantedAuthority> authorities) {
InetOrgPerson.Essence p = new InetOrgPerson.Essence(ctx); InetOrgPerson.Essence p = new InetOrgPerson.Essence(ctx);
p.setUsername(username); p.setUsername(username);

View File

@ -50,7 +50,7 @@ public class LdapUserDetailsImpl implements LdapUserDetails {
private String dn; private String dn;
private String password; private String password;
private String username; private String username;
private GrantedAuthority[] authorities = AuthorityUtils.NO_AUTHORITIES; private List<GrantedAuthority> authorities = AuthorityUtils.NO_AUTHORITIES;
private boolean accountNonExpired = true; private boolean accountNonExpired = true;
private boolean accountNonLocked = true; private boolean accountNonLocked = true;
private boolean credentialsNonExpired = true; private boolean credentialsNonExpired = true;
@ -62,7 +62,7 @@ public class LdapUserDetailsImpl implements LdapUserDetails {
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
public GrantedAuthority[] getAuthorities() { public List<GrantedAuthority> getAuthorities() {
return authorities; return authorities;
} }
@ -107,12 +107,12 @@ public class LdapUserDetailsImpl implements LdapUserDetails {
if (this.getAuthorities() != null) { if (this.getAuthorities() != null) {
sb.append("Granted Authorities: "); sb.append("Granted Authorities: ");
for (int i = 0; i < this.getAuthorities().length; i++) { for (int i = 0; i < this.getAuthorities().size(); i++) {
if (i > 0) { if (i > 0) {
sb.append(", "); sb.append(", ");
} }
sb.append(this.getAuthorities()[i].toString()); sb.append(this.getAuthorities().get(i).toString());
} }
} else { } else {
sb.append("Not granted any authorities"); sb.append("Not granted any authorities");
@ -184,8 +184,8 @@ public class LdapUserDetailsImpl implements LdapUserDetails {
return newInstance; return newInstance;
} }
public GrantedAuthority[] getGrantedAuthorities() { public List<GrantedAuthority> getGrantedAuthorities() {
return (GrantedAuthority[]) mutableAuthorities.toArray(new GrantedAuthority[0]); return mutableAuthorities;
} }
public void setAccountNonExpired(boolean accountNonExpired) { public void setAccountNonExpired(boolean accountNonExpired) {
@ -196,8 +196,8 @@ public class LdapUserDetailsImpl implements LdapUserDetails {
instance.accountNonLocked = accountNonLocked; instance.accountNonLocked = accountNonLocked;
} }
public void setAuthorities(GrantedAuthority[] authorities) { public void setAuthorities(List<GrantedAuthority> authorities) {
mutableAuthorities = new ArrayList(Arrays.asList(authorities)); mutableAuthorities = authorities;
} }
public void setCredentialsNonExpired(boolean credentialsNonExpired) { public void setCredentialsNonExpired(boolean credentialsNonExpired) {

View File

@ -60,13 +60,10 @@ import java.util.ListIterator;
* <p> * <p>
* It is designed around a standard setup where users and groups/roles are stored under separate contexts, * It is designed around a standard setup where users and groups/roles are stored under separate contexts,
* defined by the "userDnBase" and "groupSearchBase" properties respectively. * defined by the "userDnBase" and "groupSearchBase" properties respectively.
* </p>
* <p> * <p>
* In this case, LDAP is being used purely to retrieve information and this class can be used in place of any other * In this case, LDAP is being used purely to retrieve information and this class can be used in place of any other
* UserDetailsService for authentication. Authentication isn't performed directly against the directory, unlike with the * UserDetailsService for authentication. Authentication isn't performed directly against the directory, unlike with the
* LDAP authentication provider setup. * LDAP authentication provider setup.
* </p>
*
* *
* @author Luke Taylor * @author Luke Taylor
* @since 2.0 * @since 2.0
@ -127,7 +124,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
DistinguishedName dn = usernameMapper.buildDn(username); DistinguishedName dn = usernameMapper.buildDn(username);
GrantedAuthority[] authorities = getUserAuthorities(dn, username); List<GrantedAuthority> authorities = getUserAuthorities(dn, username);
logger.debug("Loading user '"+ username + "' with DN '" + dn + "'"); logger.debug("Loading user '"+ username + "' with DN '" + dn + "'");
@ -207,7 +204,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
* @param username the user whose roles are required. * @param username the user whose roles are required.
* @return the granted authorities returned by the group search * @return the granted authorities returned by the group search
*/ */
GrantedAuthority[] getUserAuthorities(final DistinguishedName dn, final String username) { List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) {
SearchExecutor se = new SearchExecutor() { SearchExecutor se = new SearchExecutor() {
public NamingEnumeration executeSearch(DirContext ctx) throws NamingException { public NamingEnumeration executeSearch(DirContext ctx) throws NamingException {
DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx); DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
@ -222,9 +219,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
new AttributesMapperCallbackHandler(roleMapper); new AttributesMapperCallbackHandler(roleMapper);
template.search(se, roleCollector); template.search(se, roleCollector);
List authorities = roleCollector.getList(); return roleCollector.getList();
return (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]);
} }
// protected String getRoleFilter(DistinguishedName dn, String username) { // protected String getRoleFilter(DistinguishedName dn, String username) {
@ -236,9 +231,9 @@ public class LdapUserDetailsManager implements UserDetailsManager {
copyToContext(user, ctx); copyToContext(user, ctx);
DistinguishedName dn = usernameMapper.buildDn(user.getUsername()); DistinguishedName dn = usernameMapper.buildDn(user.getUsername());
// Check for any existing authorities which might be set for this DN // Check for any existing authorities which might be set for this DN
GrantedAuthority[] authorities = getUserAuthorities(dn, user.getUsername()); List<GrantedAuthority> authorities = getUserAuthorities(dn, user.getUsername());
if(authorities.length > 0) { if(authorities.size() > 0) {
removeAuthorities(dn, authorities); removeAuthorities(dn, authorities);
} }
@ -255,7 +250,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
logger.debug("Updating user '"+ user.getUsername() + "' with DN '" + dn + "'"); logger.debug("Updating user '"+ user.getUsername() + "' with DN '" + dn + "'");
GrantedAuthority[] authorities = getUserAuthorities(dn, user.getUsername()); List<GrantedAuthority> authorities = getUserAuthorities(dn, user.getUsername());
DirContextAdapter ctx = loadUserAsContext(dn, user.getUsername()); DirContextAdapter ctx = loadUserAsContext(dn, user.getUsername());
ctx.setUpdateMode(true); ctx.setUpdateMode(true);
@ -318,19 +313,19 @@ public class LdapUserDetailsManager implements UserDetailsManager {
userDetailsMapper.mapUserToContext(user, ctx); userDetailsMapper.mapUserToContext(user, ctx);
} }
protected void addAuthorities(DistinguishedName userDn, GrantedAuthority[] authorities) { protected void addAuthorities(DistinguishedName userDn, List<GrantedAuthority> authorities) {
modifyAuthorities(userDn, authorities, DirContext.ADD_ATTRIBUTE); modifyAuthorities(userDn, authorities, DirContext.ADD_ATTRIBUTE);
} }
protected void removeAuthorities(DistinguishedName userDn, GrantedAuthority[] authorities) { protected void removeAuthorities(DistinguishedName userDn, List<GrantedAuthority> authorities) {
modifyAuthorities(userDn, authorities, DirContext.REMOVE_ATTRIBUTE); modifyAuthorities(userDn, authorities, DirContext.REMOVE_ATTRIBUTE);
} }
private void modifyAuthorities(final DistinguishedName userDn, final GrantedAuthority[] authorities, final int modType) { private void modifyAuthorities(final DistinguishedName userDn, final List<GrantedAuthority> authorities, final int modType) {
template.executeReadWrite(new ContextExecutor() { template.executeReadWrite(new ContextExecutor() {
public Object executeWithContext(DirContext ctx) throws NamingException { public Object executeWithContext(DirContext ctx) throws NamingException {
for(int i=0; i < authorities.length; i++) { for(int i=0; i < authorities.size(); i++) {
GrantedAuthority authority = authorities[i]; GrantedAuthority authority = authorities.get(i);
String group = convertAuthorityToGroup(authority); String group = convertAuthorityToGroup(authority);
DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx); DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx);
ModificationItem addGroup = new ModificationItem(modType, ModificationItem addGroup = new ModificationItem(modType,

View File

@ -15,6 +15,8 @@
package org.springframework.security.userdetails.ldap; package org.springframework.security.userdetails.ldap;
import java.util.List;
import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
@ -44,7 +46,7 @@ public class LdapUserDetailsMapper implements UserDetailsContextMapper {
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, GrantedAuthority[] authorities) { public UserDetails mapUserFromContext(DirContextOperations ctx, String username, List<GrantedAuthority> authorities) {
String dn = ctx.getNameInNamespace(); String dn = ctx.getNameInNamespace();
logger.debug("Mapping user details from context with DN: " + dn); logger.debug("Mapping user details from context with DN: " + dn);
@ -80,8 +82,8 @@ public class LdapUserDetailsMapper implements UserDetailsContextMapper {
// Add the supplied authorities // Add the supplied authorities
for (int i=0; i < authorities.length; i++) { for (int i=0; i < authorities.size(); i++) {
essence.addAuthority(authorities[i]); essence.addAuthority(authorities.get(i));
} }
return essence.createUserDetails(); return essence.createUserDetails();

View File

@ -1,12 +1,11 @@
package org.springframework.security.userdetails.ldap; package org.springframework.security.userdetails.ldap;
import org.springframework.security.GrantedAuthority; import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.ldap.LdapUserSearch;
import org.springframework.security.ldap.LdapAuthoritiesPopulator; import org.springframework.security.ldap.LdapAuthoritiesPopulator;
import org.springframework.security.ldap.LdapUserSearch;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException; import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
@ -32,9 +31,8 @@ public class LdapUserDetailsService implements UserDetailsService {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
DirContextOperations userData = userSearch.searchForUser(username); DirContextOperations userData = userSearch.searchForUser(username);
GrantedAuthority[] authorities = authoritiesPopulator.getGrantedAuthorities(userData, username); return userDetailsMapper.mapUserFromContext(userData, username,
authoritiesPopulator.getGrantedAuthorities(userData, username));
return userDetailsMapper.mapUserFromContext(userData, username, authorities);
} }
public void setUserDetailsMapper(UserDetailsContextMapper userDetailsMapper) { public void setUserDetailsMapper(UserDetailsContextMapper userDetailsMapper) {

View File

@ -1,5 +1,7 @@
package org.springframework.security.userdetails.ldap; package org.springframework.security.userdetails.ldap;
import java.util.List;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.DirContextOperations;
@ -12,7 +14,7 @@ import org.springframework.util.Assert;
*/ */
public class PersonContextMapper implements UserDetailsContextMapper { public class PersonContextMapper implements UserDetailsContextMapper {
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, GrantedAuthority[] authorities) { public UserDetails mapUserFromContext(DirContextOperations ctx, String username, List<GrantedAuthority> authorities) {
Person.Essence p = new Person.Essence(ctx); Person.Essence p = new Person.Essence(ctx);
p.setUsername(username); p.setUsername(username);

View File

@ -14,6 +14,8 @@
*/ */
package org.springframework.security.userdetails.ldap; package org.springframework.security.userdetails.ldap;
import java.util.List;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.DirContextOperations;
@ -37,7 +39,7 @@ public interface UserDetailsContextMapper {
* @param authority the list of authorities which the user should be given. * @param authority the list of authorities which the user should be given.
* @return the user object. * @return the user object.
*/ */
UserDetails mapUserFromContext(DirContextOperations ctx, String username, GrantedAuthority[] authority); UserDetails mapUserFromContext(DirContextOperations ctx, String username, List<GrantedAuthority> authority);
/** /**
* Reverse of the above operation. Populates a context object from the supplied user object. * Reverse of the above operation. Populates a context object from the supplied user object.

View File

@ -6,7 +6,10 @@ import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.context.SecurityContextHolder;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
/** /**
@ -14,7 +17,7 @@ import java.util.Set;
* @version $Id$ * @version $Id$
*/ */
public abstract class AuthorityUtils { public abstract class AuthorityUtils {
public static final GrantedAuthority[] NO_AUTHORITIES = new GrantedAuthority[0]; public static final List<GrantedAuthority> NO_AUTHORITIES = Collections.EMPTY_LIST;
/** /**
* Returns true if the current user has the specified authority. * Returns true if the current user has the specified authority.
@ -24,10 +27,10 @@ public abstract class AuthorityUtils {
* name exists in the current user's list of authorities. False otherwise, or if the user in not authenticated. * name exists in the current user's list of authorities. False otherwise, or if the user in not authenticated.
*/ */
public static boolean userHasAuthority(String authority) { public static boolean userHasAuthority(String authority) {
GrantedAuthority[] authorities = getUserAuthorities(); List<GrantedAuthority> authorities = getUserAuthorities();
for (int i = 0; i < authorities.length; i++) { for (GrantedAuthority grantedAuthority : authorities) {
if (authority.equals(authorities[i].getAuthority())) { if (authority.equals(grantedAuthority.getAuthority())) {
return true; return true;
} }
} }
@ -40,7 +43,7 @@ public abstract class AuthorityUtils {
* *
* @return an array containing the current user's authorities (or an empty array if not authenticated), never null. * @return an array containing the current user's authorities (or an empty array if not authenticated), never null.
*/ */
private static GrantedAuthority[] getUserAuthorities() { private static List<GrantedAuthority> getUserAuthorities() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || auth.getAuthorities() == null) { if (auth == null || auth.getAuthorities() == null) {
@ -73,21 +76,21 @@ public abstract class AuthorityUtils {
* Converts an array of GrantedAuthority objects to a Set. * Converts an array of GrantedAuthority objects to a Set.
* @return a Set of the Strings obtained from each call to GrantedAuthority.getAuthority() * @return a Set of the Strings obtained from each call to GrantedAuthority.getAuthority()
*/ */
public static Set authorityArrayToSet(GrantedAuthority[] authorities) { public static Set authorityArrayToSet(List<GrantedAuthority> authorities) {
Set set = new HashSet(authorities.length); Set set = new HashSet(authorities.size());
for (int i = 0; i < authorities.length; i++) { for (GrantedAuthority authority: authorities) {
set.add(authorities[i].getAuthority()); set.add(authority.getAuthority());
} }
return set; return set;
} }
public static GrantedAuthority[] stringArrayToAuthorityArray(String[] roles) { public static List<GrantedAuthority> createAuthorityList(String... roles) {
GrantedAuthority[] authorities = new GrantedAuthority[roles.length]; List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(roles.length);
for (int i=0; i < roles.length; i++) { for (int i=0; i < roles.length; i++) {
authorities[i] = new GrantedAuthorityImpl(roles[i]); authorities.add(new GrantedAuthorityImpl(roles[i]));
} }
return authorities; return authorities;

View File

@ -186,9 +186,9 @@ public class LabelBasedAclVoter extends AbstractAclVoter {
*/ */
List userLabels = new Vector(); List userLabels = new Vector();
for (int i = 0; i < authentication.getAuthorities().length; i++) { for (int i = 0; i < authentication.getAuthorities().size(); i++) {
if (labelMap.containsKey(authentication.getAuthorities()[i].getAuthority())) { String userLabel = authentication.getAuthorities().get(i).getAuthority();
String userLabel = authentication.getAuthorities()[i].getAuthority(); if (labelMap.containsKey(userLabel)) {
userLabels.add(userLabel); userLabels.add(userLabel);
logger.debug("Adding " + userLabel + " to <<<" + authentication.getName() logger.debug("Adding " + userLabel + " to <<<" + authentication.getName()
+ "'s>>> authorized label list"); + "'s>>> authorized label list");

View File

@ -1,29 +1,32 @@
package org.springframework.security.vote; package org.springframework.security.vote;
import java.util.List;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.hierarchicalroles.RoleHierarchy; import org.springframework.security.userdetails.hierarchicalroles.RoleHierarchy;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* Extended RoleVoter which uses a {@link RoleHierarchy} definition to determine the * Extended RoleVoter which uses a {@link RoleHierarchy} definition to determine the
* roles allocated to the current user before voting. * roles allocated to the current user before voting.
* *
* @author Luke Taylor * @author Luke Taylor
* @since 2.0.4 * @since 2.0.4
*/ */
public class RoleHierarchyVoter extends RoleVoter { public class RoleHierarchyVoter extends RoleVoter {
private RoleHierarchy roleHierarchy = null; private RoleHierarchy roleHierarchy = null;
public RoleHierarchyVoter(RoleHierarchy roleHierarchy) { public RoleHierarchyVoter(RoleHierarchy roleHierarchy) {
Assert.notNull(roleHierarchy, "RoleHierarchy must not be null"); Assert.notNull(roleHierarchy, "RoleHierarchy must not be null");
this.roleHierarchy = roleHierarchy; this.roleHierarchy = roleHierarchy;
} }
/** /**
* Calls the <tt>RoleHierarchy</tt> to obtain the complete set of user authorities. * Calls the <tt>RoleHierarchy</tt> to obtain the complete set of user authorities.
*/ */
GrantedAuthority[] extractAuthorities(Authentication authentication) { @Override
return roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities()); List<GrantedAuthority> extractAuthorities(Authentication authentication) {
} return roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities());
}
} }

View File

@ -94,18 +94,15 @@ public class RoleVoter implements AccessDecisionVoter {
public int vote(Authentication authentication, Object object, List<ConfigAttribute> attributes) { public int vote(Authentication authentication, Object object, List<ConfigAttribute> attributes) {
int result = ACCESS_ABSTAIN; int result = ACCESS_ABSTAIN;
Iterator iter = attributes.iterator(); List<GrantedAuthority> authorities = extractAuthorities(authentication);
GrantedAuthority[] authorities = extractAuthorities(authentication);
while (iter.hasNext()) {
ConfigAttribute attribute = (ConfigAttribute) iter.next();
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) { if (this.supports(attribute)) {
result = ACCESS_DENIED; result = ACCESS_DENIED;
// Attempt to find a matching granted authority // Attempt to find a matching granted authority
for (int i = 0; i < authorities.length; i++) { for (GrantedAuthority authority : authorities) {
if (attribute.getAttribute().equals(authorities[i].getAuthority())) { if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED; return ACCESS_GRANTED;
} }
} }
@ -115,7 +112,7 @@ public class RoleVoter implements AccessDecisionVoter {
return result; return result;
} }
GrantedAuthority[] extractAuthorities(Authentication authentication) { List<GrantedAuthority> extractAuthorities(Authentication authentication) {
return authentication.getAuthorities(); return authentication.getAuthorities();
} }
} }

View File

@ -18,6 +18,7 @@ package org.springframework.security.wrapper;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationTrustResolver; import org.springframework.security.AuthenticationTrustResolver;
import org.springframework.security.AuthenticationTrustResolverImpl; import org.springframework.security.AuthenticationTrustResolverImpl;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.context.SecurityContextHolder;
@ -25,6 +26,7 @@ import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.util.PortResolver; import org.springframework.security.util.PortResolver;
import java.security.Principal; import java.security.Principal;
import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletRequestWrapper;
@ -124,12 +126,19 @@ public class SecurityContextHolderAwareRequestWrapper extends HttpServletRequest
role = rolePrefix + role; role = rolePrefix + role;
} }
if ((auth == null) || (auth.getPrincipal() == null) || (auth.getAuthorities() == null)) { if ((auth == null) || (auth.getPrincipal() == null)) {
return false; return false;
} }
for (int i = 0; i < auth.getAuthorities().length; i++) { List<GrantedAuthority> authorities = auth.getAuthorities();
if (role.equals(auth.getAuthorities()[i].getAuthority())) {
if (authorities == null) {
return false;
}
for (GrantedAuthority grantedAuthority : authorities) {
if (role.equals(grantedAuthority.getAuthority())) {
return true; return true;
} }
} }
@ -138,10 +147,11 @@ public class SecurityContextHolderAwareRequestWrapper extends HttpServletRequest
} }
/** /**
* Simple searches for an exactly matching {@link org.springframework.security.GrantedAuthority#getAuthority()}.<p>Will * Simple searches for an exactly matching {@link org.springframework.security.GrantedAuthority#getAuthority()}.
* always return <code>false</code> if the <code>SecurityContextHolder</code> contains an * <p>
* Will always return <code>false</code> if the <code>SecurityContextHolder</code> contains an
* <code>Authentication</code> with <code>null</code><code>principal</code> and/or <code>GrantedAuthority[]</code> * <code>Authentication</code> with <code>null</code><code>principal</code> and/or <code>GrantedAuthority[]</code>
* objects.</p> * objects.
* *
* @param role the <code>GrantedAuthority</code><code>String</code> representation to check for * @param role the <code>GrantedAuthority</code><code>String</code> representation to check for
* *

View File

@ -15,7 +15,6 @@
package org.springframework.security; package org.springframework.security;
import java.util.Iterator;
import java.util.List; import java.util.List;
@ -34,8 +33,8 @@ public class MockAccessDecisionManager implements AccessDecisionManager {
for(ConfigAttribute attr : configAttributes) { for(ConfigAttribute attr : configAttributes) {
if (this.supports(attr)) { if (this.supports(attr)) {
for (int i = 0; i < authentication.getAuthorities().length; i++) { for(GrantedAuthority authority : authentication.getAuthorities()) {
if (attr.getAttribute().equals(authentication.getAuthorities()[i].getAuthority())) { if (attr.getAttribute().equals(authority.getAuthority())) {
return; return;
} }
} }

View File

@ -1,232 +1,214 @@
package org.springframework.security.authoritymapping; package org.springframework.security.authoritymapping;
import static org.junit.Assert.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import junit.framework.TestCase;
import org.apache.log4j.Level; import org.apache.log4j.Level;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.GrantedAuthorityImpl;
/** /**
* *
* @author Ruud Senden * @author Ruud Senden
*/ */
public class MapBasedAttributes2GrantedAuthoritiesMapperTest extends TestCase { public class MapBasedAttributes2GrantedAuthoritiesMapperTest {
protected void setUp() throws Exception { protected void setUp() throws Exception {
// Set Log4j loglevel to debug to include all logstatements in tests // Set Log4j loglevel to debug to include all logstatements in tests
Logger.getRootLogger().setLevel(Level.DEBUG); Logger.getRootLogger().setLevel(Level.DEBUG);
} }
public final void testAfterPropertiesSetNoMap() { @Test(expected=IllegalArgumentException.class)
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); public void testAfterPropertiesSetNoMap() throws Exception {
try { MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.afterPropertiesSet(); mapper.afterPropertiesSet();
fail("Expected exception not thrown"); }
} catch (IllegalArgumentException expected) {
// Expected exception
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testAfterPropertiesSetEmptyMap() {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.setAttributes2grantedAuthoritiesMap(new HashMap());
try {
mapper.afterPropertiesSet();
fail("Expected exception not thrown");
} catch (IllegalArgumentException expected) {
// Expected exception
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testAfterPropertiesSetInvalidKeyTypeMap() {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap();
m.put(new Object(),"ga1");
mapper.setAttributes2grantedAuthoritiesMap(m);
try {
mapper.afterPropertiesSet();
fail("Expected exception not thrown");
} catch (IllegalArgumentException expected) {
// Expected exception
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testAfterPropertiesSetInvalidValueTypeMap1() {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap();
m.put("role1",new Object());
mapper.setAttributes2grantedAuthoritiesMap(m);
try {
mapper.afterPropertiesSet();
fail("Expected exception not thrown");
} catch (IllegalArgumentException expected) {
// Expected exception
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testAfterPropertiesSetInvalidValueTypeMap2() {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap();
m.put("role1",new Object[]{new String[]{"ga1","ga2"}, new Object()});
mapper.setAttributes2grantedAuthoritiesMap(m);
try {
mapper.afterPropertiesSet();
fail("Expected exception not thrown");
} catch (IllegalArgumentException expected) {
// Expected exception
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testAfterPropertiesSetValidMap() { @Test(expected=IllegalArgumentException.class)
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); public void testAfterPropertiesSetEmptyMap() throws Exception {
HashMap m = getValidAttributes2GrantedAuthoritiesMap(); MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.setAttributes2grantedAuthoritiesMap(m); mapper.setAttributes2grantedAuthoritiesMap(new HashMap());
try { mapper.afterPropertiesSet();
mapper.afterPropertiesSet(); }
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testMapping1() {
String[] roles = { "role1" };
String[] expectedGas = { "ga1" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping2() {
String[] roles = { "role2" };
String[] expectedGas = { "ga2" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping3() {
String[] roles = { "role3" };
String[] expectedGas = { "ga3", "ga4" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping4() {
String[] roles = { "role4" };
String[] expectedGas = { "ga5", "ga6" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping5() {
String[] roles = { "role5" };
String[] expectedGas = { "ga7", "ga8", "ga9" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping6() {
String[] roles = { "role6" };
String[] expectedGas = { "ga10", "ga11", "ga12" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping7() {
String[] roles = { "role7" };
String[] expectedGas = { "ga13", "ga14" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping8() {
String[] roles = { "role8" };
String[] expectedGas = { "ga13", "ga14" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping9() {
String[] roles = { "role9" };
String[] expectedGas = {};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping10() {
String[] roles = { "role10" };
String[] expectedGas = {};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMapping11() {
String[] roles = { "role11" };
String[] expectedGas = {};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testNonExistingMapping() {
String[] roles = { "nonExisting" };
String[] expectedGas = {};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testMappingCombination() {
String[] roles = { "role1", "role2", "role3", "role4", "role5", "role6", "role7", "role8", "role9", "role10", "role11" };
String[] expectedGas = { "ga1", "ga2", "ga3", "ga4", "ga5", "ga6", "ga7", "ga8", "ga9", "ga10", "ga11", "ga12", "ga13", "ga14"};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
private HashMap getValidAttributes2GrantedAuthoritiesMap() { @Test(expected=IllegalArgumentException.class)
HashMap m = new HashMap(); public void testAfterPropertiesSetInvalidKeyTypeMap() throws Exception {
m.put("role1","ga1"); MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
m.put("role2",new GrantedAuthorityImpl("ga2")); HashMap m = new HashMap();
m.put("role3",Arrays.asList(new Object[]{"ga3",new GrantedAuthorityImpl("ga4")})); m.put(new Object(),"ga1");
m.put("role4","ga5,ga6"); mapper.setAttributes2grantedAuthoritiesMap(m);
m.put("role5",Arrays.asList(new Object[]{"ga7","ga8",new Object[]{new GrantedAuthorityImpl("ga9")}})); mapper.afterPropertiesSet();
m.put("role6",new Object[]{"ga10","ga11",new Object[]{new GrantedAuthorityImpl("ga12")}}); }
m.put("role7",new String[]{"ga13","ga14"});
m.put("role8",new String[]{"ga13","ga14",null});
m.put("role9",null);
m.put("role10",new Object[]{});
m.put("role11",Arrays.asList(new Object[]{null}));
return m;
}
private MapBasedAttributes2GrantedAuthoritiesMapper getDefaultMapper() { @Test(expected=IllegalArgumentException.class)
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); public void testAfterPropertiesSetInvalidValueTypeMap1() throws Exception {
mapper.setAttributes2grantedAuthoritiesMap(getValidAttributes2GrantedAuthoritiesMap()); MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.afterPropertiesSet(); HashMap m = new HashMap();
return mapper; m.put("role1",new Object());
} mapper.setAttributes2grantedAuthoritiesMap(m);
mapper.afterPropertiesSet();
}
private void testGetGrantedAuthorities(Attributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) { @Test(expected=IllegalArgumentException.class)
GrantedAuthority[] result = mapper.getGrantedAuthorities(roles); public void testAfterPropertiesSetInvalidValueTypeMap2() throws Exception {
Collection resultColl = new ArrayList(result.length); MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
for (int i = 0; i < result.length; i++) { HashMap m = new HashMap();
resultColl.add(result[i].getAuthority()); m.put("role1",new Object[]{new String[]{"ga1","ga2"}, new Object()});
} mapper.setAttributes2grantedAuthoritiesMap(m);
Collection expectedColl = Arrays.asList(expectedGas); mapper.afterPropertiesSet();
assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl }
.containsAll(resultColl)
&& resultColl.containsAll(expectedColl)); @Test
} public void testAfterPropertiesSetValidMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = getValidAttributes2GrantedAuthoritiesMap();
mapper.setAttributes2grantedAuthoritiesMap(m);
mapper.afterPropertiesSet();
}
@Test
public void testMapping1() throws Exception {
String[] roles = { "role1" };
String[] expectedGas = { "ga1" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping2() throws Exception {
String[] roles = { "role2" };
String[] expectedGas = { "ga2" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping3() throws Exception {
String[] roles = { "role3" };
String[] expectedGas = { "ga3", "ga4" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping4() throws Exception {
String[] roles = { "role4" };
String[] expectedGas = { "ga5", "ga6" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping5() throws Exception {
String[] roles = { "role5" };
String[] expectedGas = { "ga7", "ga8", "ga9" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping6() throws Exception {
String[] roles = { "role6" };
String[] expectedGas = { "ga10", "ga11", "ga12" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping7() throws Exception {
String[] roles = { "role7" };
String[] expectedGas = { "ga13", "ga14" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping8() throws Exception {
String[] roles = { "role8" };
String[] expectedGas = { "ga13", "ga14" };
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping9() throws Exception {
String[] roles = { "role9" };
String[] expectedGas = {};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping10() throws Exception {
String[] roles = { "role10" };
String[] expectedGas = {};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMapping11() throws Exception {
String[] roles = { "role11" };
String[] expectedGas = {};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testNonExistingMapping() throws Exception {
String[] roles = { "nonExisting" };
String[] expectedGas = {};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public void testMappingCombination() throws Exception {
String[] roles = { "role1", "role2", "role3", "role4", "role5", "role6", "role7", "role8", "role9", "role10", "role11" };
String[] expectedGas = { "ga1", "ga2", "ga3", "ga4", "ga5", "ga6", "ga7", "ga8", "ga9", "ga10", "ga11", "ga12", "ga13", "ga14"};
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
private HashMap getValidAttributes2GrantedAuthoritiesMap() {
HashMap m = new HashMap();
m.put("role1","ga1");
m.put("role2",new GrantedAuthorityImpl("ga2"));
m.put("role3",Arrays.asList(new Object[]{"ga3",new GrantedAuthorityImpl("ga4")}));
m.put("role4","ga5,ga6");
m.put("role5",Arrays.asList(new Object[]{"ga7","ga8",new Object[]{new GrantedAuthorityImpl("ga9")}}));
m.put("role6",new Object[]{"ga10","ga11",new Object[]{new GrantedAuthorityImpl("ga12")}});
m.put("role7",new String[]{"ga13","ga14"});
m.put("role8",new String[]{"ga13","ga14",null});
m.put("role9",null);
m.put("role10",new Object[]{});
m.put("role11",Arrays.asList(new Object[]{null}));
return m;
}
private MapBasedAttributes2GrantedAuthoritiesMapper getDefaultMapper() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.setAttributes2grantedAuthoritiesMap(getValidAttributes2GrantedAuthoritiesMap());
mapper.afterPropertiesSet();
return mapper;
}
private void testGetGrantedAuthorities(Attributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
List<GrantedAuthority> result = mapper.getGrantedAuthorities(Arrays.asList(roles));
Collection resultColl = new ArrayList(result.size());
for (int i = 0; i < result.size(); i++) {
resultColl.add(result.get(i).getAuthority());
}
Collection expectedColl = Arrays.asList(expectedGas);
assertTrue("Role collections should match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
.containsAll(resultColl)
&& resultColl.containsAll(expectedColl));
}
} }

View File

@ -5,117 +5,118 @@ import org.springframework.security.GrantedAuthority;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
* *
* @author TSARDD * @author TSARDD
* @since 18-okt-2007 * @since 18-okt-2007
*/ */
public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
public final void testAfterPropertiesSetConvertToUpperAndLowerCase() { public final void testAfterPropertiesSetConvertToUpperAndLowerCase() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
mapper.setConvertAttributeToLowerCase(true); mapper.setConvertAttributeToLowerCase(true);
mapper.setConvertAttributeToUpperCase(true); mapper.setConvertAttributeToUpperCase(true);
try { try {
mapper.afterPropertiesSet(); mapper.afterPropertiesSet();
fail("Expected exception not thrown"); fail("Expected exception not thrown");
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
} catch (Exception unexpected) { } catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected); fail("Unexpected exception: " + unexpected);
} }
} }
public final void testAfterPropertiesSet() { public final void testAfterPropertiesSet() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
try { try {
mapper.afterPropertiesSet(); mapper.afterPropertiesSet();
} catch (Exception unexpected) { } catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected); fail("Unexpected exception: " + unexpected);
} }
} }
public final void testGetGrantedAuthoritiesNoConversion() { public final void testGetGrantedAuthoritiesNoConversion() {
String[] roles = { "Role1", "Role2" }; String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "Role1", "Role2" }; String[] expectedGas = { "Role1", "Role2" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas); testGetGrantedAuthorities(mapper, roles, expectedGas);
} }
public final void testGetGrantedAuthoritiesToUpperCase() { public final void testGetGrantedAuthoritiesToUpperCase() {
String[] roles = { "Role1", "Role2" }; String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "ROLE1", "ROLE2" }; String[] expectedGas = { "ROLE1", "ROLE2" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setConvertAttributeToUpperCase(true); mapper.setConvertAttributeToUpperCase(true);
testGetGrantedAuthorities(mapper, roles, expectedGas); testGetGrantedAuthorities(mapper, roles, expectedGas);
} }
public final void testGetGrantedAuthoritiesToLowerCase() { public final void testGetGrantedAuthoritiesToLowerCase() {
String[] roles = { "Role1", "Role2" }; String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "role1", "role2" }; String[] expectedGas = { "role1", "role2" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setConvertAttributeToLowerCase(true); mapper.setConvertAttributeToLowerCase(true);
testGetGrantedAuthorities(mapper, roles, expectedGas); testGetGrantedAuthorities(mapper, roles, expectedGas);
} }
public final void testGetGrantedAuthoritiesAddPrefixIfAlreadyExisting() { public final void testGetGrantedAuthoritiesAddPrefixIfAlreadyExisting() {
String[] roles = { "Role1", "Role2", "ROLE_Role3" }; String[] roles = { "Role1", "Role2", "ROLE_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_ROLE_Role3" }; String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_ROLE_Role3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(true); mapper.setAddPrefixIfAlreadyExisting(true);
mapper.setAttributePrefix("ROLE_"); mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas); testGetGrantedAuthorities(mapper, roles, expectedGas);
} }
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting1() { public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting1() {
String[] roles = { "Role1", "Role2", "ROLE_Role3" }; String[] roles = { "Role1", "Role2", "ROLE_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_Role3" }; String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_Role3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(false); mapper.setAddPrefixIfAlreadyExisting(false);
mapper.setAttributePrefix("ROLE_"); mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas); testGetGrantedAuthorities(mapper, roles, expectedGas);
} }
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting2() { public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting2() {
String[] roles = { "Role1", "Role2", "role_Role3" }; String[] roles = { "Role1", "Role2", "role_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_role_Role3" }; String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_role_Role3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(false); mapper.setAddPrefixIfAlreadyExisting(false);
mapper.setAttributePrefix("ROLE_"); mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas); testGetGrantedAuthorities(mapper, roles, expectedGas);
} }
public final void testGetGrantedAuthoritiesCombination1() { public final void testGetGrantedAuthoritiesCombination1() {
String[] roles = { "Role1", "Role2", "role_Role3" }; String[] roles = { "Role1", "Role2", "role_Role3" };
String[] expectedGas = { "ROLE_ROLE1", "ROLE_ROLE2", "ROLE_ROLE3" }; String[] expectedGas = { "ROLE_ROLE1", "ROLE_ROLE2", "ROLE_ROLE3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(false); mapper.setAddPrefixIfAlreadyExisting(false);
mapper.setConvertAttributeToUpperCase(true); mapper.setConvertAttributeToUpperCase(true);
mapper.setAttributePrefix("ROLE_"); mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas); testGetGrantedAuthorities(mapper, roles, expectedGas);
} }
private void testGetGrantedAuthorities(SimpleAttributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) { private void testGetGrantedAuthorities(SimpleAttributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
GrantedAuthority[] result = mapper.getGrantedAuthorities(roles); List<GrantedAuthority> result = mapper.getGrantedAuthorities(Arrays.asList(roles));
Collection resultColl = new ArrayList(result.length); Collection resultColl = new ArrayList(result.size());
for (int i = 0; i < result.length; i++) { for (int i = 0; i < result.size(); i++) {
resultColl.add(result[i].getAuthority()); resultColl.add(result.get(i).getAuthority());
} }
Collection expectedColl = Arrays.asList(expectedGas); Collection expectedColl = Arrays.asList(expectedGas);
assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
.containsAll(resultColl) .containsAll(resultColl)
&& resultColl.containsAll(expectedColl)); && resultColl.containsAll(expectedColl));
} }
private SimpleAttributes2GrantedAuthoritiesMapper getDefaultMapper() { private SimpleAttributes2GrantedAuthoritiesMapper getDefaultMapper() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
mapper.setAttributePrefix(""); mapper.setAttributePrefix("");
mapper.setConvertAttributeToLowerCase(false); mapper.setConvertAttributeToLowerCase(false);
mapper.setConvertAttributeToUpperCase(false); mapper.setConvertAttributeToUpperCase(false);
mapper.setAddPrefixIfAlreadyExisting(false); mapper.setAddPrefixIfAlreadyExisting(false);
return mapper; return mapper;
} }
} }

View File

@ -38,15 +38,15 @@ public class LdapProviderBeanDefinitionParserTests {
Authentication auth = provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword")); Authentication auth = provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword"));
LdapUserDetailsImpl ben = (LdapUserDetailsImpl) auth.getPrincipal(); LdapUserDetailsImpl ben = (LdapUserDetailsImpl) auth.getPrincipal();
assertEquals(3, ben.getAuthorities().length); assertEquals(3, ben.getAuthorities().size());
} }
@Test(expected = SecurityConfigurationException.class) @Test(expected = SecurityConfigurationException.class)
public void missingServerEltCausesConfigException() { public void missingServerEltCausesConfigException() {
setContext("<ldap-authentication-provider />"); setContext("<ldap-authentication-provider />");
} }
@Test @Test
public void supportsPasswordComparisonAuthentication() { public void supportsPasswordComparisonAuthentication() {
setContext("<ldap-server /> " + setContext("<ldap-server /> " +
@ -54,10 +54,10 @@ public class LdapProviderBeanDefinitionParserTests {
" <password-compare />" + " <password-compare />" +
"</ldap-authentication-provider>"); "</ldap-authentication-provider>");
LdapAuthenticationProvider provider = getProvider(); LdapAuthenticationProvider provider = getProvider();
provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword")); provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword"));
} }
@Test @Test
public void supportsPasswordComparisonAuthenticationWithHashAttribute() { public void supportsPasswordComparisonAuthenticationWithHashAttribute() {
setContext("<ldap-server /> " + setContext("<ldap-server /> " +
@ -65,27 +65,27 @@ public class LdapProviderBeanDefinitionParserTests {
" <password-compare password-attribute='uid' hash='plaintext'/>" + " <password-compare password-attribute='uid' hash='plaintext'/>" +
"</ldap-authentication-provider>"); "</ldap-authentication-provider>");
LdapAuthenticationProvider provider = getProvider(); LdapAuthenticationProvider provider = getProvider();
provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben")); provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben"));
} }
@Test @Test
public void supportsPasswordComparisonAuthenticationWithPasswordEncoder() { public void supportsPasswordComparisonAuthenticationWithPasswordEncoder() {
setContext("<ldap-server /> " + setContext("<ldap-server /> " +
"<ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>" + "<ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>" +
" <password-compare password-attribute='uid'>" + " <password-compare password-attribute='uid'>" +
" <password-encoder hash='plaintext'/>" + " <password-encoder hash='plaintext'/>" +
" </password-compare>" + " </password-compare>" +
"</ldap-authentication-provider>"); "</ldap-authentication-provider>");
LdapAuthenticationProvider provider = getProvider(); LdapAuthenticationProvider provider = getProvider();
provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben")); provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben"));
} }
@Test @Test
public void detectsNonStandardServerId() { public void detectsNonStandardServerId() {
setContext("<ldap-server id='myServer'/> " + setContext("<ldap-server id='myServer'/> " +
"<ldap-authentication-provider />"); "<ldap-authentication-provider />");
} }
@Test @Test
public void inetOrgContextMapperIsSupported() throws Exception { public void inetOrgContextMapperIsSupported() throws Exception {
setContext( setContext(
@ -93,8 +93,8 @@ public class LdapProviderBeanDefinitionParserTests {
"<ldap-authentication-provider user-details-class='inetOrgPerson'/>"); "<ldap-authentication-provider user-details-class='inetOrgPerson'/>");
LdapAuthenticationProvider provider = getProvider(); LdapAuthenticationProvider provider = getProvider();
assertTrue(FieldUtils.getFieldValue(provider, "userDetailsContextMapper") instanceof InetOrgPersonContextMapper); assertTrue(FieldUtils.getFieldValue(provider, "userDetailsContextMapper") instanceof InetOrgPersonContextMapper);
} }
private void setContext(String context) { private void setContext(String context) {
appCtx = new InMemoryXmlApplicationContext(context); appCtx = new InMemoryXmlApplicationContext(context);
} }
@ -106,5 +106,5 @@ public class LdapProviderBeanDefinitionParserTests {
LdapAuthenticationProvider provider = (LdapAuthenticationProvider) authManager.getProviders().get(0); LdapAuthenticationProvider provider = (LdapAuthenticationProvider) authManager.getProviders().get(0);
return provider; return provider;
} }
} }

View File

@ -18,11 +18,9 @@ package org.springframework.security.context;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.MockFilterConfig; import org.springframework.security.MockFilterConfig;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken; import org.springframework.security.util.AuthorityUtils;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
@ -44,342 +42,316 @@ import javax.servlet.ServletResponse;
* 02:04:47Z benalex $ * 02:04:47Z benalex $
*/ */
public class HttpSessionContextIntegrationFilterTests extends TestCase { public class HttpSessionContextIntegrationFilterTests extends TestCase {
//~ Constructors =================================================================================================== // Build an Authentication object we simulate came from HttpSession
private UsernamePasswordAuthenticationToken sessionPrincipal = new UsernamePasswordAuthenticationToken(
"someone",
"password",
AuthorityUtils.createAuthorityList("SOME_ROLE"));
public HttpSessionContextIntegrationFilterTests() {
}
public HttpSessionContextIntegrationFilterTests(String arg0) { //~ Methods ========================================================================================================
super(arg0);
}
//~ Methods ======================================================================================================== private static void executeFilterInContainerSimulator(
FilterConfig filterConfig, Filter filter, ServletRequest request,
ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filter.init(filterConfig);
filter.doFilter(request, response, filterChain);
filter.destroy();
}
private static void executeFilterInContainerSimulator( public void testDetectsIncompatibleSessionProperties() throws Exception {
FilterConfig filterConfig, Filter filter, ServletRequest request, HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filter.init(filterConfig);
filter.doFilter(request, response, filterChain);
filter.destroy();
}
public void testDetectsIncompatibleSessionProperties() throws Exception { try {
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter(); filter.setAllowSessionCreation(false);
filter.setForceEagerSessionCreation(true);
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try { filter.setAllowSessionCreation(true);
filter.setAllowSessionCreation(false); filter.afterPropertiesSet();
filter.setForceEagerSessionCreation(true); assertTrue(true);
filter.afterPropertiesSet(); }
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
filter.setAllowSessionCreation(true); public void testDetectsMissingOrInvalidContext() throws Exception {
filter.afterPropertiesSet(); HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
assertTrue(true);
}
public void testDetectsMissingOrInvalidContext() throws Exception { try {
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter(); filter.setContextClass(null);
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try { try {
filter.setContextClass(null); filter.setContextClass(Integer.class);
filter.afterPropertiesSet(); assertEquals(Integer.class, filter.getContextClass());
fail("Shown have thrown IllegalArgumentException"); filter.afterPropertiesSet();
} catch (IllegalArgumentException expected) { fail("Shown have thrown IllegalArgumentException");
assertTrue(true); } catch (IllegalArgumentException expected) {
} assertTrue(true);
}
}
try { public void testExceptionWithinFilterChainStillClearsSecurityContextHolder() throws Exception {
filter.setContextClass(Integer.class);
assertEquals(Integer.class, filter.getContextClass());
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testExceptionWithinFilterChainStillClearsSecurityContextHolder() throws Exception { // Build a Context to store in HttpSession (simulating prior request)
// Build an Authentication object we simulate came from HttpSession SecurityContext sc = new SecurityContextImpl();
PrincipalSpringSecurityUserToken sessionPrincipal = new PrincipalSpringSecurityUserToken( sc.setAuthentication(sessionPrincipal);
"key",
"someone",
"password",
new GrantedAuthority[] { new GrantedAuthorityImpl("SOME_ROLE") },
null);
// Build a Context to store in HttpSession (simulating prior request) // Build a mock request
SecurityContext sc = new SecurityContextImpl(); MockHttpServletRequest request = new MockHttpServletRequest();
sc.setAuthentication(sessionPrincipal); request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc);
// Build a mock request MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest(); FilterChain chain = new MockFilterChain(sessionPrincipal, null,
request.getSession().setAttribute( new IOException());
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc);
MockHttpServletResponse response = new MockHttpServletResponse(); // Prepare filter
FilterChain chain = new MockFilterChain(sessionPrincipal, null, HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
new IOException()); filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Prepare filter // Execute filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter(); try {
filter.setContextClass(SecurityContextImpl.class); executeFilterInContainerSimulator(new MockFilterConfig(), filter,
filter.afterPropertiesSet(); request, response, chain);
fail("We should have received the IOException thrown inside the filter chain here");
} catch (IOException ioe) {
assertTrue(true);
}
// Execute filter // Check the SecurityContextHolder is null, even though an exception was
try { // thrown during chain
executeFilterInContainerSimulator(new MockFilterConfig(), filter, assertEquals(new SecurityContextImpl(), SecurityContextHolder.getContext());
request, response, chain); assertNull("Should have cleared FILTER_APPLIED",
fail("We should have received the IOException thrown inside the filter chain here");
} catch (IOException ioe) {
assertTrue(true);
}
// Check the SecurityContextHolder is null, even though an exception was
// thrown during chain
assertEquals(new SecurityContextImpl(), SecurityContextHolder.getContext());
assertNull("Should have cleared FILTER_APPLIED",
request.getAttribute(HttpSessionContextIntegrationFilter.FILTER_APPLIED)); request.getAttribute(HttpSessionContextIntegrationFilter.FILTER_APPLIED));
} }
public void testExistingContextContentsCopiedIntoContextHolderFromSessionAndChangesToContextCopiedBackToSession() public void testExistingContextContentsCopiedIntoContextHolderFromSessionAndChangesToContextCopiedBackToSession()
throws Exception { throws Exception {
// Build an Authentication object we simulate came from HttpSession
PrincipalSpringSecurityUserToken sessionPrincipal = new PrincipalSpringSecurityUserToken(
"key",
"someone",
"password",
new GrantedAuthority[] { new GrantedAuthorityImpl("SOME_ROLE") },
null);
// Build an Authentication object we simulate our Authentication changed // Build an Authentication object we simulate came from HttpSession
// it to UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
PrincipalSpringSecurityUserToken updatedPrincipal = new PrincipalSpringSecurityUserToken( "someone",
"key", "someone", "password", "password",
new GrantedAuthority[] { new GrantedAuthorityImpl( AuthorityUtils.createAuthorityList("SOME_DIFFERENT_ROLE"));
"SOME_DIFFERENT_ROLE") }, null);
// Build a Context to store in HttpSession (simulating prior request) // Build a Context to store in HttpSession (simulating prior request)
SecurityContext sc = new SecurityContextImpl(); SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(sessionPrincipal); sc.setAuthentication(sessionPrincipal);
// Build a mock request // Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute( request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY, HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc); sc);
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(sessionPrincipal, FilterChain chain = new MockFilterChain(sessionPrincipal,
updatedPrincipal, null); updatedPrincipal, null);
// Prepare filter // Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter(); HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class); filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet(); filter.afterPropertiesSet();
// Execute filter // Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain); request, response, chain);
// Obtain new/update Authentication from HttpSession // Obtain new/update Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession().getAttribute( SecurityContext context = (SecurityContext) request.getSession().getAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY); HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication()); assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
} }
public void testHttpSessionCreatedWhenContextHolderChanges() throws Exception { public void testHttpSessionCreatedWhenContextHolderChanges() throws Exception {
// Build an Authentication object we simulate our Authentication changed it to // Build an Authentication object we simulate our Authentication changed it to
PrincipalSpringSecurityUserToken updatedPrincipal = new PrincipalSpringSecurityUserToken( UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
"key", "someone", "password", "someone",
new GrantedAuthority[] { new GrantedAuthorityImpl( "password",
"SOME_DIFFERENT_ROLE") }, null); AuthorityUtils.createAuthorityList("SOME_ROLE"));
// Build a mock request // Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null); FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
// Prepare filter // Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter(); HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class); filter.setContextClass(SecurityContextImpl.class);
// don't call afterPropertiesSet to test case when Spring filter.afterPropertiesSet(); isn't called // don't call afterPropertiesSet to test case when Spring filter.afterPropertiesSet(); isn't called
// Execute filter // Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain); executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Obtain new/updated Authentication from HttpSession // Obtain new/updated Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession(false).getAttribute( SecurityContext context = (SecurityContext) request.getSession(false).getAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY); HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication()); assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
} }
public void testHttpSessionEagerlyCreatedWhenDirected() throws Exception { public void testHttpSessionEagerlyCreatedWhenDirected() throws Exception {
// Build a mock request // Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest(null, null); MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, null, null); FilterChain chain = new MockFilterChain(null, null, null);
// Prepare filter // Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter(); HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class); filter.setContextClass(SecurityContextImpl.class);
filter.setForceEagerSessionCreation(true); // non-default filter.setForceEagerSessionCreation(true); // non-default
filter.afterPropertiesSet(); filter.afterPropertiesSet();
// Execute filter // Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain); request, response, chain);
// Check the session is not null // Check the session is not null
assertNotNull(request.getSession(false)); assertNotNull(request.getSession(false));
} }
public void testHttpSessionNotCreatedUnlessContextHolderChanges() throws Exception { public void testHttpSessionNotCreatedUnlessContextHolderChanges() throws Exception {
// Build a mock request // Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest(null, null); MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, null, null); FilterChain chain = new MockFilterChain(null, null, null);
// Prepare filter // Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter(); HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class); filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet(); filter.afterPropertiesSet();
// Execute filter // Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain); request, response, chain);
// Check the session is null // Check the session is null
assertNull(request.getSession(false)); assertNull(request.getSession(false));
} }
public void testHttpSessionWithNonContextInWellKnownLocationIsOverwritten() throws Exception { public void testHttpSessionWithNonContextInWellKnownLocationIsOverwritten() throws Exception {
// Build an Authentication object we simulate our Authentication changed // Build an Authentication object we simulate our Authentication changed it to
// it to UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
PrincipalSpringSecurityUserToken updatedPrincipal = new PrincipalSpringSecurityUserToken( "someone",
"key", "someone", "password", "password",
new GrantedAuthority[] { new GrantedAuthorityImpl( AuthorityUtils.createAuthorityList("SOME_DIFFERENT_ROLE"));
"SOME_DIFFERENT_ROLE") }, null);
// Build a mock request // Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute( request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY, HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
"NOT_A_CONTEXT_OBJECT"); "NOT_A_CONTEXT_OBJECT");
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null); FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
// Prepare filter // Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter(); HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class); filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet(); filter.afterPropertiesSet();
// Execute filter // Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain); executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Obtain new/update Authentication from HttpSession // Obtain new/update Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession().getAttribute( SecurityContext context = (SecurityContext) request.getSession().getAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY); HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication()); assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
} }
public void testConcurrentThreadsLazilyChangeFilterAppliedValueToTrue() throws Exception { public void testConcurrentThreadsLazilyChangeFilterAppliedValueToTrue() throws Exception {
PrincipalSpringSecurityUserToken sessionPrincipal = new PrincipalSpringSecurityUserToken( // Build a Context to store in HttpSession (simulating prior request)
"key", SecurityContext sc = new SecurityContextImpl();
"someone", sc.setAuthentication(sessionPrincipal);
"password",
new GrantedAuthority[] { new GrantedAuthorityImpl("SOME_ROLE") },
null);
// Build a Context to store in HttpSession (simulating prior request) MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContext sc = new SecurityContextImpl(); request.getSession().setAttribute(
sc.setAuthentication(sessionPrincipal); HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc);
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest(); // Prepare filter
request.getSession().setAttribute( HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY, filter.setContextClass(SecurityContextImpl.class);
sc); filter.afterPropertiesSet();
MockHttpServletResponse response = new MockHttpServletResponse();
// Prepare filter for (int i = 0; i < 3; i++) {
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter(); ThreadRunner runner = new ThreadRunner(request, response, filter,
filter.setContextClass(SecurityContextImpl.class); new MockFilterChain(sessionPrincipal, null, null));
filter.afterPropertiesSet(); runner.start();
}
for (int i = 0; i < 3; i++) { }
ThreadRunner runner = new ThreadRunner(request, response, filter,
new MockFilterChain(sessionPrincipal, null, null));
runner.start();
}
} //~ Inner Classes ==================================================================================================
// ~ Inner Classes private class MockFilterChain extends TestCase implements FilterChain {
// ================================================================================================== private Authentication changeContextHolder;
private Authentication expectedOnContextHolder;
private IOException toThrowDuringChain;
private class MockFilterChain extends TestCase implements FilterChain { public MockFilterChain(Authentication expectedOnContextHolder,
private Authentication changeContextHolder; Authentication changeContextHolder,
private Authentication expectedOnContextHolder; IOException toThrowDuringChain) {
private IOException toThrowDuringChain; this.expectedOnContextHolder = expectedOnContextHolder;
this.changeContextHolder = changeContextHolder;
this.toThrowDuringChain = toThrowDuringChain;
}
public MockFilterChain(Authentication expectedOnContextHolder, public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException, ServletException {
Authentication changeContextHolder, if (expectedOnContextHolder != null) {
IOException toThrowDuringChain) { assertEquals(expectedOnContextHolder, SecurityContextHolder.getContext().getAuthentication());
this.expectedOnContextHolder = expectedOnContextHolder; }
this.changeContextHolder = changeContextHolder;
this.toThrowDuringChain = toThrowDuringChain;
}
public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException, ServletException { if (changeContextHolder != null) {
if (expectedOnContextHolder != null) { SecurityContext sc = SecurityContextHolder.getContext();
assertEquals(expectedOnContextHolder, SecurityContextHolder.getContext().getAuthentication()); sc.setAuthentication(changeContextHolder);
} SecurityContextHolder.setContext(sc);
}
if (changeContextHolder != null) { if (toThrowDuringChain != null) {
SecurityContext sc = SecurityContextHolder.getContext(); throw toThrowDuringChain;
sc.setAuthentication(changeContextHolder); }
SecurityContextHolder.setContext(sc);
}
if (toThrowDuringChain != null) { }
throw toThrowDuringChain; }
}
} private static class ThreadRunner extends Thread {
} private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HttpSessionContextIntegrationFilter filter;
private MockFilterChain chain;
private static class ThreadRunner extends Thread { public ThreadRunner(MockHttpServletRequest request,
private MockHttpServletRequest request; MockHttpServletResponse response,
private MockHttpServletResponse response; HttpSessionContextIntegrationFilter filter,
private HttpSessionContextIntegrationFilter filter; MockFilterChain chain) {
private MockFilterChain chain; this.request = request;
this.response = response;
this.filter = filter;
this.chain = chain;
}
public ThreadRunner(MockHttpServletRequest request, public void run() {
MockHttpServletResponse response, try {
HttpSessionContextIntegrationFilter filter, // Execute filter
MockFilterChain chain) { executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
this.request = request;
this.response = response;
this.filter = filter;
this.chain = chain;
}
public void run() { // Check the session is not null
try { assertNotNull(request.getSession(false));
// Execute filter } catch (Exception e) {
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain); e.printStackTrace();
}
}
// Check the session is not null }
assertNotNull(request.getSession(false));
} catch (Exception e) {
e.printStackTrace();
}
}
}
} }

View File

@ -24,6 +24,7 @@ import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.DistinguishedName;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@ -53,9 +54,9 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=notfound")); DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=notfound"));
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "notfound"); List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notfound");
assertEquals(1, authorities.length); assertEquals(1, authorities.size());
assertEquals("ROLE_USER", authorities[0].getAuthority()); assertEquals("ROLE_USER", authorities.get(0).getAuthority());
} }
@Test @Test
@ -69,13 +70,13 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org")); DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "ben"); List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "ben");
assertEquals("Should have 2 roles", 2, authorities.length); assertEquals("Should have 2 roles", 2, authorities.size());
Set roles = new HashSet(); Set roles = new HashSet();
roles.add(authorities[0].toString()); roles.add(authorities.get(0).toString());
roles.add(authorities[1].toString()); roles.add(authorities.get(1).toString());
assertTrue(roles.contains("ROLE_DEVELOPER")); assertTrue(roles.contains("ROLE_DEVELOPER"));
assertTrue(roles.contains("ROLE_MANAGER")); assertTrue(roles.contains("ROLE_MANAGER"));
} }
@ -88,10 +89,10 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org")); DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "manager"); List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "manager");
assertEquals("Should have 1 role", 1, authorities.length); assertEquals("Should have 1 role", 1, authorities.size());
assertEquals("ROLE_MANAGER", authorities[0].getAuthority()); assertEquals("ROLE_MANAGER", authorities.get(0).getAuthority());
} }
@Test @Test
@ -101,12 +102,12 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org")); DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "manager"); List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "manager");
assertEquals("Should have 2 roles", 2, authorities.length); assertEquals("Should have 2 roles", 2, authorities.size());
Set roles = new HashSet(2); Set roles = new HashSet(2);
roles.add(authorities[0].getAuthority()); roles.add(authorities.get(0).getAuthority());
roles.add(authorities[1].getAuthority()); roles.add(authorities.get(1).getAuthority());
assertTrue(roles.contains("ROLE_MANAGER")); assertTrue(roles.contains("ROLE_MANAGER"));
assertTrue(roles.contains("ROLE_DEVELOPER")); assertTrue(roles.contains("ROLE_DEVELOPER"));
} }
@ -119,13 +120,13 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org")); DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "manager"); List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "manager");
assertEquals("Should have 3 roles", 3, authorities.length); assertEquals("Should have 3 roles", 3, authorities.size());
Set roles = new HashSet(3); Set roles = new HashSet(3);
roles.add(authorities[0].getAuthority()); roles.add(authorities.get(0).getAuthority());
roles.add(authorities[1].getAuthority()); roles.add(authorities.get(1).getAuthority());
roles.add(authorities[2].getAuthority()); roles.add(authorities.get(2).getAuthority());
assertTrue(roles.contains("ROLE_MANAGER")); assertTrue(roles.contains("ROLE_MANAGER"));
assertTrue(roles.contains("ROLE_DEVELOPER")); assertTrue(roles.contains("ROLE_DEVELOPER"));
assertTrue(roles.contains("ROLE_SUBMANAGER")); assertTrue(roles.contains("ROLE_SUBMANAGER"));
@ -134,15 +135,15 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
@Test @Test
public void testUserDnWithEscapedCharacterParameterReturnsExpectedRoles() { public void testUserDnWithEscapedCharacterParameterReturnsExpectedRoles() {
populator.setGroupRoleAttribute("ou"); populator.setGroupRoleAttribute("ou");
populator.setConvertToUpperCase(true); populator.setConvertToUpperCase(true);
populator.setGroupSearchFilter("(member={0})"); populator.setGroupSearchFilter("(member={0})");
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=mouse\\, jerry,ou=people,dc=springframework,dc=org")); DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"));
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "notused"); List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notused");
assertEquals("Should have 1 role", 1, authorities.size());
assertEquals("ROLE_MANAGER", authorities.get(0).getAuthority());
}
assertEquals("Should have 1 role", 1, authorities.length);
assertEquals("ROLE_MANAGER", authorities[0].getAuthority());
}
} }

View File

@ -1,5 +1,7 @@
package org.springframework.security.ldap.populator; package org.springframework.security.ldap.populator;
import java.util.List;
import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.MockUserDetailsService; import org.springframework.security.userdetails.MockUserDetailsService;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
@ -20,9 +22,9 @@ public class UserDetailsServiceLdapAuthoritiesPopulatorTests {
public void delegationToUserDetailsServiceReturnsCorrectRoles() throws Exception { public void delegationToUserDetailsServiceReturnsCorrectRoles() throws Exception {
UserDetailsServiceLdapAuthoritiesPopulator populator = new UserDetailsServiceLdapAuthoritiesPopulator(uds); UserDetailsServiceLdapAuthoritiesPopulator populator = new UserDetailsServiceLdapAuthoritiesPopulator(uds);
GrantedAuthority[] auths = populator.getGrantedAuthorities(new DirContextAdapter(), "valid"); List<GrantedAuthority> auths = populator.getGrantedAuthorities(new DirContextAdapter(), "valid");
assertEquals(1, auths.length); assertEquals(1, auths.size());
assertEquals("ROLE_USER", auths[0].getAuthority()); assertEquals("ROLE_USER", auths.get(0).getAuthority());
} }
} }

View File

@ -15,10 +15,17 @@
package org.springframework.security.providers; package org.springframework.security.providers;
import static org.junit.Assert.*;
import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.util.AuthorityUtils;
/** /**
@ -27,49 +34,28 @@ import org.springframework.security.GrantedAuthorityImpl;
* @author Ben Alex * @author Ben Alex
* @version $Id$ * @version $Id$
*/ */
public class AbstractAuthenticationTokenTests extends TestCase { public class AbstractAuthenticationTokenTests {
//~ Instance fields ================================================================================================ //~ Instance fields ================================================================================================
private GrantedAuthority[] authorities = null; private List<GrantedAuthority> authorities = null;
//~ Constructors ===================================================================================================
public AbstractAuthenticationTokenTests() {
super();
}
public AbstractAuthenticationTokenTests(String arg0) {
super(arg0);
}
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
public static void main(String[] args) { @Before
junit.textui.TestRunner.run(AbstractAuthenticationTokenTests.class);
}
public final void setUp() throws Exception { public final void setUp() throws Exception {
super.setUp(); authorities = AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO");
authorities = new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")};
} }
@Test(expected=UnsupportedOperationException.class)
public void testAuthoritiesAreImmutable() { public void testAuthoritiesAreImmutable() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities); MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
GrantedAuthority[] gotAuthorities = token.getAuthorities(); List<GrantedAuthority> gotAuthorities = token.getAuthorities();
assertNotSame(authorities, gotAuthorities); assertNotSame(authorities, gotAuthorities);
gotAuthorities[0] = new GrantedAuthorityImpl("ROLE_SUPER_USER"); gotAuthorities.set(0, new GrantedAuthorityImpl("ROLE_SUPER_USER"));
// reget them and check nothing has changed
gotAuthorities = token.getAuthorities();
assertEquals(2, gotAuthorities.length);
assertEquals(gotAuthorities[0], authorities[0]);
assertEquals(gotAuthorities[1], authorities[1]);
assertFalse(gotAuthorities[0].equals("ROLE_SUPER_USER"));
assertFalse(gotAuthorities[1].equals("ROLE_SUPER_USER"));
} }
@Test
public void testGetters() throws Exception { public void testGetters() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities); MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertEquals("Test", token.getPrincipal()); assertEquals("Test", token.getPrincipal());
@ -77,10 +63,11 @@ public class AbstractAuthenticationTokenTests extends TestCase {
assertEquals("Test", token.getName()); assertEquals("Test", token.getName());
} }
@Test
public void testHashCode() throws Exception { public void testHashCode() throws Exception {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities); MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities); MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token3 = new MockAuthenticationImpl(null, null, new GrantedAuthority[] {}); MockAuthenticationImpl token3 = new MockAuthenticationImpl(null, null, AuthorityUtils.NO_AUTHORITIES);
assertEquals(token1.hashCode(), token2.hashCode()); assertEquals(token1.hashCode(), token2.hashCode());
assertTrue(token1.hashCode() != token3.hashCode()); assertTrue(token1.hashCode() != token3.hashCode());
@ -89,6 +76,7 @@ public class AbstractAuthenticationTokenTests extends TestCase {
assertTrue(token1.hashCode() != token2.hashCode()); assertTrue(token1.hashCode() != token2.hashCode());
} }
@Test
public void testObjectsEquals() throws Exception { public void testObjectsEquals() throws Exception {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities); MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities); MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities);
@ -100,14 +88,10 @@ public class AbstractAuthenticationTokenTests extends TestCase {
MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed", "Password", authorities); MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed", "Password", authorities);
assertTrue(!token1.equals(token4)); assertTrue(!token1.equals(token4));
MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test", "Password", MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO_CHANGED"));
new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO_CHANGED")
});
assertTrue(!token1.equals(token5)); assertTrue(!token1.equals(token5));
MockAuthenticationImpl token6 = new MockAuthenticationImpl("Test", "Password", MockAuthenticationImpl token6 = new MockAuthenticationImpl("Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE"));
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE")});
assertTrue(!token1.equals(token6)); assertTrue(!token1.equals(token6));
MockAuthenticationImpl token7 = new MockAuthenticationImpl("Test", "Password", null); MockAuthenticationImpl token7 = new MockAuthenticationImpl("Test", "Password", null);
@ -117,6 +101,7 @@ public class AbstractAuthenticationTokenTests extends TestCase {
assertTrue(!token1.equals(new Integer(100))); assertTrue(!token1.equals(new Integer(100)));
} }
@Test
public void testSetAuthenticated() throws Exception { public void testSetAuthenticated() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities); MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertTrue(!token.isAuthenticated()); assertTrue(!token.isAuthenticated());
@ -124,11 +109,13 @@ public class AbstractAuthenticationTokenTests extends TestCase {
assertTrue(token.isAuthenticated()); assertTrue(token.isAuthenticated());
} }
@Test
public void testToStringWithAuthorities() { public void testToStringWithAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities); MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertTrue(token.toString().lastIndexOf("ROLE_TWO") != -1); assertTrue(token.toString().lastIndexOf("ROLE_TWO") != -1);
} }
@Test
public void testToStringWithNullAuthorities() { public void testToStringWithNullAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", null); MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", null);
assertTrue(token.toString().lastIndexOf("Not granted any authorities") != -1); assertTrue(token.toString().lastIndexOf("Not granted any authorities") != -1);
@ -140,7 +127,7 @@ public class AbstractAuthenticationTokenTests extends TestCase {
private Object credentials; private Object credentials;
private Object principal; private Object principal;
public MockAuthenticationImpl(Object principal, Object credentials, GrantedAuthority[] authorities) { public MockAuthenticationImpl(Object principal, Object credentials, List<GrantedAuthority> authorities) {
super(authorities); super(authorities);
this.principal = principal; this.principal = principal;
this.credentials = credentials; this.credentials = credentials;

View File

@ -25,7 +25,9 @@ import org.springframework.security.AccountStatusException;
import org.springframework.security.concurrent.ConcurrentSessionControllerImpl; import org.springframework.security.concurrent.ConcurrentSessionControllerImpl;
import org.springframework.security.concurrent.NullConcurrentSessionController; import org.springframework.security.concurrent.NullConcurrentSessionController;
import org.springframework.security.concurrent.ConcurrentLoginException; import org.springframework.security.concurrent.ConcurrentLoginException;
import org.springframework.security.util.AuthorityUtils;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Vector; import java.util.Vector;
@ -55,8 +57,7 @@ public class ProviderManagerTests {
@Test @Test
public void authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject() throws Exception { public void authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject() throws Exception {
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password","ROLE_ONE","ROLE_TWO");
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
ProviderManager mgr = makeProviderManager(); ProviderManager mgr = makeProviderManager();
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true)); mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
@ -70,15 +71,12 @@ public class ProviderManagerTests {
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result; TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
assertEquals("Test", castResult.getPrincipal()); assertEquals("Test", castResult.getPrincipal());
assertEquals("Password", castResult.getCredentials()); assertEquals("Password", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority()); assertEquals(AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO"), castResult.getAuthorities());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
} }
@Test @Test
public void authenticationSuccessWhenFirstProviderReturnsNullButSecondAuthenticates() { public void authenticationSuccessWhenFirstProviderReturnsNullButSecondAuthenticates() {
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password","ROLE_ONE","ROLE_TWO");
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
ProviderManager mgr = makeProviderManagerWithMockProviderWhichReturnsNullInList(); ProviderManager mgr = makeProviderManagerWithMockProviderWhichReturnsNullInList();
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true)); mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
@ -91,8 +89,8 @@ public class ProviderManagerTests {
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result; TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
assertEquals("Test", castResult.getPrincipal()); assertEquals("Test", castResult.getPrincipal());
assertEquals("Password", castResult.getCredentials()); assertEquals("Password", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority()); assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority()); assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
} }
@Test @Test
@ -193,7 +191,7 @@ public class ProviderManagerTests {
} }
private TestingAuthenticationToken createAuthenticationToken() { private TestingAuthenticationToken createAuthenticationToken() {
return new TestingAuthenticationToken("name", "password", new GrantedAuthorityImpl[0]); return new TestingAuthenticationToken("name", "password", new ArrayList<GrantedAuthority>(0));
} }
private ProviderManager makeProviderManager() throws Exception { private ProviderManager makeProviderManager() throws Exception {
@ -221,7 +219,7 @@ public class ProviderManagerTests {
return mgr; return mgr;
} }
//~ Inner Classes ================================================================================================== //~ Inner Classes ==================================================================================================
private class MockProvider implements AuthenticationProvider { private class MockProvider implements AuthenticationProvider {

View File

@ -18,9 +18,6 @@ package org.springframework.security.providers;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.springframework.security.Authentication; import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
/** /**
* Tests {@link TestingAuthenticationProvider}. * Tests {@link TestingAuthenticationProvider}.
@ -29,41 +26,19 @@ import org.springframework.security.GrantedAuthorityImpl;
* @version $Id$ * @version $Id$
*/ */
public class TestingAuthenticationProviderTests extends TestCase { public class TestingAuthenticationProviderTests extends TestCase {
//~ Constructors ===================================================================================================
public TestingAuthenticationProviderTests() {
super();
}
public TestingAuthenticationProviderTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(TestingAuthenticationProviderTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAuthenticates() { public void testAuthenticates() {
TestingAuthenticationProvider provider = new TestingAuthenticationProvider(); TestingAuthenticationProvider provider = new TestingAuthenticationProvider();
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password","ROLE_ONE","ROLE_TWO");
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
Authentication result = provider.authenticate(token); Authentication result = provider.authenticate(token);
if (!(result instanceof TestingAuthenticationToken)) { assertTrue(result instanceof TestingAuthenticationToken);
fail("Should have returned instance of TestingAuthenticationToken");
}
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result; TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
assertEquals("Test", castResult.getPrincipal()); assertEquals("Test", castResult.getPrincipal());
assertEquals("Password", castResult.getCredentials()); assertEquals("Password", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority()); assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority()); assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
} }
public void testSupports() { public void testSupports() {

View File

@ -19,6 +19,7 @@ import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.util.AuthorityUtils;
/** /**
@ -49,9 +50,9 @@ public class UsernamePasswordAuthenticationTokenTests extends TestCase {
} }
public void testAuthenticated() { public void testAuthenticated() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", null); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", AuthorityUtils.NO_AUTHORITIES);
// check default given we passed some GrantedAuthorty[]s (well, we passed null) // check default given we passed some GrantedAuthorty[]s (well, we passed empty list)
assertTrue(token.isAuthenticated()); assertTrue(token.isAuthenticated());
// check explicit set to untrusted (we can safely go from trusted to untrusted, but not the reverse) // check explicit set to untrusted (we can safely go from trusted to untrusted, but not the reverse)
@ -81,8 +82,8 @@ public class UsernamePasswordAuthenticationTokenTests extends TestCase {
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertEquals("Test", token.getPrincipal()); assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials()); assertEquals("Password", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority()); assertEquals("ROLE_ONE", token.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority()); assertEquals("ROLE_TWO", token.getAuthorities().get(1).getAuthority());
} }
public void testNoArgConstructorDoesntExist() { public void testNoArgConstructorDoesntExist() {

View File

@ -29,26 +29,8 @@ import org.springframework.security.providers.UsernamePasswordAuthenticationToke
* @version $Id$ * @version $Id$
*/ */
public class AnonymousAuthenticationTokenTests extends TestCase { public class AnonymousAuthenticationTokenTests extends TestCase {
//~ Constructors ===================================================================================================
public AnonymousAuthenticationTokenTests() {
super();
}
public AnonymousAuthenticationTokenTests(String arg0) {
super(arg0);
}
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AnonymousAuthenticationTokenTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testConstructorRejectsNulls() { public void testConstructorRejectsNulls() {
try { try {
new AnonymousAuthenticationToken(null, "Test", new AnonymousAuthenticationToken(null, "Test",
@ -66,12 +48,12 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
assertTrue(true); assertTrue(true);
} }
try { // try {
new AnonymousAuthenticationToken("key", "Test", null); // new AnonymousAuthenticationToken("key", "Test", null);
fail("Should have thrown IllegalArgumentException"); // fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) { // } catch (IllegalArgumentException expected) {
assertTrue(true); // assertTrue(true);
} // }
try { try {
new AnonymousAuthenticationToken("key", "Test", new GrantedAuthority[] {null}); new AnonymousAuthenticationToken("key", "Test", new GrantedAuthority[] {null});
@ -105,8 +87,8 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
assertEquals("key".hashCode(), token.getKeyHash()); assertEquals("key".hashCode(), token.getKeyHash());
assertEquals("Test", token.getPrincipal()); assertEquals("Test", token.getPrincipal());
assertEquals("", token.getCredentials()); assertEquals("", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority()); assertEquals("ROLE_ONE", token.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority()); assertEquals("ROLE_TWO", token.getAuthorities().get(1).getAuthority());
assertTrue(token.isAuthenticated()); assertTrue(token.isAuthenticated());
} }

View File

@ -150,8 +150,7 @@ public class AnonymousProcessingFilterTests extends TestCase {
assertEquals(originalAuth, SecurityContextHolder.getContext().getAuthentication()); assertEquals(originalAuth, SecurityContextHolder.getContext().getAuthentication());
} }
public void testOperationWhenNoAuthenticationInSecurityContextHolder() public void testOperationWhenNoAuthenticationInSecurityContextHolder() throws Exception {
throws Exception {
UserAttribute user = new UserAttribute(); UserAttribute user = new UserAttribute();
user.setPassword("anonymousUsername"); user.setPassword("anonymousUsername");
user.addAuthority(new GrantedAuthorityImpl("ROLE_ANONYMOUS")); user.addAuthority(new GrantedAuthorityImpl("ROLE_ANONYMOUS"));
@ -169,7 +168,7 @@ public class AnonymousProcessingFilterTests extends TestCase {
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication();
assertEquals("anonymousUsername", auth.getPrincipal()); assertEquals("anonymousUsername", auth.getPrincipal());
assertEquals(new GrantedAuthorityImpl("ROLE_ANONYMOUS"), auth.getAuthorities()[0]); assertEquals(new GrantedAuthorityImpl("ROLE_ANONYMOUS"), auth.getAuthorities().get(0));
SecurityContextHolder.getContext().setAuthentication(null); // so anonymous fires again SecurityContextHolder.getContext().setAuthentication(null); // so anonymous fires again
// Now test operation if we have removeAfterRequest = true // Now test operation if we have removeAfterRequest = true

View File

@ -69,18 +69,18 @@ public class DaoAuthenticationProviderTests extends TestCase {
} }
public void testReceivedBadCredentialsWhenCredentialsNotProvided() { public void testReceivedBadCredentialsWhenCredentialsNotProvided() {
// Test related to SEC-434 // Test related to SEC-434
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(new MockAuthenticationDaoUserrod()); provider.setUserDetailsService(new MockAuthenticationDaoUserrod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null);
try { try {
provider.authenticate(authenticationToken); provider.authenticate(authenticationToken);
fail("Expected BadCredenialsException"); fail("Expected BadCredenialsException");
} catch (BadCredentialsException expected) { } catch (BadCredentialsException expected) {
assertTrue(true); assertTrue(true);
} }
} }
public void testAuthenticateFailsIfAccountExpired() { public void testAuthenticateFailsIfAccountExpired() {
@ -263,8 +263,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result; UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertEquals(User.class, castResult.getPrincipal().getClass()); assertEquals(User.class, castResult.getPrincipal().getClass());
assertEquals("koala", castResult.getCredentials()); assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority()); assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority()); assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
assertEquals("192.168.0.1", castResult.getDetails()); assertEquals("192.168.0.1", castResult.getDetails());
} }
@ -313,8 +313,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
// We expect original credentials user submitted to be returned // We expect original credentials user submitted to be returned
assertEquals("koala", castResult.getCredentials()); assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority()); assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority()); assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
} }
public void testAuthenticatesWithForcePrincipalAsString() { public void testAuthenticatesWithForcePrincipalAsString() {

View File

@ -15,33 +15,30 @@
package org.springframework.security.providers.jaas; package org.springframework.security.providers.jaas;
import junit.framework.TestCase;
import org.springframework.security.*;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContextImpl;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.session.HttpSessionDestroyedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.web.MockHttpSession;
import java.net.URL; import java.net.URL;
import java.security.Security; import java.security.Security;
import java.util.Arrays;
import java.util.List; import java.util.List;
import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import junit.framework.TestCase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.LockedException;
import org.springframework.security.SpringSecurityException;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContextImpl;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.session.HttpSessionDestroyedEvent;
/** /**
* Tests for the JaasAuthenticationProvider * Tests for the JaasAuthenticationProvider
@ -155,14 +152,11 @@ public class JaasAuthenticationProviderTests extends TestCase {
assertNotNull(jaasProvider.getLoginConfig()); assertNotNull(jaasProvider.getLoginConfig());
assertNotNull(jaasProvider.getLoginContextName()); assertNotNull(jaasProvider.getLoginContextName());
List list = Arrays.asList(auth.getAuthorities()); List list = auth.getAuthorities();
assertTrue("GrantedAuthorities should contain ROLE_TEST1", list.contains(new GrantedAuthorityImpl("ROLE_TEST1"))); assertTrue("GrantedAuthorities should contain ROLE_TEST1", list.contains(new GrantedAuthorityImpl("ROLE_TEST1")));
assertTrue("GrantedAuthorities should contain ROLE_TEST2", list.contains(new GrantedAuthorityImpl("ROLE_TEST2"))); assertTrue("GrantedAuthorities should contain ROLE_TEST2", list.contains(new GrantedAuthorityImpl("ROLE_TEST2")));
assertTrue("GrantedAuthorities should contain ROLE_1", list.contains(role1)); assertTrue("GrantedAuthorities should contain ROLE_1", list.contains(role1));
assertTrue("GrantedAuthorities should contain ROLE_2", list.contains(role2)); assertTrue("GrantedAuthorities should contain ROLE_2", list.contains(role2));
boolean foundit = false; boolean foundit = false;
@ -179,10 +173,10 @@ public class JaasAuthenticationProviderTests extends TestCase {
assertTrue("Could not find a JaasGrantedAuthority", foundit); assertTrue("Could not find a JaasGrantedAuthority", foundit);
assertNotNull("Success event not fired", eventCheck.successEvent); assertNotNull("Success event should be fired", eventCheck.successEvent);
assertEquals("Auth objects are not equal", auth, eventCheck.successEvent.getAuthentication()); assertEquals("Auth objects should be equal", auth, eventCheck.successEvent.getAuthentication());
assertNull("Failure event was fired", eventCheck.failedEvent); assertNull("Failure event should not be fired", eventCheck.failedEvent);
} }
public void testGetApplicationEventPublisher() throws Exception { public void testGetApplicationEventPublisher() throws Exception {
@ -222,12 +216,12 @@ public class JaasAuthenticationProviderTests extends TestCase {
} }
public void testNullDefaultAuthorities() { public void testNullDefaultAuthorities() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password", null); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
assertTrue(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)); assertTrue(jaasProvider.supports(UsernamePasswordAuthenticationToken.class));
Authentication auth = jaasProvider.authenticate(token); Authentication auth = jaasProvider.authenticate(token);
assertTrue("Only ROLE_TEST1 and ROLE_TEST2 should have been returned", auth.getAuthorities().length == 2); assertTrue("Only ROLE_TEST1 and ROLE_TEST2 should have been returned", auth.getAuthorities().size() == 2);
} }
public void testUnsupportedAuthenticationObjectReturnsNull() { public void testUnsupportedAuthenticationObjectReturnsNull() {

View File

@ -23,6 +23,7 @@ import org.springframework.security.ldap.LdapAuthoritiesPopulator;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken; import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.ldap.LdapUserDetailsMapper; import org.springframework.security.userdetails.ldap.LdapUserDetailsMapper;
import org.springframework.security.util.AuthorityUtils;
import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.DistinguishedName;
@ -30,6 +31,7 @@ import org.springframework.ldap.core.DistinguishedName;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
/** /**
@ -101,14 +103,14 @@ public class LdapAuthenticationProviderTests extends TestCase {
Authentication authResult = ldapProvider.authenticate(authRequest); Authentication authResult = ldapProvider.authenticate(authRequest);
assertEquals("benspassword", authResult.getCredentials()); assertEquals("benspassword", authResult.getCredentials());
UserDetails user = (UserDetails) authResult.getPrincipal(); UserDetails user = (UserDetails) authResult.getPrincipal();
assertEquals(2, user.getAuthorities().length); assertEquals(2, user.getAuthorities().size());
assertEquals("{SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=", user.getPassword()); assertEquals("{SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=", user.getPassword());
assertEquals("ben", user.getUsername()); assertEquals("ben", user.getUsername());
assertEquals("ben", populator.getRequestedUsername()); assertEquals("ben", populator.getRequestedUsername());
ArrayList authorities = new ArrayList(); ArrayList authorities = new ArrayList();
authorities.add(user.getAuthorities()[0].getAuthority()); authorities.add(user.getAuthorities().get(0).getAuthority());
authorities.add(user.getAuthorities()[1].getAuthority()); authorities.add(user.getAuthorities().get(1).getAuthority());
assertTrue(authorities.contains("ROLE_FROM_ENTRY")); assertTrue(authorities.contains("ROLE_FROM_ENTRY"));
assertTrue(authorities.contains("ROLE_FROM_POPULATOR")); assertTrue(authorities.contains("ROLE_FROM_POPULATOR"));
@ -132,8 +134,8 @@ public class LdapAuthenticationProviderTests extends TestCase {
ldapProvider.setUserDetailsContextMapper(userMapper); ldapProvider.setUserDetailsContextMapper(userMapper);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("ben", "benspassword"); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("ben", "benspassword");
UserDetails user = (UserDetails) ldapProvider.authenticate(authRequest).getPrincipal(); UserDetails user = (UserDetails) ldapProvider.authenticate(authRequest).getPrincipal();
assertEquals(1, user.getAuthorities().length); assertEquals(1, user.getAuthorities().size());
assertEquals("ROLE_FROM_ENTRY", user.getAuthorities()[0].getAuthority()); assertEquals("ROLE_FROM_ENTRY", user.getAuthorities().get(0).getAuthority());
} }
//~ Inner Classes ================================================================================================== //~ Inner Classes ==================================================================================================
@ -165,9 +167,9 @@ public class LdapAuthenticationProviderTests extends TestCase {
class MockAuthoritiesPopulator implements LdapAuthoritiesPopulator { class MockAuthoritiesPopulator implements LdapAuthoritiesPopulator {
String username; String username;
public GrantedAuthority[] getGrantedAuthorities(DirContextOperations userCtx, String username) { public List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userCtx, String username) {
this.username = username; this.username = username;
return new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_FROM_POPULATOR")}; return AuthorityUtils.createAuthorityList("ROLE_FROM_POPULATOR");
} }
String getRequestedUsername() { String getRequestedUsername() {

View File

@ -9,49 +9,48 @@ import java.util.Collection;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
* *
* @author TSARDD * @author TSARDD
* @since 18-okt-2007 * @since 18-okt-2007
*/ */
public class PreAuthenticatedAuthenticationTokenTests extends TestCase { public class PreAuthenticatedAuthenticationTokenTests extends TestCase {
public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() { public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() {
Object principal = "dummyUser"; Object principal = "dummyUser";
Object credentials = "dummyCredentials"; Object credentials = "dummyCredentials";
Object details = "dummyDetails"; Object details = "dummyDetails";
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
token.setDetails(details); token.setDetails(details);
assertEquals(principal, token.getPrincipal()); assertEquals(principal, token.getPrincipal());
assertEquals(credentials, token.getCredentials()); assertEquals(credentials, token.getCredentials());
assertEquals(details, token.getDetails()); assertEquals(details, token.getDetails());
assertNull(token.getAuthorities()); assertNull(token.getAuthorities());
} }
public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() { public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() {
Object principal = "dummyUser"; Object principal = "dummyUser";
Object credentials = "dummyCredentials"; Object credentials = "dummyCredentials";
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
assertEquals(principal, token.getPrincipal()); assertEquals(principal, token.getPrincipal());
assertEquals(credentials, token.getCredentials()); assertEquals(credentials, token.getCredentials());
assertNull(token.getDetails()); assertNull(token.getDetails());
assertNull(token.getAuthorities()); assertNull(token.getAuthorities());
} }
public void testPreAuthenticatedAuthenticationTokenResponse() { public void testPreAuthenticatedAuthenticationTokenResponse() {
Object principal = "dummyUser"; Object principal = "dummyUser";
Object credentials = "dummyCredentials"; Object credentials = "dummyCredentials";
GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1") }; GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1") };
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials, gas); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials, gas);
assertEquals(principal, token.getPrincipal()); assertEquals(principal, token.getPrincipal());
assertEquals(credentials, token.getCredentials()); assertEquals(credentials, token.getCredentials());
assertNull(token.getDetails()); assertNull(token.getDetails());
assertNotNull(token.getAuthorities()); assertNotNull(token.getAuthorities());
Collection expectedColl = Arrays.asList(gas); Collection expectedColl = Arrays.asList(gas);
Collection resultColl = Arrays.asList(token.getAuthorities()); Collection resultColl = token.getAuthorities();
assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl,
.containsAll(resultColl) expectedColl.containsAll(resultColl) && resultColl.containsAll(expectedColl));
&& resultColl.containsAll(expectedColl));
} }
} }

View File

@ -1,80 +1,77 @@
package org.springframework.security.providers.preauth; package org.springframework.security.providers.preauth;
import org.springframework.security.GrantedAuthoritiesContainer; import static org.junit.Assert.assertEquals;
import org.springframework.security.GrantedAuthorityImpl; import static org.junit.Assert.assertTrue;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetails;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import junit.framework.TestCase; import org.junit.Test;
import org.springframework.security.GrantedAuthoritiesContainer;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.util.AuthorityUtils;
/** /**
* *
* @author TSARDD * @author TSARDD
* @since 18-okt-2007 * @since 18-okt-2007
*/ */
public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests extends TestCase { public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
public final void testGetUserDetailsInvalidType() { @Test(expected=IllegalArgumentException.class)
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService(); public void testGetUserDetailsInvalidType() {
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy"); PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
token.setDetails(new Object()); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
try { token.setDetails(new Object());
svc.loadUserDetails(token); svc.loadUserDetails(token);
fail("Expected exception didn't occur"); }
} catch (IllegalArgumentException expected) {
}
}
public final void testGetUserDetailsNoDetails() { @Test(expected=IllegalArgumentException.class)
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService(); public void testGetUserDetailsNoDetails() {
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy"); PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
token.setDetails(null); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
try { token.setDetails(null);
svc.loadUserDetails(token); svc.loadUserDetails(token);
fail("Expected exception didn't occur"); }
} catch (IllegalArgumentException expected) {
}
}
public final void testGetUserDetailsEmptyAuthorities() { @Test
final String userName = "dummyUser"; public void testGetUserDetailsEmptyAuthorities() {
final GrantedAuthority[] gas = new GrantedAuthority[] {}; final String userName = "dummyUser";
testGetUserDetails(userName, gas); testGetUserDetails(userName, AuthorityUtils.NO_AUTHORITIES);
} }
public final void testGetUserDetailsWithAuthorities() { @Test
final String userName = "dummyUser"; public void testGetUserDetailsWithAuthorities() {
final GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1"), new GrantedAuthorityImpl("Role2") }; final String userName = "dummyUser";
testGetUserDetails(userName, gas); testGetUserDetails(userName, AuthorityUtils.createAuthorityList("Role1", "Role2"));
} }
private void testGetUserDetails(final String userName, final GrantedAuthority[] gas) { private void testGetUserDetails(final String userName, final List<GrantedAuthority> gas) {
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService(); PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userName, "dummy"); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userName, "dummy");
token.setDetails(new GrantedAuthoritiesContainer() { token.setDetails(new GrantedAuthoritiesContainer() {
public GrantedAuthority[] getGrantedAuthorities() { public List<GrantedAuthority> getGrantedAuthorities() {
return gas; return gas;
} }
}); });
UserDetails ud = svc.loadUserDetails(token); UserDetails ud = svc.loadUserDetails(token);
assertTrue(ud.isAccountNonExpired()); assertTrue(ud.isAccountNonExpired());
assertTrue(ud.isAccountNonLocked()); assertTrue(ud.isAccountNonLocked());
assertTrue(ud.isCredentialsNonExpired()); assertTrue(ud.isCredentialsNonExpired());
assertTrue(ud.isEnabled()); assertTrue(ud.isEnabled());
assertEquals(ud.getUsername(), userName); assertEquals(ud.getUsername(), userName);
//Password is not saved by //Password is not saved by
// PreAuthenticatedGrantedAuthoritiesUserDetailsService // PreAuthenticatedGrantedAuthoritiesUserDetailsService
//assertEquals(ud.getPassword(),password); //assertEquals(ud.getPassword(),password);
Collection expectedColl = Arrays.asList(gas); Collection expectedColl = Arrays.asList(gas);
Collection resultColl = Arrays.asList(ud.getAuthorities()); Collection resultColl = Arrays.asList(ud.getAuthorities());
assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
.containsAll(resultColl) .containsAll(resultColl)
&& resultColl.containsAll(expectedColl)); && resultColl.containsAll(expectedColl));
} }
} }

View File

@ -56,8 +56,7 @@ public class RemoteAuthenticationManagerImplTests extends TestCase {
assertNotNull(manager.getAuthenticationManager()); assertNotNull(manager.getAuthenticationManager());
} }
public void testStartupChecksAuthenticationManagerSet() public void testStartupChecksAuthenticationManagerSet() throws Exception {
throws Exception {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
try { try {

View File

@ -82,7 +82,7 @@ public class RemoteAuthenticationProviderTests extends TestCase {
Authentication result = provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password")); Authentication result = provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
assertEquals("rod", result.getPrincipal()); assertEquals("rod", result.getPrincipal());
assertEquals("password", result.getCredentials()); assertEquals("password", result.getCredentials());
assertEquals("foo", result.getAuthorities()[0].getAuthority()); assertEquals("foo", result.getAuthorities().get(0).getAuthority());
} }
public void testSupports() { public void testSupports() {

View File

@ -79,8 +79,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(); RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider();
aap.setKey("qwerty"); aap.setKey("qwerty");
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password", TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password","ROLE_A");
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
assertFalse(aap.supports(TestingAuthenticationToken.class)); assertFalse(aap.supports(TestingAuthenticationToken.class));
// Try it anyway // Try it anyway

View File

@ -91,22 +91,11 @@ public class RememberMeAuthenticationTokenTests extends TestCase {
assertEquals("key".hashCode(), token.getKeyHash()); assertEquals("key".hashCode(), token.getKeyHash());
assertEquals("Test", token.getPrincipal()); assertEquals("Test", token.getPrincipal());
assertEquals("", token.getCredentials()); assertEquals("", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority()); assertEquals("ROLE_ONE", token.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority()); assertEquals("ROLE_TWO", token.getAuthorities().get(1).getAuthority());
assertTrue(token.isAuthenticated()); assertTrue(token.isAuthenticated());
} }
public void testNoArgConstructorDoesntExist() {
Class clazz = RememberMeAuthenticationToken.class;
try {
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);
}
}
public void testNotEqualsDueToAbstractParentEqualsCheck() { public void testNotEqualsDueToAbstractParentEqualsCheck() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});

View File

@ -1,131 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509;
import junit.framework.TestCase;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import java.security.cert.X509Certificate;
/**
* Tests {@link X509AuthenticationProvider}
*
* @author Luke Taylor
* @version $Id$
*/
public class X509AuthenticationProviderTests extends TestCase {
//~ Constructors ===================================================================================================
public X509AuthenticationProviderTests() {
super();
}
public X509AuthenticationProviderTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public final void setUp() throws Exception {
super.setUp();
}
public void testAuthenticationIsNullWithUnsupportedToken() {
X509AuthenticationProvider provider = new X509AuthenticationProvider();
Authentication request = new UsernamePasswordAuthenticationToken("dummy", "dummy");
Authentication result = provider.authenticate(request);
assertNull(result);
}
public void testFailsWithNullCertificate() {
X509AuthenticationProvider provider = new X509AuthenticationProvider();
provider.setX509AuthoritiesPopulator(new MockAuthoritiesPopulator(false));
try {
provider.authenticate(new X509AuthenticationToken(null));
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException e) {
//ignore
}
}
public void testNormalOperation() throws Exception {
X509AuthenticationProvider provider = new X509AuthenticationProvider();
provider.setX509AuthoritiesPopulator(new MockAuthoritiesPopulator(false));
provider.afterPropertiesSet();
Authentication result = provider.authenticate(X509TestUtils.createToken());
assertNotNull(result);
assertNotNull(result.getAuthorities());
}
public void testPopulatorRejectionCausesFailure() throws Exception {
X509AuthenticationProvider provider = new X509AuthenticationProvider();
provider.setX509AuthoritiesPopulator(new MockAuthoritiesPopulator(true));
try {
provider.authenticate(X509TestUtils.createToken());
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException e) {
//ignore
}
}
public void testRequiresPopulator() throws Exception {
X509AuthenticationProvider provider = new X509AuthenticationProvider();
try {
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException failed) {
//ignored
}
}
//~ Inner Classes ==================================================================================================
public static class MockAuthoritiesPopulator implements X509AuthoritiesPopulator {
private boolean rejectCertificate;
public MockAuthoritiesPopulator(boolean rejectCertificate) {
this.rejectCertificate = rejectCertificate;
}
public UserDetails getUserDetails(X509Certificate userCertificate)
throws AuthenticationException {
if (rejectCertificate) {
throw new BadCredentialsException("Invalid Certificate");
}
return new User("user", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B")});
}
}
}

View File

@ -1,52 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509;
import junit.framework.TestCase;
/**
* Tests for {@link X509AuthenticationToken}.
*
* @author Luke Taylor
* @version $Id$
*/
public class X509AuthenticationTokenTests extends TestCase {
//~ Constructors ===================================================================================================
public X509AuthenticationTokenTests() {}
public X509AuthenticationTokenTests(String s) {
super(s);
}
//~ Methods ========================================================================================================
public void setUp() throws Exception {
super.setUp();
}
public void testAuthenticated() throws Exception {
X509AuthenticationToken token = X509TestUtils.createToken();
assertTrue(!token.isAuthenticated());
token.setAuthenticated(true);
assertTrue(token.isAuthenticated());
}
public void testEquals() throws Exception {
assertEquals(X509TestUtils.createToken(), X509TestUtils.createToken());
}
}

View File

@ -1,89 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509.cache;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Cache;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.x509.X509TestUtils;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests for {@link EhCacheBasedX509UserCache}.
*
* @author Luke Taylor
* @version $Id$
*/
public class EhCacheBasedX509UserCacheTests {
private static CacheManager cacheManager;
//~ Methods ========================================================================================================
@BeforeClass
public static void initCacheManaer() {
cacheManager = new CacheManager();
cacheManager.addCache(new Cache("x509cachetests", 500, false, false, 30, 30));
}
@AfterClass
public static void shutdownCacheManager() {
cacheManager.removalAll();
cacheManager.shutdown();
}
private Ehcache getCache() {
Ehcache cache = cacheManager.getCache("x509cachetests");
cache.removeAll();
return cache;
}
private UserDetails getUser() {
return new User("rod", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
}
@Test
public void cacheOperationsAreSucessful() throws Exception {
EhCacheBasedX509UserCache cache = new EhCacheBasedX509UserCache();
cache.setCache(getCache());
cache.afterPropertiesSet();
// Check it gets stored in the cache
cache.putUserInCache(X509TestUtils.buildTestCertificate(), getUser());
assertEquals(getUser().getPassword(), cache.getUserFromCache(X509TestUtils.buildTestCertificate()).getPassword());
// Check it gets removed from the cache
cache.removeUserFromCache(X509TestUtils.buildTestCertificate());
assertNull(cache.getUserFromCache(X509TestUtils.buildTestCertificate()));
// Check it doesn't return values for null user
assertNull(cache.getUserFromCache(null));
}
}

View File

@ -1,146 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.providers.x509.populator;
import junit.framework.TestCase;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.x509.X509TestUtils;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import java.security.cert.X509Certificate;
/**
* Tests for {@link DaoX509AuthoritiesPopulator}
*
* @author Luke Taylor
* @version $Id$
*/
public class DaoX509AuthoritiesPopulatorTests extends TestCase {
//~ Constructors ===================================================================================================
public DaoX509AuthoritiesPopulatorTests() {
}
public DaoX509AuthoritiesPopulatorTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public final void setUp() throws Exception {
super.setUp();
}
public void testDefaultCNPatternMatch() throws Exception {
X509Certificate cert = X509TestUtils.buildTestCertificate();
DaoX509AuthoritiesPopulator populator = new DaoX509AuthoritiesPopulator();
populator.setUserDetailsService(new MockAuthenticationDaoMatchesNameOrEmail());
populator.afterPropertiesSet();
populator.getUserDetails(cert);
}
public void testEmailPatternMatch() throws Exception {
X509Certificate cert = X509TestUtils.buildTestCertificate();
DaoX509AuthoritiesPopulator populator = new DaoX509AuthoritiesPopulator();
populator.setUserDetailsService(new MockAuthenticationDaoMatchesNameOrEmail());
populator.setSubjectDNRegex("emailAddress=(.*?),");
populator.afterPropertiesSet();
populator.getUserDetails(cert);
}
public void testInvalidRegexFails() throws Exception {
DaoX509AuthoritiesPopulator populator = new DaoX509AuthoritiesPopulator();
populator.setUserDetailsService(new MockAuthenticationDaoMatchesNameOrEmail());
populator.setSubjectDNRegex("CN=(.*?,"); // missing closing bracket on group
try {
populator.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException failed) {
// ignored
}
}
public void testMatchOnShoeSizeFieldInDNFails() throws Exception {
X509Certificate cert = X509TestUtils.buildTestCertificate();
DaoX509AuthoritiesPopulator populator = new DaoX509AuthoritiesPopulator();
populator.setUserDetailsService(new MockAuthenticationDaoMatchesNameOrEmail());
populator.setSubjectDNRegex("shoeSize=(.*?),");
populator.afterPropertiesSet();
try {
populator.getUserDetails(cert);
fail("Should have thrown BadCredentialsException.");
} catch (BadCredentialsException failed) {
// ignored
}
}
public void testPatternWithNoGroupFails() throws Exception {
X509Certificate cert = X509TestUtils.buildTestCertificate();
DaoX509AuthoritiesPopulator populator = new DaoX509AuthoritiesPopulator();
populator.setUserDetailsService(new MockAuthenticationDaoMatchesNameOrEmail());
populator.setSubjectDNRegex("CN=.*?,");
populator.afterPropertiesSet();
try {
populator.getUserDetails(cert);
fail("Should have thrown IllegalArgumentException for regexp without group");
} catch (IllegalArgumentException e) {
// ignored
}
}
public void testRequiresDao() throws Exception {
DaoX509AuthoritiesPopulator populator = new DaoX509AuthoritiesPopulator();
try {
populator.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException failed) {
// ignored
}
}
//~ Inner Classes ==================================================================================================
private class MockAuthenticationDaoMatchesNameOrEmail implements UserDetailsService {
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
if ("Luke Taylor".equals(username) || "luke@monkeymachine".equals(username)) {
return new User("luke", "monkey", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE")});
} else {
throw new UsernameNotFoundException("Could not find: " + username);
}
}
}
}

View File

@ -64,9 +64,9 @@ public class RunAsManagerImplTests extends TestCase {
assertEquals(inputToken.getPrincipal(), resultingToken.getPrincipal()); assertEquals(inputToken.getPrincipal(), resultingToken.getPrincipal());
assertEquals(inputToken.getCredentials(), resultingToken.getCredentials()); assertEquals(inputToken.getCredentials(), resultingToken.getCredentials());
assertEquals("FOOBAR_RUN_AS_SOMETHING", resultingToken.getAuthorities()[0].getAuthority()); assertEquals("FOOBAR_RUN_AS_SOMETHING", resultingToken.getAuthorities().get(0).getAuthority());
assertEquals("ONE", resultingToken.getAuthorities()[1].getAuthority()); assertEquals("ONE", resultingToken.getAuthorities().get(1).getAuthority());
assertEquals("TWO", resultingToken.getAuthorities()[2].getAuthority()); assertEquals("TWO", resultingToken.getAuthorities().get(2).getAuthority());
RunAsUserToken resultCast = (RunAsUserToken) resultingToken; RunAsUserToken resultCast = (RunAsUserToken) resultingToken;
assertEquals("my_password".hashCode(), resultCast.getKeyHash()); assertEquals("my_password".hashCode(), resultCast.getKeyHash());
@ -87,9 +87,9 @@ public class RunAsManagerImplTests extends TestCase {
assertEquals(inputToken.getPrincipal(), resultingToken.getPrincipal()); assertEquals(inputToken.getPrincipal(), resultingToken.getPrincipal());
assertEquals(inputToken.getCredentials(), resultingToken.getCredentials()); assertEquals(inputToken.getCredentials(), resultingToken.getCredentials());
assertEquals("ROLE_RUN_AS_SOMETHING", resultingToken.getAuthorities()[0].getAuthority()); assertEquals("ROLE_RUN_AS_SOMETHING", resultingToken.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_ONE", resultingToken.getAuthorities()[1].getAuthority()); assertEquals("ROLE_ONE", resultingToken.getAuthorities().get(1).getAuthority());
assertEquals("ROLE_TWO", resultingToken.getAuthorities()[2].getAuthority()); assertEquals("ROLE_TWO", resultingToken.getAuthorities().get(2).getAuthority());
RunAsUserToken resultCast = (RunAsUserToken) resultingToken; RunAsUserToken resultCast = (RunAsUserToken) resultingToken;
assertEquals("my_password".hashCode(), resultCast.getKeyHash()); assertEquals("my_password".hashCode(), resultCast.getKeyHash());

View File

@ -1,68 +1,65 @@
package org.springframework.security.ui.preauth; package org.springframework.security.ui.preauth;
import org.springframework.security.GrantedAuthorityImpl; import static org.junit.Assert.assertTrue;
import org.springframework.security.GrantedAuthority;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import junit.framework.TestCase; import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.util.AuthorityUtils;
/** /**
* @author TSARDD * @author TSARDD
*/ */
public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests extends TestCase { public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1", "Role2");
public final void testToString() { @Test
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( public void testToString() {
getRequest("testUser", new String[] {})); PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1"), new GrantedAuthorityImpl("Role2") }; getRequest("testUser", new String[] {}));
details.setGrantedAuthorities(gas); details.setGrantedAuthorities(gas);
String toString = details.toString(); String toString = details.toString();
assertTrue("toString should contain Role1", toString.contains("Role1")); assertTrue("toString should contain Role1", toString.contains("Role1"));
assertTrue("toString should contain Role2", toString.contains("Role2")); assertTrue("toString should contain Role2", toString.contains("Role2"));
} }
public final void testGetSetPreAuthenticatedGrantedAuthorities() { @Test
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( public void testGetSetPreAuthenticatedGrantedAuthorities() {
getRequest("testUser", new String[] {})); PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1"), new GrantedAuthorityImpl("Role2") }; getRequest("testUser", new String[] {}));
Collection expectedGas = Arrays.asList(gas);
details.setGrantedAuthorities(gas); Collection expectedGas = Arrays.asList(gas);
Collection returnedGas = Arrays.asList(details.getGrantedAuthorities());
assertTrue("Collections do not contain same elements; expected: " + expectedGas + ", returned: " + returnedGas,
expectedGas.containsAll(returnedGas) && returnedGas.containsAll(expectedGas));
}
public final void testGetWithoutSetPreAuthenticatedGrantedAuthorities() { details.setGrantedAuthorities(gas);
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( Collection returnedGas = Arrays.asList(details.getGrantedAuthorities());
getRequest("testUser", new String[] {})); assertTrue("Collections do not contain same elements; expected: " + expectedGas + ", returned: " + returnedGas,
try { expectedGas.containsAll(returnedGas) && returnedGas.containsAll(expectedGas));
GrantedAuthority[] gas = details.getGrantedAuthorities(); }
fail("Expected exception didn't occur");
} catch (IllegalArgumentException expected) { @Test(expected=IllegalArgumentException.class)
} catch (Exception unexpected) { public void testGetWithoutSetPreAuthenticatedGrantedAuthorities() {
fail("Unexpected exception: " + unexpected.toString()); PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
} getRequest("testUser", new String[] {}));
} List<GrantedAuthority> gas = details.getGrantedAuthorities();
}
private final HttpServletRequest getRequest(final String userName,final String[] aRoles)
{ private HttpServletRequest getRequest(final String userName,final String[] aRoles) {
MockHttpServletRequest req = new MockHttpServletRequest() { MockHttpServletRequest req = new MockHttpServletRequest() {
private Set roles = new HashSet(Arrays.asList(aRoles)); private Set roles = new HashSet(Arrays.asList(aRoles));
public boolean isUserInRole(String arg0) { public boolean isUserInRole(String arg0) {
return roles.contains(arg0); return roles.contains(arg0);
} }
}; };
req.setRemoteUser(userName); req.setRemoteUser(userName);
return req; return req;
} }
} }

Some files were not shown because too many files have changed in this diff Show More