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;
import java.util.List;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
@ -100,10 +102,10 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
}
// 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++) {
if (requiredAuthority.equals(auths[i])) {
for (int i = 0; i < auths.size(); i++) {
if (requiredAuthority.equals(auths.get(i))) {
return;
}
}

View File

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

View File

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

View File

@ -23,6 +23,8 @@ import org.springframework.security.providers.AbstractAuthenticationToken;
import org.springframework.security.userdetails.UserDetails;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
* Represents a successful CAS <code>Authentication</code>.
@ -43,7 +45,15 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
//~ 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.
*
* @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
*/
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);
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) {
CasAuthenticationToken test = (CasAuthenticationToken) obj;
if (!this.assertion.equals(test.getAssertion())) {
return false;
return false;
}
if (this.getKeyHash() != test.getKeyHash()) {

View File

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

View File

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

View File

@ -18,6 +18,7 @@ package org.springframework.security;
import java.io.Serializable;
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
*/
GrantedAuthority[] getAuthorities();
List<GrantedAuthority> getAuthorities();
/**
* 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
* <code>Authentication</code> object (including granted authorities) if successful.<p>An
* <code>AuthenticationManager</code> must honour the following contract concerning exceptions:</p>
* <p>A {@link DisabledException} must be thrown if an account is disabled and the
* <code>AuthenticationManager</code> can test for this state.</p>
* <p>A {@link LockedException} must be thrown if an account is locked and the
* <code>AuthenticationManager</code> can test for account locking.</p>
* <p>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.</p>
* <p>Exceptions should be tested for and if applicable thrown in the order expressed above (ie if an
* <code>Authentication</code> object (including granted authorities) if successful.
* <p>
* An <code>AuthenticationManager</code> must honour the following contract concerning exceptions:
* <ul>
* <li>A {@link DisabledException} must be thrown if an account is disabled and the
* <code>AuthenticationManager</code> can test for this state.</li>
* <li>A {@link LockedException} must be thrown if an account is locked and the
* <code>AuthenticationManager</code> can test for account locking.</li>
* <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
* 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
*
@ -44,6 +47,5 @@ public interface AuthenticationManager {
*
* @throws AuthenticationException if authentication fails
*/
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
Authentication authenticate(Authentication authentication) throws AuthenticationException;
}

View File

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

View File

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

View File

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

View File

@ -1,5 +1,7 @@
package org.springframework.security;
import java.util.List;
/**
* Indicates that a object can be used to store and retrieve GrantedAuthority objects.
* <p>
@ -14,5 +16,5 @@ public interface MutableGrantedAuthoritiesContainer extends GrantedAuthoritiesCo
/**
* 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
* 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
* the recipient in the <code>BasicAclEntry</code> is the same as the principal or granted authority.</p>
* <P>This class should prove an adequate ACLs resolver if you're using standard Spring Security classes. This is
* 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
* 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
* 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
// granted authorities to decide whether the presented
// 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()) {
logger.debug("Did not match principal and there are no granted authorities, "
+ "so cannot compare with recipient: " + recipient);
@ -104,10 +105,10 @@ public class GrantedAuthorityEffectiveAclsResolver implements EffectiveAclsResol
continue;
}
for (int k = 0; k < authorities.length; k++) {
if (authorities[k].equals(recipient)) {
for (int k = 0; k < authorities.size(); k++) {
if (authorities.get(k).equals(recipient)) {
if (logger.isDebugEnabled()) {
logger.debug("GrantedAuthority: " + authorities[k] + " matches recipient: " + recipient);
logger.debug("GrantedAuthority: " + authorities.get(k) + " matches recipient: " + recipient);
}
list.add(allAcls[i]);

View File

@ -1,5 +1,8 @@
package org.springframework.security.authoritymapping;
import java.util.Collection;
import java.util.List;
import org.springframework.security.GrantedAuthority;
/**
@ -20,5 +23,5 @@ public interface Attributes2GrantedAuthoritiesMapper {
* @param attribute the attributes to be mapped
* @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
* MappableAttributesRetriever interfaces based on the supplied Map.
* 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
* GrantedAuthority object.
* </p>
*
* @author Ruud Senden
*/
public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2GrantedAuthoritiesMapper, MappableAttributesRetriever, InitializingBean {
private Map attributes2grantedAuthoritiesMap = null;
private String stringSeparator = ",";
private String[] mappableAttributes = null;
private Map<String, Collection<GrantedAuthority>> attributes2grantedAuthoritiesMap = null;
private String stringSeparator = ",";
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");
}
}
/**
* Preprocess the given map
* @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;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(attributes2grantedAuthoritiesMap, "attributes2grantedAuthoritiesMap must be set");
}
/**
* Convert the given value to a collection of Granted Authorities
*
* @param value
* The value to convert to a GrantedAuthority Collection
* @return Collection containing the GrantedAuthority Collection
*/
private Collection getGrantedAuthorityCollection(Object value) {
Collection result = new ArrayList();
addGrantedAuthorityCollection(result,value);
return result;
}
/**
* Map the given array of attributes to Spring Security GrantedAuthorities.
*/
public List<GrantedAuthority> getGrantedAuthorities(Collection<String> attributes) {
ArrayList<GrantedAuthority> gaList = new ArrayList<GrantedAuthority>();
for (String attribute : attributes) {
Collection<GrantedAuthority> c = attributes2grantedAuthoritiesMap.get(attribute);
if ( c != null ) { gaList.addAll(c); }
}
gaList.trimToSize();
/**
* 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());
}
}
}
return gaList;
}
private void addGrantedAuthorityCollection(Collection result, Collection value) {
Iterator it = value.iterator();
while ( it.hasNext() ) {
addGrantedAuthorityCollection(result,it.next());
}
}
/**
* @return Returns the attributes2grantedAuthoritiesMap.
*/
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) {
for ( int i = 0 ; i < value.length ; i++ ) {
addGrantedAuthorityCollection(result,value[i]);
}
}
try {
mappableAttributes = (String[])this.attributes2grantedAuthoritiesMap.keySet().toArray(new String[]{});
} 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);
while ( st.hasMoreTokens() ) {
String nextToken = st.nextToken();
if ( StringUtils.hasText(nextToken) ) {
result.add(new GrantedAuthorityImpl(nextToken));
}
}
}
/**
* Preprocess the given map to convert all the values to GrantedAuthority collections
*
* @param orgMap The map to process
* @return the processed Map
*/
private Map<String, Collection<GrantedAuthority>> preProcessMap(Map<String, Object> orgMap) {
Map result = new HashMap(orgMap.size());
/**
* Map the given array of attributes to Spring Security GrantedAuthorities.
*/
public GrantedAuthority[] getGrantedAuthorities(String[] attributes) {
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;
}
for(Map.Entry entry : orgMap.entrySet()) {
result.put(entry.getKey(),getGrantedAuthorityCollection(entry.getValue()));
}
return result;
}
/**
* @return Returns the attributes2grantedAuthoritiesMap.
*/
public Map getAttributes2grantedAuthoritiesMap() {
return attributes2grantedAuthoritiesMap;
}
/**
* @param attributes2grantedAuthoritiesMap The attributes2grantedAuthoritiesMap to set.
*/
public void setAttributes2grantedAuthoritiesMap(Map attributes2grantedAuthoritiesMap) {
this.attributes2grantedAuthoritiesMap = attributes2grantedAuthoritiesMap;
}
/**
* Convert the given value to a collection of Granted Authorities
*
* @param value
* The value to convert to a GrantedAuthority Collection
* @return Collection containing the GrantedAuthority Collection
*/
private Collection getGrantedAuthorityCollection(Object value) {
Collection result = new ArrayList();
addGrantedAuthorityCollection(result,value);
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.GrantedAuthorityImpl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
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.
*/
public GrantedAuthority[] getGrantedAuthorities(String[] attributes) {
GrantedAuthority[] result = new GrantedAuthority[attributes.length];
for (int i = 0; i < attributes.length; i++) {
result[i] = getGrantedAuthority(attributes[i]);
public List<GrantedAuthority> getGrantedAuthorities(Collection<String> attributes) {
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(attributes.size());
for (String attribute : attributes) {
result.add(getGrantedAuthority(attribute));
}
return result;
}

View File

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

View File

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

View File

@ -15,6 +15,8 @@
package org.springframework.security.ldap;
import java.util.List;
import org.springframework.security.GrantedAuthority;
import org.springframework.ldap.core.DirContextOperations;
@ -41,5 +43,5 @@ public interface LdapAuthoritiesPopulator {
* @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 javax.naming.directory.SearchControls;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
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
*/
protected Set getAdditionalRoles(DirContextOperations user, String username) {
protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user, String username) {
return null;
}
@ -169,14 +172,14 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
* @param user the user who's authorities are required
* @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();
if (logger.isDebugEnabled()) {
logger.debug("Getting authorities for user " + userDn);
}
Set roles = getGroupMembershipRoles(userDn, username);
Set<GrantedAuthority> roles = getGroupMembershipRoles(userDn, username);
Set extraRoles = getAdditionalRoles(user, username);
@ -188,10 +191,13 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
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();
if (getGroupSearchBase() == null) {

View File

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

View File

@ -16,15 +16,18 @@
package org.springframework.security.providers;
import java.security.Principal;
import java.util.Collections;
import java.util.List;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
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 Luke Taylor
@ -34,22 +37,11 @@ public abstract class AbstractAuthenticationToken implements Authentication {
//~ Instance fields ================================================================================================
private Object details;
private GrantedAuthority[] authorities;
private List<GrantedAuthority> authorities;
private boolean authenticated = false;
//~ 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.
*
@ -60,82 +52,70 @@ public abstract class AbstractAuthenticationToken implements Authentication {
* Authentication#getAuthorities()}<code>null</code> should only be
* presented if the principal has not been authenticated).
*/
public AbstractAuthenticationToken(GrantedAuthority[] authorities) {
public AbstractAuthenticationToken(List<GrantedAuthority> authorities) {
if (authorities != null) {
for (int i = 0; i < authorities.length; i++) {
Assert.notNull(authorities[i],
"Granted authority element " + i + " is null - GrantedAuthority[] cannot contain any null elements");
for (int i = 0; i < authorities.size(); i++) {
if(authorities.get(i) == null) {
throw new IllegalArgumentException("Granted authority element " + i
+ " is null - GrantedAuthority[] cannot contain any null elements");
}
}
this.authorities = Collections.unmodifiableList(authorities);
}
this.authorities = authorities;
}
//~ Methods ========================================================================================================
public boolean equals(Object obj) {
if (obj instanceof AbstractAuthenticationToken) {
AbstractAuthenticationToken test = (AbstractAuthenticationToken) obj;
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();
if (!(obj instanceof AbstractAuthenticationToken)) {
return false;
}
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() {
if (authorities == null) {
return null;
}
GrantedAuthority[] copy = new GrantedAuthority[authorities.length];
System.arraycopy(authorities, 0, copy, 0, authorities.length);
return copy;
public List<GrantedAuthority> getAuthorities() {
return authorities;
}
public Object getDetails() {
@ -146,7 +126,7 @@ public abstract class AbstractAuthenticationToken implements Authentication {
if (this.getPrincipal() instanceof UserDetails) {
return ((UserDetails) this.getPrincipal()).getUsername();
}
if (getPrincipal() instanceof Principal) {
return ((Principal)getPrincipal()).getName();
}
@ -157,12 +137,9 @@ public abstract class AbstractAuthenticationToken implements Authentication {
public int hashCode() {
int code = 31;
// Copy authorities to local variable for performance (SEC-223)
GrantedAuthority[] authorities = this.getAuthorities();
if (authorities != null) {
for (int i = 0; i < authorities.length; i++) {
code ^= authorities[i].hashCode();
for (GrantedAuthority authority : authorities) {
code ^= authority.hashCode();
}
}
@ -205,15 +182,16 @@ public abstract class AbstractAuthenticationToken implements Authentication {
sb.append("Authenticated: ").append(this.isAuthenticated()).append("; ");
sb.append("Details: ").append(this.getDetails()).append("; ");
if (this.getAuthorities() != null) {
if (authorities != null) {
sb.append("Granted Authorities: ");
for (int i = 0; i < this.getAuthorities().length; i++) {
if (i > 0) {
int i = 0;
for (GrantedAuthority authority: authorities) {
if (i++ > 0) {
sb.append(", ");
}
sb.append(this.getAuthorities()[i].toString());
sb.append(authority);
}
} else {
sb.append("Not granted any authorities");

View File

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

View File

@ -15,6 +15,9 @@
package org.springframework.security.providers;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.GrantedAuthority;
@ -51,6 +54,13 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
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>
* 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 authorities
*/
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, GrantedAuthority[] authorities) {
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, List<GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(true); // must use super, as we override
}
//~ Methods ========================================================================================================
public Object getCredentials() {

View File

@ -20,6 +20,8 @@ import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.AbstractAuthenticationToken;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
@ -37,7 +39,11 @@ public class AnonymousAuthenticationToken extends AbstractAuthenticationToken im
//~ Constructors ===================================================================================================
/**
public AnonymousAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) {
this(key, principal, Arrays.asList(authorities));
}
/**
* Constructor.
*
* @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
*/
public AnonymousAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) {
public AnonymousAuthenticationToken(String key, Object principal, List<GrantedAuthority> authorities) {
super(authorities);
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");
}

View File

@ -153,12 +153,12 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() throws Exception {
Assert.notNull(loginConfig, "loginConfig must be set on " + getClass());
Assert.hasLength(loginContextName, "loginContextName must be set on " + getClass());
configureJaas(loginConfig);
Assert.notNull(Configuration.getConfiguration(),
"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 "
@ -190,10 +190,10 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
loginContext.login();
//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) {
authorities.addAll(Arrays.asList(request.getAuthorities()));
authorities.addAll(request.getAuthorities());
}
//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.
JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(),
request.getCredentials(),
(GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]), loginContext);
(GrantedAuthority[]) authorities.toArray(new GrantedAuthority[0]), loginContext);
//Publish the success event
publishSuccessEvent(result);
@ -379,7 +379,7 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
*/
protected void publishSuccessEvent(UsernamePasswordAuthenticationToken token) {
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;
import java.util.List;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
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.ldap.LdapUserDetailsMapper;
import org.springframework.security.userdetails.ldap.UserDetailsContextMapper;
import org.springframework.security.util.AuthorityUtils;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.ldap.NamingException;
import org.springframework.ldap.core.DirContextOperations;
@ -228,7 +231,7 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
try {
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);
@ -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);
}
@ -257,8 +260,8 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
//~ Inner Classes ==================================================================================================
private static class NullAuthoritiesPopulator implements LdapAuthoritiesPopulator {
public GrantedAuthority[] getGrantedAuthorities(DirContextOperations userDetails, String username) {
return new GrantedAuthority[0];
public List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userDetails, String username) {
return AuthorityUtils.NO_AUTHORITIES;
}
}
}

View File

@ -1,9 +1,12 @@
package org.springframework.security.providers.preauth;
import java.util.Arrays;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.userdetails.UserDetails;
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 AuthenticationUserDetailsService preAuthenticatedUserDetailsService = null;
private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
private boolean throwExceptionWhenTokenRejected = false;
private int order = -1; // default: same as non-ordered
@ -63,7 +66,7 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
if (authentication.getPrincipal() == null) {
logger.debug("No pre-authenticated principal found in request.");
if (throwExceptionWhenTokenRejected) {
throw new BadCredentialsException("No pre-authenticated principal found in request.");
}
@ -75,16 +78,17 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
if (throwExceptionWhenTokenRejected) {
throw new BadCredentialsException("No pre-authenticated credentials found in request.");
}
}
return null;
}
UserDetails ud = preAuthenticatedUserDetailsService.loadUserDetails(authentication);
userDetailsChecker.check(ud);
PreAuthenticatedAuthenticationToken result =
new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(), ud.getAuthorities());
new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(),
ud.getAuthorities().toArray(new GrantedAuthority[0]));
result.setDetails(authentication.getDetails());
return result;
@ -114,22 +118,22 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
order = i;
}
/**
* 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
/**
* 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
* null. Defaults to false.
*/
*/
public void setThrowExceptionWhenTokenRejected(boolean throwExceptionWhenTokenRejected) {
this.throwExceptionWhenTokenRejected = throwExceptionWhenTokenRejected;
}
/**
* 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
*/
public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) {
Assert.notNull(userDetailsChecker, "userDetailsChacker cannot be null");
this.userDetailsChecker = userDetailsChecker;
}
public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) {
Assert.notNull(userDetailsChecker, "userDetailsChacker cannot be null");
this.userDetailsChecker = userDetailsChecker;
}
}

View File

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

View File

@ -1,5 +1,7 @@
package org.springframework.security.providers.preauth;
import java.util.List;
import org.springframework.security.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.User;
@ -20,7 +22,7 @@ import org.springframework.util.Assert;
* PreAuthenticatedAuthenticationProvider anyway), and the Granted Authorities
* are retrieved from the details object as returned by
* PreAuthenticatedAuthenticationToken.getDetails().
*
*
* <p>
* The details object as returned by PreAuthenticatedAuthenticationToken.getDetails() must implement the
* {@link GrantedAuthoritiesContainer} interface for this implementation to work.
@ -29,27 +31,27 @@ import org.springframework.util.Assert;
* @since 2.0
*/
public class PreAuthenticatedGrantedAuthoritiesUserDetailsService implements AuthenticationUserDetailsService {
/**
* Get a UserDetails object based on the user name contained in the given
* token, and the GrantedAuthorities as returned by the
* GrantedAuthoritiesContainer implementation as returned by
* the token.getDetails() method.
*/
public final UserDetails loadUserDetails(Authentication token) throws AuthenticationException {
Assert.notNull(token.getDetails());
Assert.isInstanceOf(GrantedAuthoritiesContainer.class, token.getDetails());
GrantedAuthority[] authorities = ((GrantedAuthoritiesContainer) token.getDetails()).getGrantedAuthorities();
UserDetails ud = createuserDetails(token, authorities);
return ud;
}
/**
* Creates the final <tt>UserDetails</tt> object. Can be overridden to customize the contents.
*
* @param token the authentication request token
* @param authorities the pre-authenticated authorities.
*/
protected UserDetails createuserDetails(Authentication token, GrantedAuthority[] authorities) {
return new User(token.getName(), "N/A", true, true, true, true, authorities);
}
/**
* Get a UserDetails object based on the user name contained in the given
* token, and the GrantedAuthorities as returned by the
* GrantedAuthoritiesContainer implementation as returned by
* the token.getDetails() method.
*/
public final UserDetails loadUserDetails(Authentication token) throws AuthenticationException {
Assert.notNull(token.getDetails());
Assert.isInstanceOf(GrantedAuthoritiesContainer.class, token.getDetails());
List<GrantedAuthority> authorities = ((GrantedAuthoritiesContainer) token.getDetails()).getGrantedAuthorities();
UserDetails ud = createuserDetails(token, authorities);
return ud;
}
/**
* Creates the final <tt>UserDetails</tt> object. Can be overridden to customize the contents.
*
* @param token the authentication request token
* @param authorities the pre-authenticated authorities.
*/
protected UserDetails createuserDetails(Authentication token, List<GrantedAuthority> 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;
import java.util.List;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
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
* protect it. Instead, the bean uses the configured <code>AuthenticationManager</code> to resolve an authentication
* request.</p>
* Server-side processor of a remote authentication 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
* @version $Id$
@ -46,11 +49,13 @@ public class RemoteAuthenticationManagerImpl implements RemoteAuthenticationMana
}
public GrantedAuthority[] attemptAuthentication(String username, String password)
throws RemoteAuthenticationException {
throws RemoteAuthenticationException {
UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken(username, password);
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) {
throw new RemoteAuthenticationException(authEx.getMessage());
}

View File

@ -16,6 +16,8 @@
package org.springframework.security.providers.rememberme;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.AbstractAuthenticationToken;
@ -37,6 +39,10 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken i
//~ Constructors ===================================================================================================
public RememberMeAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) {
this(key, principal, Arrays.asList(authorities));
}
/**
* Constructor.
*
@ -46,7 +52,7 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken i
*
* @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);
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;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.springframework.beans.factory.InitializingBean;
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
* ConfigAttribute#getAttribute()} is prefixed with <Code>RUN_AS_</code>. If found, it generates a new {@link
* RunAsUserToken} containing the same principal, credentials and granted authorities as the original {@link
* Authentication} object, along with {@link GrantedAuthorityImpl}s for each <code>RUN_AS_</code> indicated. The
* created <code>GrantedAuthorityImpl</code>s will be prefixed with a special prefix indicating that it is a role
* (default prefix value is <code>ROLE_</code>), and then the remainder of the <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>.
* Basic concrete implementation of a {@link RunAsManager}.
* <p>
* Is activated if any {@link ConfigAttribute#getAttribute()} is prefixed with <Code>RUN_AS_</code>.
* If found, it generates a new {@link RunAsUserToken} containing the same principal, credentials and granted
* authorities as the original {@link Authentication} object, along with {@link GrantedAuthorityImpl}s for each
* <code>RUN_AS_</code> indicated. The created <code>GrantedAuthorityImpl</code>s will be prefixed with a special
* prefix indicating that it is a role (default prefix value is <code>ROLE_</code>), and then the remainder of the
* <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>
* 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
* potential issues with using an empty role prefix since different categories of {@link
* org.springframework.security.ConfigAttribute} can not be properly discerned based on the prefix, with possible consequences
* when performing voting and other actions. However, this option may be of some use when using preexisting role names
* without a prefix, and no ability exists to prefix them with a role prefix on reading them in, such as provided for
* example in {@link org.springframework.security.userdetails.jdbc.JdbcDaoImpl}.
* potential issues with using an empty role prefix since different categories of {@link ConfigAttribute} can not be
* properly discerned based on the prefix, with possible consequences when performing voting and other actions.
* However, this option may be of some use when using preexisting role names without a prefix, and no ability exists to
* prefix them with a role prefix on reading them in, such as provided for example in
* {@link org.springframework.security.userdetails.jdbc.JdbcDaoImpl}.
*
* @author Ben Alex
* @author colin sampaleanu
@ -62,12 +63,11 @@ public class RunAsManagerImpl implements RunAsManager, InitializingBean {
}
public Authentication buildRunAs(Authentication authentication, Object object, List<ConfigAttribute> config) {
List newAuthorities = new Vector();
List<GrantedAuthority> newAuthorities = new ArrayList();
for(ConfigAttribute attribute : config) {
if (this.supports(attribute)) {
GrantedAuthorityImpl extraAuthority = new GrantedAuthorityImpl(getRolePrefix()
+ attribute.getAttribute());
GrantedAuthority extraAuthority = new GrantedAuthorityImpl(getRolePrefix() + attribute.getAttribute());
newAuthorities.add(extraAuthority);
}
}
@ -76,16 +76,14 @@ public class RunAsManagerImpl implements RunAsManager, InitializingBean {
return null;
}
// Add existing authorities
newAuthorities.addAll(authentication.getAuthorities());
for (int i = 0; i < authentication.getAuthorities().length; i++) {
newAuthorities.add(authentication.getAuthorities()[i]);
}
GrantedAuthority[] resultType = {new GrantedAuthorityImpl("holder")};
GrantedAuthority[] newAuthoritiesAsArray = (GrantedAuthority[]) newAuthorities.toArray(resultType);
// GrantedAuthority[] resultType = {new GrantedAuthorityImpl("holder")};
GrantedAuthority[] newAuthoritiesAsArray = newAuthorities.toArray(new GrantedAuthority[0]);
return new RunAsUserToken(this.key, authentication.getPrincipal(), authentication.getCredentials(),
newAuthoritiesAsArray, authentication.getClass());
newAuthoritiesAsArray, authentication.getClass());
}
public String getKey() {

View File

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

View File

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

View File

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

View File

@ -1,6 +1,8 @@
package org.springframework.security.ui.preauth.j2ee;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
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
* 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)}.
* <p>
*
*
*
*
* @author Luke Taylor
* @since 2.0
*/
public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extends AuthenticationDetailsSourceImpl {
protected final Log logger = LogFactory.getLog(getClass());
protected String[] j2eeMappableRoles;
protected Attributes2GrantedAuthoritiesMapper j2eeUserRoles2GrantedAuthoritiesMapper =
protected Attributes2GrantedAuthoritiesMapper j2eeUserRoles2GrantedAuthoritiesMapper =
new SimpleAttributes2GrantedAuthoritiesMapper();
public AbstractPreAuthenticatedAuthenticationDetailsSource() {
@ -49,29 +51,28 @@ public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extend
*/
public Object buildDetails(Object context) {
Object result = super.buildDetails(context);
if (result instanceof MutableGrantedAuthoritiesContainer) {
String[] j2eeUserRoles = getUserRoles(context, j2eeMappableRoles);
GrantedAuthority[] userGas = j2eeUserRoles2GrantedAuthoritiesMapper.getGrantedAuthorities(j2eeUserRoles);
Collection<String> j2eeUserRoles = getUserRoles(context, j2eeMappableRoles);
List<GrantedAuthority> userGas = j2eeUserRoles2GrantedAuthoritiesMapper.getGrantedAuthorities(j2eeUserRoles);
if (logger.isDebugEnabled()) {
logger.debug("J2EE user roles [" + Arrays.asList(j2eeUserRoles) + "] mapped to Granted Authorities: ["
+ Arrays.asList(userGas) + "]");
logger.debug("J2EE roles [" + j2eeUserRoles + "] mapped to Granted Authorities: [" + userGas + "]");
}
((MutableGrantedAuthoritiesContainer) result).setGrantedAuthorities(userGas);
}
return result;
}
/**
* Allows the roles of the current user to be determined from the context object
*
*
* @param context the context object (an HttpRequest, PortletRequest etc)
* @param mappableRoles the possible roles as determined by the MappableAttributesRetriever
* @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
@ -88,4 +89,4 @@ public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extend
public void setUserRoles2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) {
j2eeUserRoles2GrantedAuthoritiesMapper = mapper;
}
}
}

View File

@ -4,6 +4,7 @@ import org.springframework.security.ui.preauth.PreAuthenticatedGrantedAuthoritie
import org.springframework.security.authoritymapping.SimpleAttributes2GrantedAuthoritiesMapper;
import java.util.ArrayList;
import java.util.Collection;
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
* {@link HttpServletRequest#isUserInRole(String)}) into GrantedAuthoritys and stores these in the authentication
* details object (.
* details object (.
*
* @author Ruud Senden
* @since 2.0
@ -24,7 +25,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs
*/
public J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource() {
super.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class);
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.
*
* @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.
*/
protected String[] getUserRoles(Object context, String[] mappableRoles) {
protected Collection<String> getUserRoles(Object context, String[] mappableRoles) {
ArrayList j2eeUserRolesList = new ArrayList();
for (int i = 0; i < mappableRoles.length; i++) {
@ -43,7 +44,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs
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;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -17,70 +18,70 @@ import org.springframework.util.Assert;
* This AuthenticationDetailsSource implementation, when configured with a MutableGrantedAuthoritiesContainer,
* will set the pre-authenticated granted authorities based on the WebSphere groups for the current WebSphere
* user, mapped using the configured Attributes2GrantedAuthoritiesMapper.
*
*
* By default, this class is configured to build instances of the
* PreAuthenticatedGrantedAuthoritiesAuthenticationDetails class.
*
*
* @author Ruud Senden
*/
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
* class to be used.
*/
public WebSpherePreAuthenticatedAuthenticationDetailsSource() {
super.setClazz(PreAuthenticatedGrantedAuthoritiesAuthenticationDetails.class);
}
/**
* Public constructor which overrides the default AuthenticationDetails
* class to be used.
*/
public WebSpherePreAuthenticatedAuthenticationDetailsSource() {
super.setClazz(PreAuthenticatedGrantedAuthoritiesAuthenticationDetails.class);
}
/**
* Check that all required properties have been set.
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(webSphereGroups2GrantedAuthoritiesMapper, "WebSphere groups to granted authorities mapper not set");
}
/**
* Check that all required properties have been set.
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(webSphereGroups2GrantedAuthoritiesMapper, "WebSphere groups to granted authorities mapper not set");
}
/**
* Build the authentication details object. If the speficied authentication
* details class implements the PreAuthenticatedGrantedAuthoritiesSetter, a
* list of pre-authenticated Granted Authorities will be set based on the
* WebSphere groups for the current user.
*
* @see org.springframework.security.ui.AuthenticationDetailsSource#buildDetails(Object)
*/
public Object buildDetails(Object context) {
Object result = super.buildDetails(context);
if (result instanceof MutableGrantedAuthoritiesContainer) {
((MutableGrantedAuthoritiesContainer) result)
.setGrantedAuthorities(getWebSphereGroupsBasedGrantedAuthorities());
}
return result;
}
/**
* Build the authentication details object. If the specified authentication
* details class implements the PreAuthenticatedGrantedAuthoritiesSetter, a
* list of pre-authenticated Granted Authorities will be set based on the
* WebSphere groups for the current user.
*
* @see org.springframework.security.ui.AuthenticationDetailsSource#buildDetails(Object)
*/
public Object buildDetails(Object context) {
Object result = super.buildDetails(context);
if (result instanceof MutableGrantedAuthoritiesContainer) {
((MutableGrantedAuthoritiesContainer) result)
.setGrantedAuthorities(getWebSphereGroupsBasedGrantedAuthorities());
}
return result;
}
/**
* Get a list of Granted Authorities based on the current user's WebSphere groups.
*
* @return GrantedAuthority[] mapped from the user's WebSphere groups.
*/
private GrantedAuthority[] getWebSphereGroupsBasedGrantedAuthorities() {
String[] webSphereGroups = WASSecurityHelper.getGroupsForCurrentUser();
GrantedAuthority[] userGas = webSphereGroups2GrantedAuthoritiesMapper.getGrantedAuthorities(webSphereGroups);
if (LOG.isDebugEnabled()) {
LOG.debug("WebSphere groups: " + Arrays.asList(webSphereGroups) + " mapped to Granted Authorities: "
+ Arrays.asList(userGas));
}
return userGas;
}
/**
* Get a list of Granted Authorities based on the current user's WebSphere groups.
*
* @return GrantedAuthority[] mapped from the user's WebSphere groups.
*/
private List<GrantedAuthority> getWebSphereGroupsBasedGrantedAuthorities() {
List<String> webSphereGroups = Arrays.asList(WASSecurityHelper.getGroupsForCurrentUser());
List<GrantedAuthority> userGas = webSphereGroups2GrantedAuthoritiesMapper.getGrantedAuthorities(webSphereGroups);
if (logger.isDebugEnabled()) {
logger.debug("WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: "
+ Arrays.asList(userGas));
}
return userGas;
}
/**
* @param mapper
* The Attributes2GrantedAuthoritiesMapper to use
*/
public void setWebSphereGroups2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) {
webSphereGroups2GrantedAuthoritiesMapper = mapper;
}
/**
* @param mapper
* The Attributes2GrantedAuthoritiesMapper to use
*/
public void setWebSphereGroups2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) {
webSphereGroups2GrantedAuthoritiesMapper = mapper;
}
}

View File

@ -240,7 +240,7 @@ public class SwitchUserProcessingFilter extends SpringSecurityFilter implements
GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_PREVIOUS_ADMINISTRATOR, currentAuth);
// get the original authorities
List orig = Arrays.asList(targetUser.getAuthorities());
List orig = targetUser.getAuthorities();
// Allow subclasses to change the authorities to be granted
if (switchUserAuthorityChanger != null) {
@ -251,11 +251,8 @@ public class SwitchUserProcessingFilter extends SpringSecurityFilter implements
List newAuths = new ArrayList(orig);
newAuths.add(switchAuthority);
GrantedAuthority[] authorities =
(GrantedAuthority[]) newAuths.toArray(new GrantedAuthority[newAuths.size()]);
// create the new authentication token
targetUserRequest = new UsernamePasswordAuthenticationToken(targetUser, targetUser.getPassword(), authorities);
targetUserRequest = new UsernamePasswordAuthenticationToken(targetUser, targetUser.getPassword(), newAuths);
// set details
targetUserRequest.setDetails(authenticationDetailsSource.buildDetails(request));
@ -304,7 +301,7 @@ public class SwitchUserProcessingFilter extends SpringSecurityFilter implements
logger.debug("Switch User failed", failed);
if (switchFailureUrl != null) {
sendRedirect(request, response, switchFailureUrl);
sendRedirect(request, response, switchFailureUrl);
} else {
response.getWriter().print("Switch user failed: " + failed.getMessage());
response.flushBuffer();
@ -330,12 +327,12 @@ public class SwitchUserProcessingFilter extends SpringSecurityFilter implements
Authentication original = null;
// 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
if (authorities[i] instanceof SwitchUserGrantedAuthority) {
original = ((SwitchUserGrantedAuthority) authorities[i]).getSource();
if (auth instanceof SwitchUserGrantedAuthority) {
original = ((SwitchUserGrantedAuthority) auth).getSource();
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;
import java.util.List;
import org.springframework.security.GrantedAuthority;
/**
@ -36,7 +38,7 @@ public interface GroupManager {
* @param groupName the name for the new 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.
@ -69,7 +71,7 @@ public interface GroupManager {
/**
* 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.

View File

@ -15,13 +15,16 @@
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.TreeSet;
import org.springframework.security.GrantedAuthority;
import org.springframework.util.Assert;
/**
* 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,
@ -36,7 +39,7 @@ public class User implements UserDetails {
private static final long serialVersionUID = 1L;
private String password;
private String username;
private GrantedAuthority[] authorities;
private List<GrantedAuthority> authorities;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
@ -45,58 +48,12 @@ public class User implements UserDetails {
//~ Constructors ===================================================================================================
/**
* 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 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)
* @deprecated
*/
public User(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, GrantedAuthority[] authorities)
throws IllegalArgumentException {
this(username, password, enabled, accountNonExpired, credentialsNonExpired, true, authorities);
boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities) {
this(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
authorities == null ? null : Arrays.asList(authorities));
}
/**
@ -123,8 +80,8 @@ public class User implements UserDetails {
* <code>GrantedAuthority[]</code> array
*/
public User(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities)
throws IllegalArgumentException {
boolean credentialsNonExpired, boolean accountNonLocked, List<GrantedAuthority> authorities) {
if (((username == null) || "".equals(username)) || (password == null)) {
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
// authorities
if (user.getAuthorities().length != this.getAuthorities().length) {
if (!authorities.equals(user.authorities)) {
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
return (this.getPassword().equals(user.getPassword()) && this.getUsername().equals(user.getUsername())
&& (this.isAccountNonExpired() == user.isAccountNonExpired())
@ -167,7 +118,7 @@ public class User implements UserDetails {
&& (this.isEnabled() == user.isEnabled()));
}
public GrantedAuthority[] getAuthorities() {
public List<GrantedAuthority> getAuthorities() {
return authorities;
}
@ -183,8 +134,8 @@ public class User implements UserDetails {
int code = 9792;
if (this.getAuthorities() != null) {
for (int i = 0; i < this.getAuthorities().length; i++) {
code = code * (this.getAuthorities()[i].hashCode() % 7);
for (int i = 0; i < this.getAuthorities().size(); i++) {
code = code * (authorities.get(i).hashCode() % 7);
}
}
@ -231,17 +182,20 @@ public class User implements UserDetails {
return enabled;
}
protected void setAuthorities(GrantedAuthority[] authorities) {
protected void setAuthorities(List<GrantedAuthority> authorities) {
Assert.notNull(authorities, "Cannot pass a null GrantedAuthority array");
// Ensure array iteration order is predictable (as per UserDetails.getAuthorities() contract and SEC-xxx)
SortedSet sorter = new TreeSet();
for (int i = 0; i < authorities.length; i++) {
Assert.notNull(authorities[i],
"Granted authority element " + i + " is null - GrantedAuthority[] cannot contain any null elements");
sorter.add(authorities[i]);
SortedSet<GrantedAuthority> sorter = new TreeSet<GrantedAuthority>();
for (GrantedAuthority grantedAuthority : authorities) {
Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");
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() {
@ -257,12 +211,12 @@ public class User implements UserDetails {
if (this.getAuthorities() != null) {
sb.append("Granted Authorities: ");
for (int i = 0; i < this.getAuthorities().length; i++) {
for (int i = 0; i < authorities.size(); i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(this.getAuthorities()[i].toString());
sb.append(authorities.get(i));
}
} else {
sb.append("Not granted any authorities");

View File

@ -19,6 +19,7 @@ import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
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>)
*/
GrantedAuthority[] getAuthorities();
List<GrantedAuthority> getAuthorities();
/**
* 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;
import java.util.List;
import org.springframework.security.GrantedAuthority;
/**
@ -37,6 +39,6 @@ public interface RoleHierarchy {
* @param authorities - Array of the directly 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();
}
public GrantedAuthority[] getReachableGrantedAuthorities(GrantedAuthority[] authorities) {
if (authorities == null || authorities.length == 0) {
public List<GrantedAuthority> getReachableGrantedAuthorities(List<GrantedAuthority> authorities) {
if (authorities == null || authorities.isEmpty()) {
return null;
}
Set reachableRoles = new HashSet();
Set<GrantedAuthority> reachableRoles = new HashSet<GrantedAuthority>();
for (int i = 0; i < authorities.length; i++) {
reachableRoles.add(authorities[i]);
Set additionalReachableRoles = (Set) rolesReachableInOneOrMoreStepsMap.get(authorities[i]);
for (GrantedAuthority authority : authorities) {
reachableRoles.add(authority);
Set additionalReachableRoles = (Set) rolesReachableInOneOrMoreStepsMap.get(authority);
if (additionalReachableRoles != null) {
reachableRoles.addAll(additionalReachableRoles);
}
}
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.");
}
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;
import java.util.List;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetails;
@ -46,7 +48,7 @@ public class UserDetailsWrapper implements UserDetails {
return userDetails.isAccountNonLocked();
}
public GrantedAuthority[] getAuthorities() {
public List<GrantedAuthority> 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) {
validateUserDetails(user);
getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.setBoolean(3, user.isEnabled());
}
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.setBoolean(3, user.isEnabled());
}
});
insertUserAuthorities(user);
@ -148,11 +148,11 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
public void updateUser(final UserDetails user) {
validateUserDetails(user);
getJdbcTemplate().update(updateUserSql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, user.getPassword());
ps.setBoolean(2, user.isEnabled());
ps.setString(3, user.getUsername());
}
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, user.getPassword());
ps.setBoolean(2, user.isEnabled());
ps.setString(3, user.getUsername());
}
});
deleteUserAuthorities(user.getUsername());
@ -162,9 +162,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
}
private void insertUserAuthorities(UserDetails user) {
for (int i=0; i < user.getAuthorities().length; i++) {
getJdbcTemplate().update(createAuthoritySql,
new Object[] {user.getUsername(), user.getAuthorities()[i].getAuthority()});
for (int i=0; i < user.getAuthorities().size(); i++) {
getJdbcTemplate().update(createAuthoritySql,
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});
userCache.removeUserFromCache(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 {
@ -218,7 +218,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
}
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) {
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]);
}
public void createGroup(final String groupName, final GrantedAuthority[] authorities) {
public void createGroup(final String groupName, final List<GrantedAuthority> authorities) {
Assert.hasText(groupName);
Assert.notNull(authorities);
logger.debug("Creating new group '" + groupName + "' with authorities " +
AuthorityUtils.authorityArrayToSet(authorities));
AuthorityUtils.authorityArrayToSet(authorities));
getJdbcTemplate().update(insertGroupSql, new String[] {groupName});
final int groupId = findGroupId(groupName);
for (int i=0; i < authorities.length; i++) {
final String authority = authorities[i].getAuthority();
getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, groupId);
ps.setString(2, authority);
}
});
for (int i=0; i < authorities.size(); i++) {
final String authority = authorities.get(i).getAuthority();
getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, groupId);
ps.setString(2, authority);
}
});
}
}
@ -266,9 +266,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName);
PreparedStatementSetter groupIdPSS = new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
}
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
}
};
getJdbcTemplate().update(deleteGroupMembersSql, groupIdPSS);
getJdbcTemplate().update(deleteGroupAuthoritiesSql, groupIdPSS);
@ -290,10 +290,10 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName);
getJdbcTemplate().update(insertGroupMemberSql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
ps.setString(2, username);
}
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
ps.setString(2, username);
}
});
userCache.removeUserFromCache(username);
@ -307,29 +307,29 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName);
getJdbcTemplate().update(deleteGroupMemberSql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
ps.setString(2, username);
}
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
ps.setString(2, username);
}
});
userCache.removeUserFromCache(username);
}
public GrantedAuthority[] findGroupAuthorities(String groupName) {
public List<GrantedAuthority> findGroupAuthorities(String groupName) {
logger.debug("Loading authorities for group '" + 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) {
@ -338,13 +338,13 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
Assert.notNull(authority);
final int id = findGroupId(groupName);
getJdbcTemplate().update(deleteGroupAuthoritySql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
ps.setString(2, authority.getAuthority());
}
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
ps.setString(2, authority.getAuthority());
}
});
}
@ -355,15 +355,15 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName);
getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
ps.setString(2, authority.getAuthority());
}
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
ps.setString(2, authority.getAuthority());
}
});
}
private int findGroupId(String group) {
return getJdbcTemplate().queryForInt(findGroupIdSql, new Object[] {group});
return getJdbcTemplate().queryForInt(findGroupIdSql, new Object[] {group});
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
@ -425,12 +425,12 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
validateAuthorities(user.getAuthorities());
}
private void validateAuthorities(GrantedAuthority[] authorities) {
private void validateAuthorities(List<GrantedAuthority> authorities) {
Assert.notNull(authorities, "Authorities list must not be null");
for (int i=0; i < authorities.length; i++) {
Assert.notNull(authorities[i], "Authorities list contains a null entry");
Assert.hasText(authorities[i].getAuthority(), "getAuthority() method must return a non-empty string");
for (int i=0; i < authorities.size(); i++) {
Assert.notNull(authorities.get(i), "Authorities list contains a null entry");
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;
import java.util.List;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.GrantedAuthority;
import org.springframework.ldap.core.DirContextOperations;
@ -27,7 +29,7 @@ import org.springframework.util.Assert;
*/
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);
p.setUsername(username);

View File

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

View File

@ -60,13 +60,10 @@ import java.util.ListIterator;
* <p>
* 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.
* </p>
* <p>
* 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
* LDAP authentication provider setup.
* </p>
*
*
* @author Luke Taylor
* @since 2.0
@ -127,7 +124,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
DistinguishedName dn = usernameMapper.buildDn(username);
GrantedAuthority[] authorities = getUserAuthorities(dn, username);
List<GrantedAuthority> authorities = getUserAuthorities(dn, username);
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.
* @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() {
public NamingEnumeration executeSearch(DirContext ctx) throws NamingException {
DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
@ -222,9 +219,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
new AttributesMapperCallbackHandler(roleMapper);
template.search(se, roleCollector);
List authorities = roleCollector.getList();
return (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]);
return roleCollector.getList();
}
// protected String getRoleFilter(DistinguishedName dn, String username) {
@ -236,9 +231,9 @@ public class LdapUserDetailsManager implements UserDetailsManager {
copyToContext(user, ctx);
DistinguishedName dn = usernameMapper.buildDn(user.getUsername());
// 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);
}
@ -255,7 +250,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
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());
ctx.setUpdateMode(true);
@ -318,19 +313,19 @@ public class LdapUserDetailsManager implements UserDetailsManager {
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);
}
protected void removeAuthorities(DistinguishedName userDn, GrantedAuthority[] authorities) {
protected void removeAuthorities(DistinguishedName userDn, List<GrantedAuthority> authorities) {
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() {
public Object executeWithContext(DirContext ctx) throws NamingException {
for(int i=0; i < authorities.length; i++) {
GrantedAuthority authority = authorities[i];
for(int i=0; i < authorities.size(); i++) {
GrantedAuthority authority = authorities.get(i);
String group = convertAuthorityToGroup(authority);
DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx);
ModificationItem addGroup = new ModificationItem(modType,

View File

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

View File

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

View File

@ -1,5 +1,7 @@
package org.springframework.security.userdetails.ldap;
import java.util.List;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.GrantedAuthority;
import org.springframework.ldap.core.DirContextOperations;
@ -12,7 +14,7 @@ import org.springframework.util.Assert;
*/
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);
p.setUsername(username);

View File

@ -14,6 +14,8 @@
*/
package org.springframework.security.userdetails.ldap;
import java.util.List;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.GrantedAuthority;
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.
* @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.

View File

@ -6,7 +6,10 @@ import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
@ -14,7 +17,7 @@ import java.util.Set;
* @version $Id$
*/
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.
@ -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.
*/
public static boolean userHasAuthority(String authority) {
GrantedAuthority[] authorities = getUserAuthorities();
List<GrantedAuthority> authorities = getUserAuthorities();
for (int i = 0; i < authorities.length; i++) {
if (authority.equals(authorities[i].getAuthority())) {
for (GrantedAuthority grantedAuthority : authorities) {
if (authority.equals(grantedAuthority.getAuthority())) {
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.
*/
private static GrantedAuthority[] getUserAuthorities() {
private static List<GrantedAuthority> getUserAuthorities() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || auth.getAuthorities() == null) {
@ -73,21 +76,21 @@ public abstract class AuthorityUtils {
* Converts an array of GrantedAuthority objects to a Set.
* @return a Set of the Strings obtained from each call to GrantedAuthority.getAuthority()
*/
public static Set authorityArrayToSet(GrantedAuthority[] authorities) {
Set set = new HashSet(authorities.length);
public static Set authorityArrayToSet(List<GrantedAuthority> authorities) {
Set set = new HashSet(authorities.size());
for (int i = 0; i < authorities.length; i++) {
set.add(authorities[i].getAuthority());
for (GrantedAuthority authority: authorities) {
set.add(authority.getAuthority());
}
return set;
}
public static GrantedAuthority[] stringArrayToAuthorityArray(String[] roles) {
GrantedAuthority[] authorities = new GrantedAuthority[roles.length];
public static List<GrantedAuthority> createAuthorityList(String... roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(roles.length);
for (int i=0; i < roles.length; i++) {
authorities[i] = new GrantedAuthorityImpl(roles[i]);
authorities.add(new GrantedAuthorityImpl(roles[i]));
}
return authorities;

View File

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

View File

@ -1,29 +1,32 @@
package org.springframework.security.vote;
import java.util.List;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.hierarchicalroles.RoleHierarchy;
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.
*
*
* @author Luke Taylor
* @since 2.0.4
*/
public class RoleHierarchyVoter extends RoleVoter {
private RoleHierarchy roleHierarchy = null;
public RoleHierarchyVoter(RoleHierarchy roleHierarchy) {
Assert.notNull(roleHierarchy, "RoleHierarchy must not be null");
this.roleHierarchy = roleHierarchy;
Assert.notNull(roleHierarchy, "RoleHierarchy must not be null");
this.roleHierarchy = roleHierarchy;
}
/**
* Calls the <tt>RoleHierarchy</tt> to obtain the complete set of user authorities.
*/
GrantedAuthority[] extractAuthorities(Authentication authentication) {
return roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities());
}
@Override
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) {
int result = ACCESS_ABSTAIN;
Iterator iter = attributes.iterator();
GrantedAuthority[] authorities = extractAuthorities(authentication);
while (iter.hasNext()) {
ConfigAttribute attribute = (ConfigAttribute) iter.next();
List<GrantedAuthority> authorities = extractAuthorities(authentication);
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
result = ACCESS_DENIED;
// Attempt to find a matching granted authority
for (int i = 0; i < authorities.length; i++) {
if (attribute.getAttribute().equals(authorities[i].getAuthority())) {
for (GrantedAuthority authority : authorities) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED;
}
}
@ -115,7 +112,7 @@ public class RoleVoter implements AccessDecisionVoter {
return result;
}
GrantedAuthority[] extractAuthorities(Authentication authentication) {
List<GrantedAuthority> extractAuthorities(Authentication authentication) {
return authentication.getAuthorities();
}
}

View File

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

View File

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

View File

@ -1,232 +1,214 @@
package org.springframework.security.authoritymapping;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import junit.framework.TestCase;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
/**
*
*
* @author Ruud Senden
*/
public class MapBasedAttributes2GrantedAuthoritiesMapperTest extends TestCase {
public class MapBasedAttributes2GrantedAuthoritiesMapperTest {
protected void setUp() throws Exception {
// Set Log4j loglevel to debug to include all logstatements in tests
Logger.getRootLogger().setLevel(Level.DEBUG);
}
protected void setUp() throws Exception {
// Set Log4j loglevel to debug to include all logstatements in tests
Logger.getRootLogger().setLevel(Level.DEBUG);
}
public final void testAfterPropertiesSetNoMap() {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
try {
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);
}
}
@Test(expected=IllegalArgumentException.class)
public void testAfterPropertiesSetNoMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.afterPropertiesSet();
}
public final void testAfterPropertiesSetValidMap() {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = getValidAttributes2GrantedAuthoritiesMap();
mapper.setAttributes2grantedAuthoritiesMap(m);
try {
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);
}
@Test(expected=IllegalArgumentException.class)
public void testAfterPropertiesSetEmptyMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.setAttributes2grantedAuthoritiesMap(new HashMap());
mapper.afterPropertiesSet();
}
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;
}
@Test(expected=IllegalArgumentException.class)
public void testAfterPropertiesSetInvalidKeyTypeMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap();
m.put(new Object(),"ga1");
mapper.setAttributes2grantedAuthoritiesMap(m);
mapper.afterPropertiesSet();
}
private MapBasedAttributes2GrantedAuthoritiesMapper getDefaultMapper() {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.setAttributes2grantedAuthoritiesMap(getValidAttributes2GrantedAuthoritiesMap());
mapper.afterPropertiesSet();
return mapper;
}
@Test(expected=IllegalArgumentException.class)
public void testAfterPropertiesSetInvalidValueTypeMap1() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap();
m.put("role1",new Object());
mapper.setAttributes2grantedAuthoritiesMap(m);
mapper.afterPropertiesSet();
}
private void testGetGrantedAuthorities(Attributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
GrantedAuthority[] result = mapper.getGrantedAuthorities(roles);
Collection resultColl = new ArrayList(result.length);
for (int i = 0; i < result.length; i++) {
resultColl.add(result[i].getAuthority());
}
Collection expectedColl = Arrays.asList(expectedGas);
assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
.containsAll(resultColl)
&& resultColl.containsAll(expectedColl));
}
@Test(expected=IllegalArgumentException.class)
public void testAfterPropertiesSetInvalidValueTypeMap2() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap();
m.put("role1",new Object[]{new String[]{"ga1","ga2"}, new Object()});
mapper.setAttributes2grantedAuthoritiesMap(m);
mapper.afterPropertiesSet();
}
@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.Arrays;
import java.util.Collection;
import java.util.List;
import junit.framework.TestCase;
/**
*
*
* @author TSARDD
* @since 18-okt-2007
*/
public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
public final void testAfterPropertiesSetConvertToUpperAndLowerCase() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
mapper.setConvertAttributeToLowerCase(true);
mapper.setConvertAttributeToUpperCase(true);
try {
mapper.afterPropertiesSet();
fail("Expected exception not thrown");
} catch (IllegalArgumentException expected) {
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testAfterPropertiesSetConvertToUpperAndLowerCase() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
mapper.setConvertAttributeToLowerCase(true);
mapper.setConvertAttributeToUpperCase(true);
try {
mapper.afterPropertiesSet();
fail("Expected exception not thrown");
} catch (IllegalArgumentException expected) {
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testAfterPropertiesSet() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
try {
mapper.afterPropertiesSet();
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testAfterPropertiesSet() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
try {
mapper.afterPropertiesSet();
} catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
}
public final void testGetGrantedAuthoritiesNoConversion() {
String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "Role1", "Role2" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesNoConversion() {
String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "Role1", "Role2" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesToUpperCase() {
String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "ROLE1", "ROLE2" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setConvertAttributeToUpperCase(true);
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesToUpperCase() {
String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "ROLE1", "ROLE2" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setConvertAttributeToUpperCase(true);
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesToLowerCase() {
String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "role1", "role2" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setConvertAttributeToLowerCase(true);
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesToLowerCase() {
String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "role1", "role2" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setConvertAttributeToLowerCase(true);
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesAddPrefixIfAlreadyExisting() {
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_ROLE_Role3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(true);
mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesAddPrefixIfAlreadyExisting() {
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_ROLE_Role3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(true);
mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting1() {
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_Role3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(false);
mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting1() {
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_Role3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(false);
mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting2() {
String[] roles = { "Role1", "Role2", "role_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_role_Role3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(false);
mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting2() {
String[] roles = { "Role1", "Role2", "role_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_role_Role3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(false);
mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesCombination1() {
String[] roles = { "Role1", "Role2", "role_Role3" };
String[] expectedGas = { "ROLE_ROLE1", "ROLE_ROLE2", "ROLE_ROLE3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(false);
mapper.setConvertAttributeToUpperCase(true);
mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
public final void testGetGrantedAuthoritiesCombination1() {
String[] roles = { "Role1", "Role2", "role_Role3" };
String[] expectedGas = { "ROLE_ROLE1", "ROLE_ROLE2", "ROLE_ROLE3" };
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
mapper.setAddPrefixIfAlreadyExisting(false);
mapper.setConvertAttributeToUpperCase(true);
mapper.setAttributePrefix("ROLE_");
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
private void testGetGrantedAuthorities(SimpleAttributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
GrantedAuthority[] result = mapper.getGrantedAuthorities(roles);
Collection resultColl = new ArrayList(result.length);
for (int i = 0; i < result.length; i++) {
resultColl.add(result[i].getAuthority());
}
Collection expectedColl = Arrays.asList(expectedGas);
assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
.containsAll(resultColl)
&& resultColl.containsAll(expectedColl));
}
private void testGetGrantedAuthorities(SimpleAttributes2GrantedAuthoritiesMapper 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 do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
.containsAll(resultColl)
&& resultColl.containsAll(expectedColl));
}
private SimpleAttributes2GrantedAuthoritiesMapper getDefaultMapper() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
mapper.setAttributePrefix("");
mapper.setConvertAttributeToLowerCase(false);
mapper.setConvertAttributeToUpperCase(false);
mapper.setAddPrefixIfAlreadyExisting(false);
return mapper;
}
private SimpleAttributes2GrantedAuthoritiesMapper getDefaultMapper() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
mapper.setAttributePrefix("");
mapper.setConvertAttributeToLowerCase(false);
mapper.setConvertAttributeToUpperCase(false);
mapper.setAddPrefixIfAlreadyExisting(false);
return mapper;
}
}

View File

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

View File

@ -18,11 +18,9 @@ package org.springframework.security.context;
import junit.framework.TestCase;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.MockFilterConfig;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.util.AuthorityUtils;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@ -44,342 +42,316 @@ import javax.servlet.ServletResponse;
* 02:04:47Z benalex $
*/
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) {
super(arg0);
}
//~ Methods ========================================================================================================
//~ 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(
FilterConfig filterConfig, Filter filter, ServletRequest request,
ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filter.init(filterConfig);
filter.doFilter(request, response, filterChain);
filter.destroy();
}
public void testDetectsIncompatibleSessionProperties() throws Exception {
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
public void testDetectsIncompatibleSessionProperties() throws Exception {
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
try {
filter.setAllowSessionCreation(false);
filter.setForceEagerSessionCreation(true);
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
filter.setAllowSessionCreation(false);
filter.setForceEagerSessionCreation(true);
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
filter.setAllowSessionCreation(true);
filter.afterPropertiesSet();
assertTrue(true);
}
filter.setAllowSessionCreation(true);
filter.afterPropertiesSet();
assertTrue(true);
}
public void testDetectsMissingOrInvalidContext() throws Exception {
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
public void testDetectsMissingOrInvalidContext() throws Exception {
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
try {
filter.setContextClass(null);
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
filter.setContextClass(null);
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
filter.setContextClass(Integer.class);
assertEquals(Integer.class, filter.getContextClass());
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
try {
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 {
public void testExceptionWithinFilterChainStillClearsSecurityContextHolder() 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 a Context to store in HttpSession (simulating prior request)
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(sessionPrincipal);
// Build a Context to store in HttpSession (simulating prior request)
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(sessionPrincipal);
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc);
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(sessionPrincipal, null,
new IOException());
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(sessionPrincipal, null,
new IOException());
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Execute filter
try {
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
fail("We should have received the IOException thrown inside the filter chain here");
} catch (IOException ioe) {
assertTrue(true);
}
// Execute filter
try {
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
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",
// 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));
}
}
public void testExistingContextContentsCopiedIntoContextHolderFromSessionAndChangesToContextCopiedBackToSession()
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);
public void testExistingContextContentsCopiedIntoContextHolderFromSessionAndChangesToContextCopiedBackToSession()
throws Exception {
// Build an Authentication object we simulate our Authentication changed
// it to
PrincipalSpringSecurityUserToken updatedPrincipal = new PrincipalSpringSecurityUserToken(
"key", "someone", "password",
new GrantedAuthority[] { new GrantedAuthorityImpl(
"SOME_DIFFERENT_ROLE") }, null);
// Build an Authentication object we simulate came from HttpSession
UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
"someone",
"password",
AuthorityUtils.createAuthorityList("SOME_DIFFERENT_ROLE"));
// Build a Context to store in HttpSession (simulating prior request)
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(sessionPrincipal);
// Build a Context to store in HttpSession (simulating prior request)
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(sessionPrincipal);
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc);
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(sessionPrincipal,
updatedPrincipal, null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(sessionPrincipal,
updatedPrincipal, null);
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
// Obtain new/update Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession().getAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
}
// Obtain new/update Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession().getAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
}
public void testHttpSessionCreatedWhenContextHolderChanges() throws Exception {
// Build an Authentication object we simulate our Authentication changed it to
PrincipalSpringSecurityUserToken updatedPrincipal = new PrincipalSpringSecurityUserToken(
"key", "someone", "password",
new GrantedAuthority[] { new GrantedAuthorityImpl(
"SOME_DIFFERENT_ROLE") }, null);
public void testHttpSessionCreatedWhenContextHolderChanges() throws Exception {
// Build an Authentication object we simulate our Authentication changed it to
UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
"someone",
"password",
AuthorityUtils.createAuthorityList("SOME_ROLE"));
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
// don't call afterPropertiesSet to test case when Spring filter.afterPropertiesSet(); isn't called
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
// don't call afterPropertiesSet to test case when Spring filter.afterPropertiesSet(); isn't called
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Obtain new/updated Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession(false).getAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
}
// Obtain new/updated Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession(false).getAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
}
public void testHttpSessionEagerlyCreatedWhenDirected() throws Exception {
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, null, null);
public void testHttpSessionEagerlyCreatedWhenDirected() throws Exception {
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, null, null);
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.setForceEagerSessionCreation(true); // non-default
filter.afterPropertiesSet();
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.setForceEagerSessionCreation(true); // non-default
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
// Check the session is not null
assertNotNull(request.getSession(false));
}
// Check the session is not null
assertNotNull(request.getSession(false));
}
public void testHttpSessionNotCreatedUnlessContextHolderChanges() throws Exception {
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, null, null);
public void testHttpSessionNotCreatedUnlessContextHolderChanges() throws Exception {
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, null, null);
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
// Check the session is null
assertNull(request.getSession(false));
}
// Check the session is null
assertNull(request.getSession(false));
}
public void testHttpSessionWithNonContextInWellKnownLocationIsOverwritten() throws Exception {
// Build an Authentication object we simulate our Authentication changed
// it to
PrincipalSpringSecurityUserToken updatedPrincipal = new PrincipalSpringSecurityUserToken(
"key", "someone", "password",
new GrantedAuthority[] { new GrantedAuthorityImpl(
"SOME_DIFFERENT_ROLE") }, null);
public void testHttpSessionWithNonContextInWellKnownLocationIsOverwritten() throws Exception {
// Build an Authentication object we simulate our Authentication changed it to
UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
"someone",
"password",
AuthorityUtils.createAuthorityList("SOME_DIFFERENT_ROLE"));
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
"NOT_A_CONTEXT_OBJECT");
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
"NOT_A_CONTEXT_OBJECT");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Obtain new/update Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession().getAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
}
// Obtain new/update Authentication from HttpSession
SecurityContext context = (SecurityContext) request.getSession().getAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
}
public void testConcurrentThreadsLazilyChangeFilterAppliedValueToTrue() throws Exception {
PrincipalSpringSecurityUserToken sessionPrincipal = new PrincipalSpringSecurityUserToken(
"key",
"someone",
"password",
new GrantedAuthority[] { new GrantedAuthorityImpl("SOME_ROLE") },
null);
public void testConcurrentThreadsLazilyChangeFilterAppliedValueToTrue() throws Exception {
// Build a Context to store in HttpSession (simulating prior request)
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(sessionPrincipal);
// Build a Context to store in HttpSession (simulating prior request)
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(sessionPrincipal);
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc);
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
sc);
MockHttpServletResponse response = new MockHttpServletResponse();
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContextClass(SecurityContextImpl.class);
filter.afterPropertiesSet();
for (int i = 0; i < 3; i++) {
ThreadRunner runner = new ThreadRunner(request, response, filter,
new MockFilterChain(sessionPrincipal, null, null));
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 {
private Authentication changeContextHolder;
private Authentication expectedOnContextHolder;
private IOException toThrowDuringChain;
public MockFilterChain(Authentication expectedOnContextHolder,
Authentication changeContextHolder,
IOException toThrowDuringChain) {
this.expectedOnContextHolder = expectedOnContextHolder;
this.changeContextHolder = changeContextHolder;
this.toThrowDuringChain = toThrowDuringChain;
}
public MockFilterChain(Authentication expectedOnContextHolder,
Authentication changeContextHolder,
IOException toThrowDuringChain) {
this.expectedOnContextHolder = expectedOnContextHolder;
this.changeContextHolder = changeContextHolder;
this.toThrowDuringChain = toThrowDuringChain;
}
public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException, ServletException {
if (expectedOnContextHolder != null) {
assertEquals(expectedOnContextHolder, SecurityContextHolder.getContext().getAuthentication());
}
public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException, ServletException {
if (expectedOnContextHolder != null) {
assertEquals(expectedOnContextHolder, SecurityContextHolder.getContext().getAuthentication());
}
if (changeContextHolder != null) {
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(changeContextHolder);
SecurityContextHolder.setContext(sc);
}
if (changeContextHolder != null) {
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(changeContextHolder);
SecurityContextHolder.setContext(sc);
}
if (toThrowDuringChain != null) {
throw toThrowDuringChain;
}
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 {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HttpSessionContextIntegrationFilter filter;
private MockFilterChain chain;
public ThreadRunner(MockHttpServletRequest request,
MockHttpServletResponse response,
HttpSessionContextIntegrationFilter filter,
MockFilterChain chain) {
this.request = request;
this.response = response;
this.filter = filter;
this.chain = chain;
}
public ThreadRunner(MockHttpServletRequest request,
MockHttpServletResponse response,
HttpSessionContextIntegrationFilter filter,
MockFilterChain chain) {
this.request = request;
this.response = response;
this.filter = filter;
this.chain = chain;
}
public void run() {
try {
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
public void run() {
try {
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
// Check the session is not null
assertNotNull(request.getSession(false));
} catch (Exception e) {
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 java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.*;
@ -53,9 +54,9 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=notfound"));
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "notfound");
assertEquals(1, authorities.length);
assertEquals("ROLE_USER", authorities[0].getAuthority());
List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notfound");
assertEquals(1, authorities.size());
assertEquals("ROLE_USER", authorities.get(0).getAuthority());
}
@Test
@ -69,13 +70,13 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
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();
roles.add(authorities[0].toString());
roles.add(authorities[1].toString());
roles.add(authorities.get(0).toString());
roles.add(authorities.get(1).toString());
assertTrue(roles.contains("ROLE_DEVELOPER"));
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"));
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "manager");
List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "manager");
assertEquals("Should have 1 role", 1, authorities.length);
assertEquals("ROLE_MANAGER", authorities[0].getAuthority());
assertEquals("Should have 1 role", 1, authorities.size());
assertEquals("ROLE_MANAGER", authorities.get(0).getAuthority());
}
@Test
@ -101,12 +102,12 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
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);
roles.add(authorities[0].getAuthority());
roles.add(authorities[1].getAuthority());
roles.add(authorities.get(0).getAuthority());
roles.add(authorities.get(1).getAuthority());
assertTrue(roles.contains("ROLE_MANAGER"));
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"));
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);
roles.add(authorities[0].getAuthority());
roles.add(authorities[1].getAuthority());
roles.add(authorities[2].getAuthority());
roles.add(authorities.get(0).getAuthority());
roles.add(authorities.get(1).getAuthority());
roles.add(authorities.get(2).getAuthority());
assertTrue(roles.contains("ROLE_MANAGER"));
assertTrue(roles.contains("ROLE_DEVELOPER"));
assertTrue(roles.contains("ROLE_SUBMANAGER"));
@ -134,15 +135,15 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
@Test
public void testUserDnWithEscapedCharacterParameterReturnsExpectedRoles() {
populator.setGroupRoleAttribute("ou");
populator.setConvertToUpperCase(true);
populator.setConvertToUpperCase(true);
populator.setGroupSearchFilter("(member={0})");
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;
import java.util.List;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.MockUserDetailsService;
import org.springframework.security.GrantedAuthority;
@ -20,9 +22,9 @@ public class UserDetailsServiceLdapAuthoritiesPopulatorTests {
public void delegationToUserDetailsServiceReturnsCorrectRoles() throws Exception {
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("ROLE_USER", auths[0].getAuthority());
assertEquals(1, auths.size());
assertEquals("ROLE_USER", auths.get(0).getAuthority());
}
}

View File

@ -15,10 +15,17 @@
package org.springframework.security.providers;
import static org.junit.Assert.*;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.util.AuthorityUtils;
/**
@ -27,49 +34,28 @@ import org.springframework.security.GrantedAuthorityImpl;
* @author Ben Alex
* @version $Id$
*/
public class AbstractAuthenticationTokenTests extends TestCase {
public class AbstractAuthenticationTokenTests {
//~ Instance fields ================================================================================================
private GrantedAuthority[] authorities = null;
//~ Constructors ===================================================================================================
public AbstractAuthenticationTokenTests() {
super();
}
public AbstractAuthenticationTokenTests(String arg0) {
super(arg0);
}
private List<GrantedAuthority> authorities = null;
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(AbstractAuthenticationTokenTests.class);
}
@Before
public final void setUp() throws Exception {
super.setUp();
authorities = new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")};
authorities = AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO");
}
@Test(expected=UnsupportedOperationException.class)
public void testAuthoritiesAreImmutable() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
GrantedAuthority[] gotAuthorities = token.getAuthorities();
List<GrantedAuthority> gotAuthorities = token.getAuthorities();
assertNotSame(authorities, gotAuthorities);
gotAuthorities[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"));
gotAuthorities.set(0, new GrantedAuthorityImpl("ROLE_SUPER_USER"));
}
@Test
public void testGetters() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertEquals("Test", token.getPrincipal());
@ -77,10 +63,11 @@ public class AbstractAuthenticationTokenTests extends TestCase {
assertEquals("Test", token.getName());
}
@Test
public void testHashCode() throws Exception {
MockAuthenticationImpl token1 = 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());
assertTrue(token1.hashCode() != token3.hashCode());
@ -89,6 +76,7 @@ public class AbstractAuthenticationTokenTests extends TestCase {
assertTrue(token1.hashCode() != token2.hashCode());
}
@Test
public void testObjectsEquals() throws Exception {
MockAuthenticationImpl token1 = 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);
assertTrue(!token1.equals(token4));
MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test", "Password",
new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO_CHANGED")
});
MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO_CHANGED"));
assertTrue(!token1.equals(token5));
MockAuthenticationImpl token6 = new MockAuthenticationImpl("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE")});
MockAuthenticationImpl token6 = new MockAuthenticationImpl("Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE"));
assertTrue(!token1.equals(token6));
MockAuthenticationImpl token7 = new MockAuthenticationImpl("Test", "Password", null);
@ -117,6 +101,7 @@ public class AbstractAuthenticationTokenTests extends TestCase {
assertTrue(!token1.equals(new Integer(100)));
}
@Test
public void testSetAuthenticated() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertTrue(!token.isAuthenticated());
@ -124,11 +109,13 @@ public class AbstractAuthenticationTokenTests extends TestCase {
assertTrue(token.isAuthenticated());
}
@Test
public void testToStringWithAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertTrue(token.toString().lastIndexOf("ROLE_TWO") != -1);
}
@Test
public void testToStringWithNullAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", null);
assertTrue(token.toString().lastIndexOf("Not granted any authorities") != -1);
@ -140,7 +127,7 @@ public class AbstractAuthenticationTokenTests extends TestCase {
private Object credentials;
private Object principal;
public MockAuthenticationImpl(Object principal, Object credentials, GrantedAuthority[] authorities) {
public MockAuthenticationImpl(Object principal, Object credentials, List<GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
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.NullConcurrentSessionController;
import org.springframework.security.concurrent.ConcurrentLoginException;
import org.springframework.security.util.AuthorityUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
@ -55,8 +57,7 @@ public class ProviderManagerTests {
@Test
public void authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject() throws Exception {
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password","ROLE_ONE","ROLE_TWO");
ProviderManager mgr = makeProviderManager();
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
@ -70,15 +71,12 @@ public class ProviderManagerTests {
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
assertEquals("Test", castResult.getPrincipal());
assertEquals("Password", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
assertEquals(AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO"), castResult.getAuthorities());
}
@Test
public void authenticationSuccessWhenFirstProviderReturnsNullButSecondAuthenticates() {
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password","ROLE_ONE","ROLE_TWO");
ProviderManager mgr = makeProviderManagerWithMockProviderWhichReturnsNullInList();
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
@ -91,8 +89,8 @@ public class ProviderManagerTests {
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
assertEquals("Test", castResult.getPrincipal());
assertEquals("Password", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
}
@Test
@ -193,7 +191,7 @@ public class ProviderManagerTests {
}
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 {
@ -221,7 +219,7 @@ public class ProviderManagerTests {
return mgr;
}
//~ Inner Classes ==================================================================================================
private class MockProvider implements AuthenticationProvider {

View File

@ -18,9 +18,6 @@ package org.springframework.security.providers;
import junit.framework.TestCase;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
/**
* Tests {@link TestingAuthenticationProvider}.
@ -29,41 +26,19 @@ import org.springframework.security.GrantedAuthorityImpl;
* @version $Id$
*/
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() {
TestingAuthenticationProvider provider = new TestingAuthenticationProvider();
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password","ROLE_ONE","ROLE_TWO");
Authentication result = provider.authenticate(token);
if (!(result instanceof TestingAuthenticationToken)) {
fail("Should have returned instance of TestingAuthenticationToken");
}
assertTrue(result instanceof TestingAuthenticationToken);
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
assertEquals("Test", castResult.getPrincipal());
assertEquals("Password", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
}
public void testSupports() {

View File

@ -19,6 +19,7 @@ import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.util.AuthorityUtils;
/**
@ -49,9 +50,9 @@ public class UsernamePasswordAuthenticationTokenTests extends TestCase {
}
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());
// 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")});
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority());
assertEquals("ROLE_ONE", token.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities().get(1).getAuthority());
}
public void testNoArgConstructorDoesntExist() {

View File

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

View File

@ -150,8 +150,7 @@ public class AnonymousProcessingFilterTests extends TestCase {
assertEquals(originalAuth, SecurityContextHolder.getContext().getAuthentication());
}
public void testOperationWhenNoAuthenticationInSecurityContextHolder()
throws Exception {
public void testOperationWhenNoAuthenticationInSecurityContextHolder() throws Exception {
UserAttribute user = new UserAttribute();
user.setPassword("anonymousUsername");
user.addAuthority(new GrantedAuthorityImpl("ROLE_ANONYMOUS"));
@ -169,7 +168,7 @@ public class AnonymousProcessingFilterTests extends TestCase {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
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
// Now test operation if we have removeAfterRequest = true

View File

@ -69,18 +69,18 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
public void testReceivedBadCredentialsWhenCredentialsNotProvided() {
// Test related to SEC-434
// Test related to SEC-434
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(new MockAuthenticationDaoUserrod());
provider.setUserCache(new MockUserCache());
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null);
try {
provider.authenticate(authenticationToken);
fail("Expected BadCredenialsException");
} catch (BadCredentialsException expected) {
assertTrue(true);
}
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null);
try {
provider.authenticate(authenticationToken);
fail("Expected BadCredenialsException");
} catch (BadCredentialsException expected) {
assertTrue(true);
}
}
public void testAuthenticateFailsIfAccountExpired() {
@ -263,8 +263,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertEquals(User.class, castResult.getPrincipal().getClass());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
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
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
}
public void testAuthenticatesWithForcePrincipalAsString() {

View File

@ -15,33 +15,30 @@
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.security.Security;
import java.util.Arrays;
import java.util.List;
import javax.security.auth.login.LoginContext;
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
@ -155,14 +152,11 @@ public class JaasAuthenticationProviderTests extends TestCase {
assertNotNull(jaasProvider.getLoginConfig());
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_TEST2", list.contains(new GrantedAuthorityImpl("ROLE_TEST2")));
assertTrue("GrantedAuthorities should contain ROLE_1", list.contains(role1));
assertTrue("GrantedAuthorities should contain ROLE_2", list.contains(role2));
boolean foundit = false;
@ -179,10 +173,10 @@ public class JaasAuthenticationProviderTests extends TestCase {
assertTrue("Could not find a JaasGrantedAuthority", foundit);
assertNotNull("Success event not fired", eventCheck.successEvent);
assertEquals("Auth objects are not equal", auth, eventCheck.successEvent.getAuthentication());
assertNotNull("Success event should be fired", eventCheck.successEvent);
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 {
@ -222,12 +216,12 @@ public class JaasAuthenticationProviderTests extends TestCase {
}
public void testNullDefaultAuthorities() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password", null);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
assertTrue(jaasProvider.supports(UsernamePasswordAuthenticationToken.class));
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() {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -91,22 +91,11 @@ public class RememberMeAuthenticationTokenTests extends TestCase {
assertEquals("key".hashCode(), token.getKeyHash());
assertEquals("Test", token.getPrincipal());
assertEquals("", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority());
assertEquals("ROLE_ONE", token.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities().get(1).getAuthority());
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() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test",
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.getCredentials(), resultingToken.getCredentials());
assertEquals("FOOBAR_RUN_AS_SOMETHING", resultingToken.getAuthorities()[0].getAuthority());
assertEquals("ONE", resultingToken.getAuthorities()[1].getAuthority());
assertEquals("TWO", resultingToken.getAuthorities()[2].getAuthority());
assertEquals("FOOBAR_RUN_AS_SOMETHING", resultingToken.getAuthorities().get(0).getAuthority());
assertEquals("ONE", resultingToken.getAuthorities().get(1).getAuthority());
assertEquals("TWO", resultingToken.getAuthorities().get(2).getAuthority());
RunAsUserToken resultCast = (RunAsUserToken) resultingToken;
assertEquals("my_password".hashCode(), resultCast.getKeyHash());
@ -87,9 +87,9 @@ public class RunAsManagerImplTests extends TestCase {
assertEquals(inputToken.getPrincipal(), resultingToken.getPrincipal());
assertEquals(inputToken.getCredentials(), resultingToken.getCredentials());
assertEquals("ROLE_RUN_AS_SOMETHING", resultingToken.getAuthorities()[0].getAuthority());
assertEquals("ROLE_ONE", resultingToken.getAuthorities()[1].getAuthority());
assertEquals("ROLE_TWO", resultingToken.getAuthorities()[2].getAuthority());
assertEquals("ROLE_RUN_AS_SOMETHING", resultingToken.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_ONE", resultingToken.getAuthorities().get(1).getAuthority());
assertEquals("ROLE_TWO", resultingToken.getAuthorities().get(2).getAuthority());
RunAsUserToken resultCast = (RunAsUserToken) resultingToken;
assertEquals("my_password".hashCode(), resultCast.getKeyHash());

View File

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

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