SEC-1012: Refactoring of use of GrantedAuthority[] to generified collections
This commit is contained in:
parent
e891b334e6
commit
ec44f2bdfe
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -4,8 +4,6 @@ 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;
|
||||
|
||||
/**
|
||||
|
@ -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);
|
||||
|
||||
|
|
|
@ -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,6 +45,14 @@ 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.
|
||||
*
|
||||
|
@ -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)
|
||||
|
|
|
@ -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());
|
||||
|
||||
|
|
|
@ -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")},
|
||||
|
@ -151,8 +144,8 @@ public class CasAuthenticationTokenTests extends TestCase {
|
|||
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());
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
|
|
@ -1,22 +1,20 @@
|
|||
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() {
|
||||
public List<GrantedAuthority> getGrantedAuthorities() {
|
||||
Assert.notNull(authorities, "Granted authorities have not been set");
|
||||
return (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]);
|
||||
return authorities;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
|
|
|
@ -34,7 +34,6 @@ public class MockAuthenticationManager extends AbstractAuthenticationManager {
|
|||
}
|
||||
|
||||
public MockAuthenticationManager() {
|
||||
super();
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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]);
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -16,43 +16,68 @@ 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 Map<String, Collection<GrantedAuthority>> attributes2grantedAuthoritiesMap = null;
|
||||
private String stringSeparator = ",";
|
||||
private String[] mappableAttributes = null;
|
||||
|
||||
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
Assert.notNull(attributes2grantedAuthoritiesMap, "attributes2grantedAuthoritiesMap must be set");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether all properties have been set to correct values, and do some preprocessing.
|
||||
* Map the given array of attributes to Spring Security GrantedAuthorities.
|
||||
*/
|
||||
public void afterPropertiesSet() {
|
||||
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();
|
||||
|
||||
return gaList;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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");
|
||||
attributes2grantedAuthoritiesMap = preProcessMap(attributes2grantedAuthoritiesMap);
|
||||
this.attributes2grantedAuthoritiesMap = preProcessMap(attributes2grantedAuthoritiesMap);
|
||||
|
||||
try {
|
||||
mappableAttributes = (String[])attributes2grantedAuthoritiesMap.keySet().toArray(new String[]{});
|
||||
mappableAttributes = (String[])this.attributes2grantedAuthoritiesMap.keySet().toArray(new String[]{});
|
||||
} catch ( ArrayStoreException ase ) {
|
||||
throw new IllegalArgumentException("attributes2grantedAuthoritiesMap contains non-String objects as keys");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Preprocess the given map
|
||||
* Preprocess the given map to convert all the values to GrantedAuthority collections
|
||||
*
|
||||
* @param orgMap The map to process
|
||||
* @return the processed Map
|
||||
*/
|
||||
private Map preProcessMap(Map orgMap) {
|
||||
private Map<String, Collection<GrantedAuthority>> preProcessMap(Map<String, Object> orgMap) {
|
||||
Map result = new HashMap(orgMap.size());
|
||||
Iterator it = orgMap.entrySet().iterator();
|
||||
while ( it.hasNext() ) {
|
||||
Map.Entry entry = (Map.Entry)it.next();
|
||||
|
||||
for(Map.Entry entry : orgMap.entrySet()) {
|
||||
result.put(entry.getKey(),getGrantedAuthorityCollection(entry.getValue()));
|
||||
}
|
||||
return result;
|
||||
|
@ -79,8 +104,10 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
|
|||
* The value to convert to a GrantedAuthority Collection
|
||||
* @return Collection containing the GrantedAuthority Collection
|
||||
*/
|
||||
private void addGrantedAuthorityCollection(Collection result, Object value) {
|
||||
if ( value != null ) {
|
||||
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[] ) {
|
||||
|
@ -88,27 +115,26 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
|
|||
} else if ( value instanceof String ) {
|
||||
addGrantedAuthorityCollection(result,(String)value);
|
||||
} else if ( value instanceof GrantedAuthority ) {
|
||||
result.add(value);
|
||||
result.add((GrantedAuthority) value);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid object type: "+value.getClass().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void addGrantedAuthorityCollection(Collection result, Collection value) {
|
||||
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Collection value) {
|
||||
Iterator it = value.iterator();
|
||||
while ( it.hasNext() ) {
|
||||
addGrantedAuthorityCollection(result,it.next());
|
||||
}
|
||||
}
|
||||
|
||||
private void addGrantedAuthorityCollection(Collection result, Object[] value) {
|
||||
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Object[] value) {
|
||||
for ( int i = 0 ; i < value.length ; i++ ) {
|
||||
addGrantedAuthorityCollection(result,value[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private void addGrantedAuthorityCollection(Collection result, String value) {
|
||||
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, String value) {
|
||||
StringTokenizer st = new StringTokenizer(value,stringSeparator,false);
|
||||
while ( st.hasMoreTokens() ) {
|
||||
String nextToken = st.nextToken();
|
||||
|
@ -118,33 +144,6 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the attributes2grantedAuthoritiesMap.
|
||||
*/
|
||||
public Map getAttributes2grantedAuthoritiesMap() {
|
||||
return attributes2grantedAuthoritiesMap;
|
||||
}
|
||||
/**
|
||||
* @param attributes2grantedAuthoritiesMap The attributes2grantedAuthoritiesMap to set.
|
||||
*/
|
||||
public void setAttributes2grantedAuthoritiesMap(Map attributes2grantedAuthoritiesMap) {
|
||||
this.attributes2grantedAuthoritiesMap = attributes2grantedAuthoritiesMap;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @see org.springframework.security.authoritymapping.MappableAttributesRetriever#getMappableAttributes()
|
||||
|
@ -164,4 +163,5 @@ public class MapBasedAttributes2GrantedAuthoritiesMapper implements Attributes2G
|
|||
public void setStringSeparator(String stringSeparator) {
|
||||
this.stringSeparator = stringSeparator;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -70,7 +70,7 @@ public class MethodInvocationPrivilegeEvaluator implements InitializingBean {
|
|||
}
|
||||
|
||||
if ((authentication == null) || (authentication.getAuthorities() == null)
|
||||
|| (authentication.getAuthorities().length == 0)) {
|
||||
|| (authentication.getAuthorities().isEmpty())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
|
@ -62,7 +62,7 @@ public class WebInvocationPrivilegeEvaluator implements InitializingBean {
|
|||
}
|
||||
|
||||
if ((authentication == null) || (authentication.getAuthorities() == null)
|
||||
|| (authentication.getAuthorities().length == 0)) {
|
||||
|| authentication.getAuthorities().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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,37 +52,35 @@ 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 = authorities;
|
||||
this.authorities = Collections.unmodifiableList(authorities);
|
||||
}
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof AbstractAuthenticationToken) {
|
||||
if (!(obj instanceof AbstractAuthenticationToken)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
AbstractAuthenticationToken test = (AbstractAuthenticationToken) obj;
|
||||
|
||||
if (!((this.getAuthorities() == null) && (test.getAuthorities() == null))) {
|
||||
if ((this.getAuthorities() == null) || (test.getAuthorities() == null)) {
|
||||
if (!(authorities == null && test.authorities == null)) {
|
||||
// Not both null
|
||||
if (authorities == null || test.authorities == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.getAuthorities().length != test.getAuthorities().length) {
|
||||
if(!authorities.equals(test.authorities)) {
|
||||
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)) {
|
||||
|
@ -124,18 +114,8 @@ public abstract class AbstractAuthenticationToken implements Authentication {
|
|||
return this.isAuthenticated() == test.isAuthenticated();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
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() {
|
||||
|
@ -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");
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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,6 +39,10 @@ public class AnonymousAuthenticationToken extends AbstractAuthenticationToken im
|
|||
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public AnonymousAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) {
|
||||
this(key, principal, Arrays.asList(authorities));
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
|
@ -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");
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
@ -84,7 +87,8 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
|
|||
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;
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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;
|
||||
|
@ -38,7 +40,7 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsService implements Aut
|
|||
public final UserDetails loadUserDetails(Authentication token) throws AuthenticationException {
|
||||
Assert.notNull(token.getDetails());
|
||||
Assert.isInstanceOf(GrantedAuthoritiesContainer.class, token.getDetails());
|
||||
GrantedAuthority[] authorities = ((GrantedAuthoritiesContainer) token.getDetails()).getGrantedAuthorities();
|
||||
List<GrantedAuthority> authorities = ((GrantedAuthoritiesContainer) token.getDetails()).getGrantedAuthorities();
|
||||
UserDetails ud = createuserDetails(token, authorities);
|
||||
return ud;
|
||||
}
|
||||
|
@ -49,7 +51,7 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsService implements Aut
|
|||
* @param token the authentication request token
|
||||
* @param authorities the pre-authenticated authorities.
|
||||
*/
|
||||
protected UserDetails createuserDetails(Authentication token, GrantedAuthority[] authorities) {
|
||||
protected UserDetails createuserDetails(Authentication token, List<GrantedAuthority> authorities) {
|
||||
return new User(token.getName(), "N/A", true, true, true, true, authorities);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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$
|
||||
|
@ -50,7 +53,9 @@ public class RemoteAuthenticationManagerImpl implements RemoteAuthenticationMana
|
|||
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());
|
||||
}
|
||||
|
|
|
@ -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)) {
|
||||
|
|
|
@ -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 <x509 /> 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);
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
|
@ -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);
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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) {}
|
||||
}
|
|
@ -1,5 +0,0 @@
|
|||
<html>
|
||||
<body>
|
||||
Deprecated and will be removed in a future version. Use a caching UserDetailsService instead.
|
||||
</body>
|
||||
</html>
|
|
@ -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>
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -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,13 +76,11 @@ 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());
|
||||
|
|
|
@ -15,6 +15,8 @@
|
|||
|
||||
package org.springframework.security.runas;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
|
||||
import org.springframework.security.providers.AbstractAuthenticationToken;
|
||||
|
@ -39,7 +41,7 @@ public class RunAsUserToken extends AbstractAuthenticationToken {
|
|||
|
||||
public RunAsUserToken(String key, Object principal, Object credentials, GrantedAuthority[] authorities,
|
||||
Class originalAuthentication) {
|
||||
super(authorities);
|
||||
super(Arrays.asList(authorities));
|
||||
this.keyHash = key.hashCode();
|
||||
this.principal = principal;
|
||||
this.credentials = credentials;
|
||||
|
|
|
@ -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;
|
||||
|
@ -18,7 +19,7 @@ public class PreAuthenticatedGrantedAuthoritiesAuthenticationDetails extends Aut
|
|||
MutableGrantedAuthoritiesContainer {
|
||||
public static final long serialVersionUID = 1L;
|
||||
|
||||
private GrantedAuthority[] preAuthenticatedGrantedAuthorities = null;
|
||||
private List<GrantedAuthority> preAuthenticatedGrantedAuthorities = null;
|
||||
|
||||
public PreAuthenticatedGrantedAuthoritiesAuthenticationDetails(Object context) {
|
||||
super(context);
|
||||
|
@ -30,7 +31,7 @@ public class PreAuthenticatedGrantedAuthoritiesAuthenticationDetails extends Aut
|
|||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append(super.toString() + "; ");
|
||||
sb.append("preAuthenticatedGrantedAuthorities: " + Arrays.asList(preAuthenticatedGrantedAuthorities));
|
||||
sb.append("preAuthenticatedGrantedAuthorities: " + preAuthenticatedGrantedAuthorities);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
@ -38,18 +39,16 @@ public class PreAuthenticatedGrantedAuthoritiesAuthenticationDetails extends Aut
|
|||
*
|
||||
* @see org.springframework.security.GrantedAuthoritiesContainer#getGrantedAuthorities()
|
||||
*/
|
||||
public GrantedAuthority[] getGrantedAuthorities() {
|
||||
public List<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;
|
||||
|
||||
return preAuthenticatedGrantedAuthorities;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
public void setGrantedAuthorities(List<GrantedAuthority> aJ2eeBasedGrantedAuthorities) {
|
||||
this.preAuthenticatedGrantedAuthorities = Collections.unmodifiableList(aJ2eeBasedGrantedAuthorities);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
@ -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;
|
||||
|
@ -51,12 +53,11 @@ public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extend
|
|||
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);
|
||||
|
@ -71,7 +72,7 @@ public abstract class AbstractPreAuthenticatedAuthenticationDetailsSource extend
|
|||
* @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
|
||||
|
|
|
@ -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;
|
||||
|
||||
|
@ -35,7 +36,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs
|
|||
* 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++) {
|
||||
|
@ -44,6 +45,6 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource extends Abs
|
|||
}
|
||||
}
|
||||
|
||||
return (String[]) j2eeUserRolesList.toArray(new String[j2eeUserRolesList.size()]);
|
||||
return j2eeUserRolesList;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
@ -24,7 +25,7 @@ import org.springframework.util.Assert;
|
|||
* @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();
|
||||
|
||||
|
@ -44,7 +45,7 @@ public class WebSpherePreAuthenticatedAuthenticationDetailsSource extends Authen
|
|||
}
|
||||
|
||||
/**
|
||||
* Build the authentication details object. If the speficied authentication
|
||||
* 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.
|
||||
|
@ -65,11 +66,11 @@ public class WebSpherePreAuthenticatedAuthenticationDetailsSource extends Authen
|
|||
*
|
||||
* @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: "
|
||||
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;
|
||||
|
|
|
@ -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));
|
||||
|
@ -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 + "]");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -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.
|
||||
|
|
|
@ -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");
|
||||
|
|
|
@ -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>.
|
||||
|
|
|
@ -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);
|
||||
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
|
||||
|
|
|
@ -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++) {
|
||||
for (int i=0; i < user.getAuthorities().size(); i++) {
|
||||
getJdbcTemplate().update(createAuthoritySql,
|
||||
new Object[] {user.getUsername(), user.getAuthorities()[i].getAuthority()});
|
||||
new Object[] {user.getUsername(), user.getAuthorities().get(i).getAuthority()});
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -238,7 +238,7 @@ 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);
|
||||
|
||||
|
@ -249,8 +249,8 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
|
|||
|
||||
final int groupId = findGroupId(groupName);
|
||||
|
||||
for (int i=0; i < authorities.length; i++) {
|
||||
final String authority = authorities[i].getAuthority();
|
||||
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);
|
||||
|
@ -316,11 +316,11 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
|
|||
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() {
|
||||
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);
|
||||
|
@ -329,7 +329,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
|
|||
}
|
||||
});
|
||||
|
||||
return (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[0]);
|
||||
return authorities;
|
||||
}
|
||||
|
||||
public void removeGroupAuthority(String groupName, final GrantedAuthority authority) {
|
||||
|
@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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();
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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");
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
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;
|
||||
|
@ -23,7 +25,8 @@ public class RoleHierarchyVoter extends RoleVoter {
|
|||
/**
|
||||
* Calls the <tt>RoleHierarchy</tt> to obtain the complete set of user authorities.
|
||||
*/
|
||||
GrantedAuthority[] extractAuthorities(Authentication authentication) {
|
||||
@Override
|
||||
List<GrantedAuthority> extractAuthorities(Authentication authentication) {
|
||||
return roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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
|
||||
*
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,14 +1,16 @@
|
|||
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;
|
||||
|
||||
|
@ -16,179 +18,159 @@ 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);
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetNoMap() {
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testAfterPropertiesSetNoMap() throws Exception {
|
||||
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() {
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testAfterPropertiesSetEmptyMap() throws Exception {
|
||||
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() {
|
||||
@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);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// Expected exception
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetInvalidValueTypeMap1() {
|
||||
@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);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// Expected exception
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetInvalidValueTypeMap2() {
|
||||
@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);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// Expected exception
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetValidMap() {
|
||||
@Test
|
||||
public void testAfterPropertiesSetValidMap() throws Exception {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
HashMap m = getValidAttributes2GrantedAuthoritiesMap();
|
||||
mapper.setAttributes2grantedAuthoritiesMap(m);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testMapping1() {
|
||||
@Test
|
||||
public void testMapping1() throws Exception {
|
||||
String[] roles = { "role1" };
|
||||
String[] expectedGas = { "ga1" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping2() {
|
||||
@Test
|
||||
public void testMapping2() throws Exception {
|
||||
String[] roles = { "role2" };
|
||||
String[] expectedGas = { "ga2" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping3() {
|
||||
@Test
|
||||
public void testMapping3() throws Exception {
|
||||
String[] roles = { "role3" };
|
||||
String[] expectedGas = { "ga3", "ga4" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping4() {
|
||||
@Test
|
||||
public void testMapping4() throws Exception {
|
||||
String[] roles = { "role4" };
|
||||
String[] expectedGas = { "ga5", "ga6" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping5() {
|
||||
@Test
|
||||
public void testMapping5() throws Exception {
|
||||
String[] roles = { "role5" };
|
||||
String[] expectedGas = { "ga7", "ga8", "ga9" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping6() {
|
||||
@Test
|
||||
public void testMapping6() throws Exception {
|
||||
String[] roles = { "role6" };
|
||||
String[] expectedGas = { "ga10", "ga11", "ga12" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping7() {
|
||||
@Test
|
||||
public void testMapping7() throws Exception {
|
||||
String[] roles = { "role7" };
|
||||
String[] expectedGas = { "ga13", "ga14" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping8() {
|
||||
@Test
|
||||
public void testMapping8() throws Exception {
|
||||
String[] roles = { "role8" };
|
||||
String[] expectedGas = { "ga13", "ga14" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping9() {
|
||||
@Test
|
||||
public void testMapping9() throws Exception {
|
||||
String[] roles = { "role9" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping10() {
|
||||
@Test
|
||||
public void testMapping10() throws Exception {
|
||||
String[] roles = { "role10" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping11() {
|
||||
@Test
|
||||
public void testMapping11() throws Exception {
|
||||
String[] roles = { "role11" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testNonExistingMapping() {
|
||||
@Test
|
||||
public void testNonExistingMapping() throws Exception {
|
||||
String[] roles = { "nonExisting" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMappingCombination() {
|
||||
@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();
|
||||
|
@ -211,7 +193,7 @@ public class MapBasedAttributes2GrantedAuthoritiesMapperTest extends TestCase {
|
|||
return m;
|
||||
}
|
||||
|
||||
private MapBasedAttributes2GrantedAuthoritiesMapper getDefaultMapper() {
|
||||
private MapBasedAttributes2GrantedAuthoritiesMapper getDefaultMapper() throws Exception {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.setAttributes2grantedAuthoritiesMap(getValidAttributes2GrantedAuthoritiesMap());
|
||||
mapper.afterPropertiesSet();
|
||||
|
@ -219,13 +201,13 @@ public class MapBasedAttributes2GrantedAuthoritiesMapperTest extends TestCase {
|
|||
}
|
||||
|
||||
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());
|
||||
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
|
||||
assertTrue("Role collections should match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
|
||||
.containsAll(resultColl)
|
||||
&& resultColl.containsAll(expectedColl));
|
||||
}
|
||||
|
|
|
@ -5,6 +5,7 @@ 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;
|
||||
|
||||
|
@ -98,10 +99,10 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
|
|||
}
|
||||
|
||||
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());
|
||||
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
|
||||
|
|
|
@ -38,7 +38,7 @@ 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)
|
||||
|
|
|
@ -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,14 +42,12 @@ 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 ========================================================================================================
|
||||
|
||||
|
@ -103,13 +99,6 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
|
|||
}
|
||||
|
||||
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();
|
||||
|
@ -148,20 +137,12 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
|
|||
|
||||
public void testExistingContextContentsCopiedIntoContextHolderFromSessionAndChangesToContextCopiedBackToSession()
|
||||
throws Exception {
|
||||
|
||||
// Build an Authentication object we simulate came from HttpSession
|
||||
PrincipalSpringSecurityUserToken sessionPrincipal = new PrincipalSpringSecurityUserToken(
|
||||
"key",
|
||||
UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
|
||||
"someone",
|
||||
"password",
|
||||
new GrantedAuthority[] { new GrantedAuthorityImpl("SOME_ROLE") },
|
||||
null);
|
||||
|
||||
// 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);
|
||||
AuthorityUtils.createAuthorityList("SOME_DIFFERENT_ROLE"));
|
||||
|
||||
// Build a Context to store in HttpSession (simulating prior request)
|
||||
SecurityContext sc = new SecurityContextImpl();
|
||||
|
@ -194,10 +175,10 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
|
|||
|
||||
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);
|
||||
UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
|
||||
"someone",
|
||||
"password",
|
||||
AuthorityUtils.createAuthorityList("SOME_ROLE"));
|
||||
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
@ -258,12 +239,11 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
|
|||
}
|
||||
|
||||
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);
|
||||
// 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();
|
||||
|
@ -289,13 +269,6 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
|
|||
}
|
||||
|
||||
public void testConcurrentThreadsLazilyChangeFilterAppliedValueToTrue() throws Exception {
|
||||
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);
|
||||
|
@ -319,8 +292,7 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
|
|||
|
||||
}
|
||||
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockFilterChain extends TestCase implements FilterChain {
|
||||
private Authentication changeContextHolder;
|
||||
|
|
|
@ -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"));
|
||||
|
@ -139,10 +140,10 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
|
|||
|
||||
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.length);
|
||||
assertEquals("ROLE_MANAGER", authorities[0].getAuthority());
|
||||
assertEquals("Should have 1 role", 1, authorities.size());
|
||||
assertEquals("ROLE_MANAGER", authorities.get(0).getAuthority());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -47,10 +47,9 @@ public class PreAuthenticatedAuthenticationTokenTests extends TestCase {
|
|||
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));
|
||||
Collection resultColl = token.getAuthorities();
|
||||
assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl,
|
||||
expectedColl.containsAll(resultColl) && resultColl.containsAll(expectedColl));
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -1,61 +1,58 @@
|
|||
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() {
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public 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) {
|
||||
}
|
||||
}
|
||||
|
||||
public final void testGetUserDetailsNoDetails() {
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public 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) {
|
||||
}
|
||||
}
|
||||
|
||||
public final void testGetUserDetailsEmptyAuthorities() {
|
||||
@Test
|
||||
public void testGetUserDetailsEmptyAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
final GrantedAuthority[] gas = new GrantedAuthority[] {};
|
||||
testGetUserDetails(userName, gas);
|
||||
testGetUserDetails(userName, AuthorityUtils.NO_AUTHORITIES);
|
||||
}
|
||||
|
||||
public final void testGetUserDetailsWithAuthorities() {
|
||||
@Test
|
||||
public void testGetUserDetailsWithAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
final GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1"), new GrantedAuthorityImpl("Role2") };
|
||||
testGetUserDetails(userName, gas);
|
||||
testGetUserDetails(userName, AuthorityUtils.createAuthorityList("Role1", "Role2"));
|
||||
}
|
||||
|
||||
private void testGetUserDetails(final String userName, final GrantedAuthority[] gas) {
|
||||
private void testGetUserDetails(final String userName, final List<GrantedAuthority> gas) {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userName, "dummy");
|
||||
token.setDetails(new GrantedAuthoritiesContainer() {
|
||||
public GrantedAuthority[] getGrantedAuthorities() {
|
||||
public List<GrantedAuthority> getGrantedAuthorities() {
|
||||
return gas;
|
||||
}
|
||||
});
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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")});
|
||||
|
|
|
@ -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")});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
|
|
|
@ -1,38 +1,41 @@
|
|||
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() {
|
||||
@Test
|
||||
public 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"));
|
||||
}
|
||||
|
||||
public final void testGetSetPreAuthenticatedGrantedAuthorities() {
|
||||
@Test
|
||||
public 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);
|
||||
|
||||
details.setGrantedAuthorities(gas);
|
||||
|
@ -41,20 +44,14 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests ext
|
|||
expectedGas.containsAll(returnedGas) && returnedGas.containsAll(expectedGas));
|
||||
}
|
||||
|
||||
public final void testGetWithoutSetPreAuthenticatedGrantedAuthorities() {
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public 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());
|
||||
}
|
||||
List<GrantedAuthority> gas = details.getGrantedAuthorities();
|
||||
}
|
||||
|
||||
private final HttpServletRequest getRequest(final String userName,final String[] aRoles)
|
||||
{
|
||||
private HttpServletRequest getRequest(final String userName,final String[] aRoles) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set roles = new HashSet(Arrays.asList(aRoles));
|
||||
public boolean isUserInRole(String arg0) {
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue