SEC-1012: Refactoring of use of GrantedAuthority[] to generified collections
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+192
-210
@@ -1,232 +1,214 @@
|
||||
package org.springframework.security.authoritymapping;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author Ruud Senden
|
||||
*/
|
||||
public class MapBasedAttributes2GrantedAuthoritiesMapperTest extends TestCase {
|
||||
public class MapBasedAttributes2GrantedAuthoritiesMapperTest {
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
// Set Log4j loglevel to debug to include all logstatements in tests
|
||||
Logger.getRootLogger().setLevel(Level.DEBUG);
|
||||
}
|
||||
protected void setUp() throws Exception {
|
||||
// Set Log4j loglevel to debug to include all logstatements in tests
|
||||
Logger.getRootLogger().setLevel(Level.DEBUG);
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetNoMap() {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// Expected exception
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetEmptyMap() {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.setAttributes2grantedAuthoritiesMap(new HashMap());
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// Expected exception
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetInvalidKeyTypeMap() {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
HashMap m = new HashMap();
|
||||
m.put(new Object(),"ga1");
|
||||
mapper.setAttributes2grantedAuthoritiesMap(m);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// Expected exception
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetInvalidValueTypeMap1() {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
HashMap m = new HashMap();
|
||||
m.put("role1",new Object());
|
||||
mapper.setAttributes2grantedAuthoritiesMap(m);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// Expected exception
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetInvalidValueTypeMap2() {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
HashMap m = new HashMap();
|
||||
m.put("role1",new Object[]{new String[]{"ga1","ga2"}, new Object()});
|
||||
mapper.setAttributes2grantedAuthoritiesMap(m);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// Expected exception
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testAfterPropertiesSetNoMap() throws Exception {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.afterPropertiesSet();
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSetValidMap() {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
HashMap m = getValidAttributes2GrantedAuthoritiesMap();
|
||||
mapper.setAttributes2grantedAuthoritiesMap(m);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testMapping1() {
|
||||
String[] roles = { "role1" };
|
||||
String[] expectedGas = { "ga1" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping2() {
|
||||
String[] roles = { "role2" };
|
||||
String[] expectedGas = { "ga2" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping3() {
|
||||
String[] roles = { "role3" };
|
||||
String[] expectedGas = { "ga3", "ga4" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping4() {
|
||||
String[] roles = { "role4" };
|
||||
String[] expectedGas = { "ga5", "ga6" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping5() {
|
||||
String[] roles = { "role5" };
|
||||
String[] expectedGas = { "ga7", "ga8", "ga9" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping6() {
|
||||
String[] roles = { "role6" };
|
||||
String[] expectedGas = { "ga10", "ga11", "ga12" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping7() {
|
||||
String[] roles = { "role7" };
|
||||
String[] expectedGas = { "ga13", "ga14" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping8() {
|
||||
String[] roles = { "role8" };
|
||||
String[] expectedGas = { "ga13", "ga14" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping9() {
|
||||
String[] roles = { "role9" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping10() {
|
||||
String[] roles = { "role10" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMapping11() {
|
||||
String[] roles = { "role11" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testNonExistingMapping() {
|
||||
String[] roles = { "nonExisting" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testMappingCombination() {
|
||||
String[] roles = { "role1", "role2", "role3", "role4", "role5", "role6", "role7", "role8", "role9", "role10", "role11" };
|
||||
String[] expectedGas = { "ga1", "ga2", "ga3", "ga4", "ga5", "ga6", "ga7", "ga8", "ga9", "ga10", "ga11", "ga12", "ga13", "ga14"};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testAfterPropertiesSetEmptyMap() throws Exception {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.setAttributes2grantedAuthoritiesMap(new HashMap());
|
||||
mapper.afterPropertiesSet();
|
||||
}
|
||||
|
||||
private HashMap getValidAttributes2GrantedAuthoritiesMap() {
|
||||
HashMap m = new HashMap();
|
||||
m.put("role1","ga1");
|
||||
m.put("role2",new GrantedAuthorityImpl("ga2"));
|
||||
m.put("role3",Arrays.asList(new Object[]{"ga3",new GrantedAuthorityImpl("ga4")}));
|
||||
m.put("role4","ga5,ga6");
|
||||
m.put("role5",Arrays.asList(new Object[]{"ga7","ga8",new Object[]{new GrantedAuthorityImpl("ga9")}}));
|
||||
m.put("role6",new Object[]{"ga10","ga11",new Object[]{new GrantedAuthorityImpl("ga12")}});
|
||||
m.put("role7",new String[]{"ga13","ga14"});
|
||||
m.put("role8",new String[]{"ga13","ga14",null});
|
||||
m.put("role9",null);
|
||||
m.put("role10",new Object[]{});
|
||||
m.put("role11",Arrays.asList(new Object[]{null}));
|
||||
return m;
|
||||
}
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testAfterPropertiesSetInvalidKeyTypeMap() throws Exception {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
HashMap m = new HashMap();
|
||||
m.put(new Object(),"ga1");
|
||||
mapper.setAttributes2grantedAuthoritiesMap(m);
|
||||
mapper.afterPropertiesSet();
|
||||
}
|
||||
|
||||
private MapBasedAttributes2GrantedAuthoritiesMapper getDefaultMapper() {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.setAttributes2grantedAuthoritiesMap(getValidAttributes2GrantedAuthoritiesMap());
|
||||
mapper.afterPropertiesSet();
|
||||
return mapper;
|
||||
}
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testAfterPropertiesSetInvalidValueTypeMap1() throws Exception {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
HashMap m = new HashMap();
|
||||
m.put("role1",new Object());
|
||||
mapper.setAttributes2grantedAuthoritiesMap(m);
|
||||
mapper.afterPropertiesSet();
|
||||
}
|
||||
|
||||
private void testGetGrantedAuthorities(Attributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
|
||||
GrantedAuthority[] result = mapper.getGrantedAuthorities(roles);
|
||||
Collection resultColl = new ArrayList(result.length);
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
resultColl.add(result[i].getAuthority());
|
||||
}
|
||||
Collection expectedColl = Arrays.asList(expectedGas);
|
||||
assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
|
||||
.containsAll(resultColl)
|
||||
&& resultColl.containsAll(expectedColl));
|
||||
}
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testAfterPropertiesSetInvalidValueTypeMap2() throws Exception {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
HashMap m = new HashMap();
|
||||
m.put("role1",new Object[]{new String[]{"ga1","ga2"}, new Object()});
|
||||
mapper.setAttributes2grantedAuthoritiesMap(m);
|
||||
mapper.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterPropertiesSetValidMap() throws Exception {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
HashMap m = getValidAttributes2GrantedAuthoritiesMap();
|
||||
mapper.setAttributes2grantedAuthoritiesMap(m);
|
||||
mapper.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping1() throws Exception {
|
||||
String[] roles = { "role1" };
|
||||
String[] expectedGas = { "ga1" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping2() throws Exception {
|
||||
String[] roles = { "role2" };
|
||||
String[] expectedGas = { "ga2" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping3() throws Exception {
|
||||
String[] roles = { "role3" };
|
||||
String[] expectedGas = { "ga3", "ga4" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping4() throws Exception {
|
||||
String[] roles = { "role4" };
|
||||
String[] expectedGas = { "ga5", "ga6" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping5() throws Exception {
|
||||
String[] roles = { "role5" };
|
||||
String[] expectedGas = { "ga7", "ga8", "ga9" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping6() throws Exception {
|
||||
String[] roles = { "role6" };
|
||||
String[] expectedGas = { "ga10", "ga11", "ga12" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping7() throws Exception {
|
||||
String[] roles = { "role7" };
|
||||
String[] expectedGas = { "ga13", "ga14" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping8() throws Exception {
|
||||
String[] roles = { "role8" };
|
||||
String[] expectedGas = { "ga13", "ga14" };
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping9() throws Exception {
|
||||
String[] roles = { "role9" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping10() throws Exception {
|
||||
String[] roles = { "role10" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapping11() throws Exception {
|
||||
String[] roles = { "role11" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonExistingMapping() throws Exception {
|
||||
String[] roles = { "nonExisting" };
|
||||
String[] expectedGas = {};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMappingCombination() throws Exception {
|
||||
String[] roles = { "role1", "role2", "role3", "role4", "role5", "role6", "role7", "role8", "role9", "role10", "role11" };
|
||||
String[] expectedGas = { "ga1", "ga2", "ga3", "ga4", "ga5", "ga6", "ga7", "ga8", "ga9", "ga10", "ga11", "ga12", "ga13", "ga14"};
|
||||
Attributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
private HashMap getValidAttributes2GrantedAuthoritiesMap() {
|
||||
HashMap m = new HashMap();
|
||||
m.put("role1","ga1");
|
||||
m.put("role2",new GrantedAuthorityImpl("ga2"));
|
||||
m.put("role3",Arrays.asList(new Object[]{"ga3",new GrantedAuthorityImpl("ga4")}));
|
||||
m.put("role4","ga5,ga6");
|
||||
m.put("role5",Arrays.asList(new Object[]{"ga7","ga8",new Object[]{new GrantedAuthorityImpl("ga9")}}));
|
||||
m.put("role6",new Object[]{"ga10","ga11",new Object[]{new GrantedAuthorityImpl("ga12")}});
|
||||
m.put("role7",new String[]{"ga13","ga14"});
|
||||
m.put("role8",new String[]{"ga13","ga14",null});
|
||||
m.put("role9",null);
|
||||
m.put("role10",new Object[]{});
|
||||
m.put("role11",Arrays.asList(new Object[]{null}));
|
||||
return m;
|
||||
}
|
||||
|
||||
private MapBasedAttributes2GrantedAuthoritiesMapper getDefaultMapper() throws Exception {
|
||||
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.setAttributes2grantedAuthoritiesMap(getValidAttributes2GrantedAuthoritiesMap());
|
||||
mapper.afterPropertiesSet();
|
||||
return mapper;
|
||||
}
|
||||
|
||||
private void testGetGrantedAuthorities(Attributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
|
||||
List<GrantedAuthority> result = mapper.getGrantedAuthorities(Arrays.asList(roles));
|
||||
Collection resultColl = new ArrayList(result.size());
|
||||
for (int i = 0; i < result.size(); i++) {
|
||||
resultColl.add(result.get(i).getAuthority());
|
||||
}
|
||||
Collection expectedColl = Arrays.asList(expectedGas);
|
||||
assertTrue("Role collections should match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
|
||||
.containsAll(resultColl)
|
||||
&& resultColl.containsAll(expectedColl));
|
||||
}
|
||||
}
|
||||
|
||||
+94
-93
@@ -5,117 +5,118 @@ import org.springframework.security.GrantedAuthority;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author TSARDD
|
||||
* @since 18-okt-2007
|
||||
*/
|
||||
public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
|
||||
|
||||
public final void testAfterPropertiesSetConvertToUpperAndLowerCase() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.setConvertAttributeToLowerCase(true);
|
||||
mapper.setConvertAttributeToUpperCase(true);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
public final void testAfterPropertiesSetConvertToUpperAndLowerCase() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.setConvertAttributeToLowerCase(true);
|
||||
mapper.setConvertAttributeToUpperCase(true);
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
fail("Expected exception not thrown");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testAfterPropertiesSet() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
public final void testAfterPropertiesSet() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
try {
|
||||
mapper.afterPropertiesSet();
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
public final void testGetGrantedAuthoritiesNoConversion() {
|
||||
String[] roles = { "Role1", "Role2" };
|
||||
String[] expectedGas = { "Role1", "Role2" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
public final void testGetGrantedAuthoritiesNoConversion() {
|
||||
String[] roles = { "Role1", "Role2" };
|
||||
String[] expectedGas = { "Role1", "Role2" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testGetGrantedAuthoritiesToUpperCase() {
|
||||
String[] roles = { "Role1", "Role2" };
|
||||
String[] expectedGas = { "ROLE1", "ROLE2" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setConvertAttributeToUpperCase(true);
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
public final void testGetGrantedAuthoritiesToUpperCase() {
|
||||
String[] roles = { "Role1", "Role2" };
|
||||
String[] expectedGas = { "ROLE1", "ROLE2" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setConvertAttributeToUpperCase(true);
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testGetGrantedAuthoritiesToLowerCase() {
|
||||
String[] roles = { "Role1", "Role2" };
|
||||
String[] expectedGas = { "role1", "role2" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setConvertAttributeToLowerCase(true);
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
public final void testGetGrantedAuthoritiesToLowerCase() {
|
||||
String[] roles = { "Role1", "Role2" };
|
||||
String[] expectedGas = { "role1", "role2" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setConvertAttributeToLowerCase(true);
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testGetGrantedAuthoritiesAddPrefixIfAlreadyExisting() {
|
||||
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
|
||||
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_ROLE_Role3" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setAddPrefixIfAlreadyExisting(true);
|
||||
mapper.setAttributePrefix("ROLE_");
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
public final void testGetGrantedAuthoritiesAddPrefixIfAlreadyExisting() {
|
||||
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
|
||||
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_ROLE_Role3" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setAddPrefixIfAlreadyExisting(true);
|
||||
mapper.setAttributePrefix("ROLE_");
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting1() {
|
||||
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
|
||||
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_Role3" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setAddPrefixIfAlreadyExisting(false);
|
||||
mapper.setAttributePrefix("ROLE_");
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting1() {
|
||||
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
|
||||
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_Role3" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setAddPrefixIfAlreadyExisting(false);
|
||||
mapper.setAttributePrefix("ROLE_");
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting2() {
|
||||
String[] roles = { "Role1", "Role2", "role_Role3" };
|
||||
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_role_Role3" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setAddPrefixIfAlreadyExisting(false);
|
||||
mapper.setAttributePrefix("ROLE_");
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting2() {
|
||||
String[] roles = { "Role1", "Role2", "role_Role3" };
|
||||
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_role_Role3" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setAddPrefixIfAlreadyExisting(false);
|
||||
mapper.setAttributePrefix("ROLE_");
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
public final void testGetGrantedAuthoritiesCombination1() {
|
||||
String[] roles = { "Role1", "Role2", "role_Role3" };
|
||||
String[] expectedGas = { "ROLE_ROLE1", "ROLE_ROLE2", "ROLE_ROLE3" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setAddPrefixIfAlreadyExisting(false);
|
||||
mapper.setConvertAttributeToUpperCase(true);
|
||||
mapper.setAttributePrefix("ROLE_");
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
public final void testGetGrantedAuthoritiesCombination1() {
|
||||
String[] roles = { "Role1", "Role2", "role_Role3" };
|
||||
String[] expectedGas = { "ROLE_ROLE1", "ROLE_ROLE2", "ROLE_ROLE3" };
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = getDefaultMapper();
|
||||
mapper.setAddPrefixIfAlreadyExisting(false);
|
||||
mapper.setConvertAttributeToUpperCase(true);
|
||||
mapper.setAttributePrefix("ROLE_");
|
||||
testGetGrantedAuthorities(mapper, roles, expectedGas);
|
||||
}
|
||||
|
||||
private void testGetGrantedAuthorities(SimpleAttributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
|
||||
GrantedAuthority[] result = mapper.getGrantedAuthorities(roles);
|
||||
Collection resultColl = new ArrayList(result.length);
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
resultColl.add(result[i].getAuthority());
|
||||
}
|
||||
Collection expectedColl = Arrays.asList(expectedGas);
|
||||
assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
|
||||
.containsAll(resultColl)
|
||||
&& resultColl.containsAll(expectedColl));
|
||||
}
|
||||
private void testGetGrantedAuthorities(SimpleAttributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
|
||||
List<GrantedAuthority> result = mapper.getGrantedAuthorities(Arrays.asList(roles));
|
||||
Collection resultColl = new ArrayList(result.size());
|
||||
for (int i = 0; i < result.size(); i++) {
|
||||
resultColl.add(result.get(i).getAuthority());
|
||||
}
|
||||
Collection expectedColl = Arrays.asList(expectedGas);
|
||||
assertTrue("Role collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
|
||||
.containsAll(resultColl)
|
||||
&& resultColl.containsAll(expectedColl));
|
||||
}
|
||||
|
||||
private SimpleAttributes2GrantedAuthoritiesMapper getDefaultMapper() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.setAttributePrefix("");
|
||||
mapper.setConvertAttributeToLowerCase(false);
|
||||
mapper.setConvertAttributeToUpperCase(false);
|
||||
mapper.setAddPrefixIfAlreadyExisting(false);
|
||||
return mapper;
|
||||
}
|
||||
private SimpleAttributes2GrantedAuthoritiesMapper getDefaultMapper() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
mapper.setAttributePrefix("");
|
||||
mapper.setConvertAttributeToLowerCase(false);
|
||||
mapper.setConvertAttributeToUpperCase(false);
|
||||
mapper.setAddPrefixIfAlreadyExisting(false);
|
||||
return mapper;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+21
-21
@@ -38,15 +38,15 @@ public class LdapProviderBeanDefinitionParserTests {
|
||||
Authentication auth = provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword"));
|
||||
LdapUserDetailsImpl ben = (LdapUserDetailsImpl) auth.getPrincipal();
|
||||
|
||||
assertEquals(3, ben.getAuthorities().length);
|
||||
assertEquals(3, ben.getAuthorities().size());
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = SecurityConfigurationException.class)
|
||||
public void missingServerEltCausesConfigException() {
|
||||
setContext("<ldap-authentication-provider />");
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void supportsPasswordComparisonAuthentication() {
|
||||
setContext("<ldap-server /> " +
|
||||
@@ -54,10 +54,10 @@ public class LdapProviderBeanDefinitionParserTests {
|
||||
" <password-compare />" +
|
||||
"</ldap-authentication-provider>");
|
||||
LdapAuthenticationProvider provider = getProvider();
|
||||
provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword"));
|
||||
}
|
||||
|
||||
|
||||
provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void supportsPasswordComparisonAuthenticationWithHashAttribute() {
|
||||
setContext("<ldap-server /> " +
|
||||
@@ -65,27 +65,27 @@ public class LdapProviderBeanDefinitionParserTests {
|
||||
" <password-compare password-attribute='uid' hash='plaintext'/>" +
|
||||
"</ldap-authentication-provider>");
|
||||
LdapAuthenticationProvider provider = getProvider();
|
||||
provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben"));
|
||||
}
|
||||
|
||||
provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsPasswordComparisonAuthenticationWithPasswordEncoder() {
|
||||
setContext("<ldap-server /> " +
|
||||
"<ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>" +
|
||||
" <password-compare password-attribute='uid'>" +
|
||||
" <password-encoder hash='plaintext'/>" +
|
||||
" </password-compare>" +
|
||||
"</ldap-authentication-provider>");
|
||||
"<ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>" +
|
||||
" <password-compare password-attribute='uid'>" +
|
||||
" <password-encoder hash='plaintext'/>" +
|
||||
" </password-compare>" +
|
||||
"</ldap-authentication-provider>");
|
||||
LdapAuthenticationProvider provider = getProvider();
|
||||
provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben"));
|
||||
}
|
||||
provider.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsNonStandardServerId() {
|
||||
setContext("<ldap-server id='myServer'/> " +
|
||||
"<ldap-authentication-provider />");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void inetOrgContextMapperIsSupported() throws Exception {
|
||||
setContext(
|
||||
@@ -93,8 +93,8 @@ public class LdapProviderBeanDefinitionParserTests {
|
||||
"<ldap-authentication-provider user-details-class='inetOrgPerson'/>");
|
||||
LdapAuthenticationProvider provider = getProvider();
|
||||
assertTrue(FieldUtils.getFieldValue(provider, "userDetailsContextMapper") instanceof InetOrgPersonContextMapper);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void setContext(String context) {
|
||||
appCtx = new InMemoryXmlApplicationContext(context);
|
||||
}
|
||||
@@ -106,5 +106,5 @@ public class LdapProviderBeanDefinitionParserTests {
|
||||
|
||||
LdapAuthenticationProvider provider = (LdapAuthenticationProvider) authManager.getProviders().get(0);
|
||||
return provider;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+253
-281
@@ -18,11 +18,9 @@ package org.springframework.security.context;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.MockFilterConfig;
|
||||
|
||||
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
|
||||
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
@@ -44,342 +42,316 @@ import javax.servlet.ServletResponse;
|
||||
* 02:04:47Z benalex $
|
||||
*/
|
||||
public class HttpSessionContextIntegrationFilterTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
// Build an Authentication object we simulate came from HttpSession
|
||||
private UsernamePasswordAuthenticationToken sessionPrincipal = new UsernamePasswordAuthenticationToken(
|
||||
"someone",
|
||||
"password",
|
||||
AuthorityUtils.createAuthorityList("SOME_ROLE"));
|
||||
|
||||
public HttpSessionContextIntegrationFilterTests() {
|
||||
}
|
||||
|
||||
public HttpSessionContextIntegrationFilterTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
private static void executeFilterInContainerSimulator(
|
||||
FilterConfig filterConfig, Filter filter, ServletRequest request,
|
||||
ServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
filter.init(filterConfig);
|
||||
filter.doFilter(request, response, filterChain);
|
||||
filter.destroy();
|
||||
}
|
||||
|
||||
private static void executeFilterInContainerSimulator(
|
||||
FilterConfig filterConfig, Filter filter, ServletRequest request,
|
||||
ServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
filter.init(filterConfig);
|
||||
filter.doFilter(request, response, filterChain);
|
||||
filter.destroy();
|
||||
}
|
||||
public void testDetectsIncompatibleSessionProperties() throws Exception {
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
|
||||
public void testDetectsIncompatibleSessionProperties() throws Exception {
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
try {
|
||||
filter.setAllowSessionCreation(false);
|
||||
filter.setForceEagerSessionCreation(true);
|
||||
filter.afterPropertiesSet();
|
||||
fail("Shown have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
filter.setAllowSessionCreation(false);
|
||||
filter.setForceEagerSessionCreation(true);
|
||||
filter.afterPropertiesSet();
|
||||
fail("Shown have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
filter.setAllowSessionCreation(true);
|
||||
filter.afterPropertiesSet();
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
filter.setAllowSessionCreation(true);
|
||||
filter.afterPropertiesSet();
|
||||
assertTrue(true);
|
||||
}
|
||||
public void testDetectsMissingOrInvalidContext() throws Exception {
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
|
||||
public void testDetectsMissingOrInvalidContext() throws Exception {
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
try {
|
||||
filter.setContextClass(null);
|
||||
filter.afterPropertiesSet();
|
||||
fail("Shown have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
filter.setContextClass(null);
|
||||
filter.afterPropertiesSet();
|
||||
fail("Shown have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
try {
|
||||
filter.setContextClass(Integer.class);
|
||||
assertEquals(Integer.class, filter.getContextClass());
|
||||
filter.afterPropertiesSet();
|
||||
fail("Shown have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
filter.setContextClass(Integer.class);
|
||||
assertEquals(Integer.class, filter.getContextClass());
|
||||
filter.afterPropertiesSet();
|
||||
fail("Shown have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
public void testExceptionWithinFilterChainStillClearsSecurityContextHolder() throws Exception {
|
||||
|
||||
public void testExceptionWithinFilterChainStillClearsSecurityContextHolder() throws Exception {
|
||||
// Build an Authentication object we simulate came from HttpSession
|
||||
PrincipalSpringSecurityUserToken sessionPrincipal = new PrincipalSpringSecurityUserToken(
|
||||
"key",
|
||||
"someone",
|
||||
"password",
|
||||
new GrantedAuthority[] { new GrantedAuthorityImpl("SOME_ROLE") },
|
||||
null);
|
||||
// Build a Context to store in HttpSession (simulating prior request)
|
||||
SecurityContext sc = new SecurityContextImpl();
|
||||
sc.setAuthentication(sessionPrincipal);
|
||||
|
||||
// Build a Context to store in HttpSession (simulating prior request)
|
||||
SecurityContext sc = new SecurityContextImpl();
|
||||
sc.setAuthentication(sessionPrincipal);
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession().setAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
|
||||
sc);
|
||||
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession().setAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
|
||||
sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(sessionPrincipal, null,
|
||||
new IOException());
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(sessionPrincipal, null,
|
||||
new IOException());
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
// Execute filter
|
||||
try {
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
|
||||
request, response, chain);
|
||||
fail("We should have received the IOException thrown inside the filter chain here");
|
||||
} catch (IOException ioe) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
// Execute filter
|
||||
try {
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
|
||||
request, response, chain);
|
||||
fail("We should have received the IOException thrown inside the filter chain here");
|
||||
} catch (IOException ioe) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
// Check the SecurityContextHolder is null, even though an exception was
|
||||
// thrown during chain
|
||||
assertEquals(new SecurityContextImpl(), SecurityContextHolder.getContext());
|
||||
assertNull("Should have cleared FILTER_APPLIED",
|
||||
// Check the SecurityContextHolder is null, even though an exception was
|
||||
// thrown during chain
|
||||
assertEquals(new SecurityContextImpl(), SecurityContextHolder.getContext());
|
||||
assertNull("Should have cleared FILTER_APPLIED",
|
||||
request.getAttribute(HttpSessionContextIntegrationFilter.FILTER_APPLIED));
|
||||
}
|
||||
}
|
||||
|
||||
public void testExistingContextContentsCopiedIntoContextHolderFromSessionAndChangesToContextCopiedBackToSession()
|
||||
throws Exception {
|
||||
// Build an Authentication object we simulate came from HttpSession
|
||||
PrincipalSpringSecurityUserToken sessionPrincipal = new PrincipalSpringSecurityUserToken(
|
||||
"key",
|
||||
"someone",
|
||||
"password",
|
||||
new GrantedAuthority[] { new GrantedAuthorityImpl("SOME_ROLE") },
|
||||
null);
|
||||
public void testExistingContextContentsCopiedIntoContextHolderFromSessionAndChangesToContextCopiedBackToSession()
|
||||
throws Exception {
|
||||
|
||||
// Build an Authentication object we simulate our Authentication changed
|
||||
// it to
|
||||
PrincipalSpringSecurityUserToken updatedPrincipal = new PrincipalSpringSecurityUserToken(
|
||||
"key", "someone", "password",
|
||||
new GrantedAuthority[] { new GrantedAuthorityImpl(
|
||||
"SOME_DIFFERENT_ROLE") }, null);
|
||||
// Build an Authentication object we simulate came from HttpSession
|
||||
UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
|
||||
"someone",
|
||||
"password",
|
||||
AuthorityUtils.createAuthorityList("SOME_DIFFERENT_ROLE"));
|
||||
|
||||
// Build a Context to store in HttpSession (simulating prior request)
|
||||
SecurityContext sc = new SecurityContextImpl();
|
||||
sc.setAuthentication(sessionPrincipal);
|
||||
// Build a Context to store in HttpSession (simulating prior request)
|
||||
SecurityContext sc = new SecurityContextImpl();
|
||||
sc.setAuthentication(sessionPrincipal);
|
||||
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession().setAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
|
||||
sc);
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession().setAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
|
||||
sc);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(sessionPrincipal,
|
||||
updatedPrincipal, null);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(sessionPrincipal,
|
||||
updatedPrincipal, null);
|
||||
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
|
||||
request, response, chain);
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
|
||||
request, response, chain);
|
||||
|
||||
// Obtain new/update Authentication from HttpSession
|
||||
SecurityContext context = (SecurityContext) request.getSession().getAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
|
||||
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
|
||||
}
|
||||
// Obtain new/update Authentication from HttpSession
|
||||
SecurityContext context = (SecurityContext) request.getSession().getAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
|
||||
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
|
||||
}
|
||||
|
||||
public void testHttpSessionCreatedWhenContextHolderChanges() throws Exception {
|
||||
// Build an Authentication object we simulate our Authentication changed it to
|
||||
PrincipalSpringSecurityUserToken updatedPrincipal = new PrincipalSpringSecurityUserToken(
|
||||
"key", "someone", "password",
|
||||
new GrantedAuthority[] { new GrantedAuthorityImpl(
|
||||
"SOME_DIFFERENT_ROLE") }, null);
|
||||
public void testHttpSessionCreatedWhenContextHolderChanges() throws Exception {
|
||||
// Build an Authentication object we simulate our Authentication changed it to
|
||||
UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
|
||||
"someone",
|
||||
"password",
|
||||
AuthorityUtils.createAuthorityList("SOME_ROLE"));
|
||||
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
|
||||
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
// don't call afterPropertiesSet to test case when Spring filter.afterPropertiesSet(); isn't called
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
// don't call afterPropertiesSet to test case when Spring filter.afterPropertiesSet(); isn't called
|
||||
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
|
||||
|
||||
// Obtain new/updated Authentication from HttpSession
|
||||
SecurityContext context = (SecurityContext) request.getSession(false).getAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
|
||||
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
|
||||
}
|
||||
// Obtain new/updated Authentication from HttpSession
|
||||
SecurityContext context = (SecurityContext) request.getSession(false).getAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
|
||||
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
|
||||
}
|
||||
|
||||
public void testHttpSessionEagerlyCreatedWhenDirected() throws Exception {
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(null, null, null);
|
||||
public void testHttpSessionEagerlyCreatedWhenDirected() throws Exception {
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(null, null, null);
|
||||
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.setForceEagerSessionCreation(true); // non-default
|
||||
filter.afterPropertiesSet();
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.setForceEagerSessionCreation(true); // non-default
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
|
||||
request, response, chain);
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
|
||||
request, response, chain);
|
||||
|
||||
// Check the session is not null
|
||||
assertNotNull(request.getSession(false));
|
||||
}
|
||||
// Check the session is not null
|
||||
assertNotNull(request.getSession(false));
|
||||
}
|
||||
|
||||
public void testHttpSessionNotCreatedUnlessContextHolderChanges() throws Exception {
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(null, null, null);
|
||||
public void testHttpSessionNotCreatedUnlessContextHolderChanges() throws Exception {
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(null, null, null);
|
||||
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
|
||||
request, response, chain);
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
|
||||
request, response, chain);
|
||||
|
||||
// Check the session is null
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
// Check the session is null
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
|
||||
public void testHttpSessionWithNonContextInWellKnownLocationIsOverwritten() throws Exception {
|
||||
// Build an Authentication object we simulate our Authentication changed
|
||||
// it to
|
||||
PrincipalSpringSecurityUserToken updatedPrincipal = new PrincipalSpringSecurityUserToken(
|
||||
"key", "someone", "password",
|
||||
new GrantedAuthority[] { new GrantedAuthorityImpl(
|
||||
"SOME_DIFFERENT_ROLE") }, null);
|
||||
public void testHttpSessionWithNonContextInWellKnownLocationIsOverwritten() throws Exception {
|
||||
// Build an Authentication object we simulate our Authentication changed it to
|
||||
UsernamePasswordAuthenticationToken updatedPrincipal = new UsernamePasswordAuthenticationToken(
|
||||
"someone",
|
||||
"password",
|
||||
AuthorityUtils.createAuthorityList("SOME_DIFFERENT_ROLE"));
|
||||
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession().setAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
|
||||
"NOT_A_CONTEXT_OBJECT");
|
||||
// Build a mock request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession().setAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
|
||||
"NOT_A_CONTEXT_OBJECT");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(null, updatedPrincipal, null);
|
||||
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
|
||||
|
||||
// Obtain new/update Authentication from HttpSession
|
||||
SecurityContext context = (SecurityContext) request.getSession().getAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
|
||||
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
|
||||
}
|
||||
// Obtain new/update Authentication from HttpSession
|
||||
SecurityContext context = (SecurityContext) request.getSession().getAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
|
||||
assertEquals(updatedPrincipal, ((SecurityContext) context).getAuthentication());
|
||||
}
|
||||
|
||||
public void testConcurrentThreadsLazilyChangeFilterAppliedValueToTrue() throws Exception {
|
||||
PrincipalSpringSecurityUserToken sessionPrincipal = new PrincipalSpringSecurityUserToken(
|
||||
"key",
|
||||
"someone",
|
||||
"password",
|
||||
new GrantedAuthority[] { new GrantedAuthorityImpl("SOME_ROLE") },
|
||||
null);
|
||||
public void testConcurrentThreadsLazilyChangeFilterAppliedValueToTrue() throws Exception {
|
||||
// Build a Context to store in HttpSession (simulating prior request)
|
||||
SecurityContext sc = new SecurityContextImpl();
|
||||
sc.setAuthentication(sessionPrincipal);
|
||||
|
||||
// Build a Context to store in HttpSession (simulating prior request)
|
||||
SecurityContext sc = new SecurityContextImpl();
|
||||
sc.setAuthentication(sessionPrincipal);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession().setAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
|
||||
sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession().setAttribute(
|
||||
HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY,
|
||||
sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Prepare filter
|
||||
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
|
||||
filter.setContextClass(SecurityContextImpl.class);
|
||||
filter.afterPropertiesSet();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
ThreadRunner runner = new ThreadRunner(request, response, filter,
|
||||
new MockFilterChain(sessionPrincipal, null, null));
|
||||
runner.start();
|
||||
}
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
ThreadRunner runner = new ThreadRunner(request, response, filter,
|
||||
new MockFilterChain(sessionPrincipal, null, null));
|
||||
runner.start();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
private class MockFilterChain extends TestCase implements FilterChain {
|
||||
private Authentication changeContextHolder;
|
||||
private Authentication expectedOnContextHolder;
|
||||
private IOException toThrowDuringChain;
|
||||
|
||||
private class MockFilterChain extends TestCase implements FilterChain {
|
||||
private Authentication changeContextHolder;
|
||||
private Authentication expectedOnContextHolder;
|
||||
private IOException toThrowDuringChain;
|
||||
public MockFilterChain(Authentication expectedOnContextHolder,
|
||||
Authentication changeContextHolder,
|
||||
IOException toThrowDuringChain) {
|
||||
this.expectedOnContextHolder = expectedOnContextHolder;
|
||||
this.changeContextHolder = changeContextHolder;
|
||||
this.toThrowDuringChain = toThrowDuringChain;
|
||||
}
|
||||
|
||||
public MockFilterChain(Authentication expectedOnContextHolder,
|
||||
Authentication changeContextHolder,
|
||||
IOException toThrowDuringChain) {
|
||||
this.expectedOnContextHolder = expectedOnContextHolder;
|
||||
this.changeContextHolder = changeContextHolder;
|
||||
this.toThrowDuringChain = toThrowDuringChain;
|
||||
}
|
||||
public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException, ServletException {
|
||||
if (expectedOnContextHolder != null) {
|
||||
assertEquals(expectedOnContextHolder, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException, ServletException {
|
||||
if (expectedOnContextHolder != null) {
|
||||
assertEquals(expectedOnContextHolder, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
if (changeContextHolder != null) {
|
||||
SecurityContext sc = SecurityContextHolder.getContext();
|
||||
sc.setAuthentication(changeContextHolder);
|
||||
SecurityContextHolder.setContext(sc);
|
||||
}
|
||||
|
||||
if (changeContextHolder != null) {
|
||||
SecurityContext sc = SecurityContextHolder.getContext();
|
||||
sc.setAuthentication(changeContextHolder);
|
||||
SecurityContextHolder.setContext(sc);
|
||||
}
|
||||
if (toThrowDuringChain != null) {
|
||||
throw toThrowDuringChain;
|
||||
}
|
||||
|
||||
if (toThrowDuringChain != null) {
|
||||
throw toThrowDuringChain;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
private static class ThreadRunner extends Thread {
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private HttpSessionContextIntegrationFilter filter;
|
||||
private MockFilterChain chain;
|
||||
|
||||
private static class ThreadRunner extends Thread {
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private HttpSessionContextIntegrationFilter filter;
|
||||
private MockFilterChain chain;
|
||||
public ThreadRunner(MockHttpServletRequest request,
|
||||
MockHttpServletResponse response,
|
||||
HttpSessionContextIntegrationFilter filter,
|
||||
MockFilterChain chain) {
|
||||
this.request = request;
|
||||
this.response = response;
|
||||
this.filter = filter;
|
||||
this.chain = chain;
|
||||
}
|
||||
|
||||
public ThreadRunner(MockHttpServletRequest request,
|
||||
MockHttpServletResponse response,
|
||||
HttpSessionContextIntegrationFilter filter,
|
||||
MockFilterChain chain) {
|
||||
this.request = request;
|
||||
this.response = response;
|
||||
this.filter = filter;
|
||||
this.chain = chain;
|
||||
}
|
||||
public void run() {
|
||||
try {
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
// Execute filter
|
||||
executeFilterInContainerSimulator(new MockFilterConfig(), filter, request, response, chain);
|
||||
// Check the session is not null
|
||||
assertNotNull(request.getSession(false));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// Check the session is not null
|
||||
assertNotNull(request.getSession(false));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+26
-25
@@ -24,6 +24,7 @@ import org.springframework.ldap.core.DirContextAdapter;
|
||||
import org.springframework.ldap.core.DistinguishedName;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
@@ -53,9 +54,9 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
|
||||
|
||||
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=notfound"));
|
||||
|
||||
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "notfound");
|
||||
assertEquals(1, authorities.length);
|
||||
assertEquals("ROLE_USER", authorities[0].getAuthority());
|
||||
List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notfound");
|
||||
assertEquals(1, authorities.size());
|
||||
assertEquals("ROLE_USER", authorities.get(0).getAuthority());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -69,13 +70,13 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
|
||||
|
||||
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
|
||||
|
||||
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "ben");
|
||||
List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "ben");
|
||||
|
||||
assertEquals("Should have 2 roles", 2, authorities.length);
|
||||
assertEquals("Should have 2 roles", 2, authorities.size());
|
||||
|
||||
Set roles = new HashSet();
|
||||
roles.add(authorities[0].toString());
|
||||
roles.add(authorities[1].toString());
|
||||
roles.add(authorities.get(0).toString());
|
||||
roles.add(authorities.get(1).toString());
|
||||
assertTrue(roles.contains("ROLE_DEVELOPER"));
|
||||
assertTrue(roles.contains("ROLE_MANAGER"));
|
||||
}
|
||||
@@ -88,10 +89,10 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
|
||||
|
||||
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
|
||||
|
||||
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "manager");
|
||||
List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "manager");
|
||||
|
||||
assertEquals("Should have 1 role", 1, authorities.length);
|
||||
assertEquals("ROLE_MANAGER", authorities[0].getAuthority());
|
||||
assertEquals("Should have 1 role", 1, authorities.size());
|
||||
assertEquals("ROLE_MANAGER", authorities.get(0).getAuthority());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -101,12 +102,12 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
|
||||
|
||||
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
|
||||
|
||||
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "manager");
|
||||
List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "manager");
|
||||
|
||||
assertEquals("Should have 2 roles", 2, authorities.length);
|
||||
assertEquals("Should have 2 roles", 2, authorities.size());
|
||||
Set roles = new HashSet(2);
|
||||
roles.add(authorities[0].getAuthority());
|
||||
roles.add(authorities[1].getAuthority());
|
||||
roles.add(authorities.get(0).getAuthority());
|
||||
roles.add(authorities.get(1).getAuthority());
|
||||
assertTrue(roles.contains("ROLE_MANAGER"));
|
||||
assertTrue(roles.contains("ROLE_DEVELOPER"));
|
||||
}
|
||||
@@ -119,13 +120,13 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
|
||||
|
||||
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
|
||||
|
||||
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "manager");
|
||||
List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "manager");
|
||||
|
||||
assertEquals("Should have 3 roles", 3, authorities.length);
|
||||
assertEquals("Should have 3 roles", 3, authorities.size());
|
||||
Set roles = new HashSet(3);
|
||||
roles.add(authorities[0].getAuthority());
|
||||
roles.add(authorities[1].getAuthority());
|
||||
roles.add(authorities[2].getAuthority());
|
||||
roles.add(authorities.get(0).getAuthority());
|
||||
roles.add(authorities.get(1).getAuthority());
|
||||
roles.add(authorities.get(2).getAuthority());
|
||||
assertTrue(roles.contains("ROLE_MANAGER"));
|
||||
assertTrue(roles.contains("ROLE_DEVELOPER"));
|
||||
assertTrue(roles.contains("ROLE_SUBMANAGER"));
|
||||
@@ -134,15 +135,15 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio
|
||||
@Test
|
||||
public void testUserDnWithEscapedCharacterParameterReturnsExpectedRoles() {
|
||||
populator.setGroupRoleAttribute("ou");
|
||||
populator.setConvertToUpperCase(true);
|
||||
populator.setConvertToUpperCase(true);
|
||||
populator.setGroupSearchFilter("(member={0})");
|
||||
|
||||
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"));
|
||||
|
||||
GrantedAuthority[] authorities = populator.getGrantedAuthorities(ctx, "notused");
|
||||
List<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notused");
|
||||
|
||||
assertEquals("Should have 1 role", 1, authorities.size());
|
||||
assertEquals("ROLE_MANAGER", authorities.get(0).getAuthority());
|
||||
}
|
||||
|
||||
assertEquals("Should have 1 role", 1, authorities.length);
|
||||
assertEquals("ROLE_MANAGER", authorities[0].getAuthority());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+5
-3
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
+24
-37
@@ -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;
|
||||
|
||||
+9
-11
@@ -25,7 +25,9 @@ import org.springframework.security.AccountStatusException;
|
||||
import org.springframework.security.concurrent.ConcurrentSessionControllerImpl;
|
||||
import org.springframework.security.concurrent.NullConcurrentSessionController;
|
||||
import org.springframework.security.concurrent.ConcurrentLoginException;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Vector;
|
||||
@@ -55,8 +57,7 @@ public class ProviderManagerTests {
|
||||
|
||||
@Test
|
||||
public void authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject() throws Exception {
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password","ROLE_ONE","ROLE_TWO");
|
||||
|
||||
ProviderManager mgr = makeProviderManager();
|
||||
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
|
||||
@@ -70,15 +71,12 @@ public class ProviderManagerTests {
|
||||
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
|
||||
assertEquals("Test", castResult.getPrincipal());
|
||||
assertEquals("Password", castResult.getCredentials());
|
||||
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
|
||||
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
|
||||
assertEquals(AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO"), castResult.getAuthorities());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticationSuccessWhenFirstProviderReturnsNullButSecondAuthenticates() {
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
|
||||
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password","ROLE_ONE","ROLE_TWO");
|
||||
ProviderManager mgr = makeProviderManagerWithMockProviderWhichReturnsNullInList();
|
||||
mgr.setApplicationEventPublisher(new MockApplicationEventPublisher(true));
|
||||
|
||||
@@ -91,8 +89,8 @@ public class ProviderManagerTests {
|
||||
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
|
||||
assertEquals("Test", castResult.getPrincipal());
|
||||
assertEquals("Password", castResult.getCredentials());
|
||||
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
|
||||
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
|
||||
assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
|
||||
assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -193,7 +191,7 @@ public class ProviderManagerTests {
|
||||
}
|
||||
|
||||
private TestingAuthenticationToken createAuthenticationToken() {
|
||||
return new TestingAuthenticationToken("name", "password", new GrantedAuthorityImpl[0]);
|
||||
return new TestingAuthenticationToken("name", "password", new ArrayList<GrantedAuthority>(0));
|
||||
}
|
||||
|
||||
private ProviderManager makeProviderManager() throws Exception {
|
||||
@@ -221,7 +219,7 @@ public class ProviderManagerTests {
|
||||
|
||||
return mgr;
|
||||
}
|
||||
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockProvider implements AuthenticationProvider {
|
||||
|
||||
+4
-29
@@ -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() {
|
||||
|
||||
+5
-4
@@ -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() {
|
||||
|
||||
+8
-26
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
+2
-3
@@ -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
|
||||
|
||||
+12
-12
@@ -69,18 +69,18 @@ public class DaoAuthenticationProviderTests extends TestCase {
|
||||
}
|
||||
|
||||
public void testReceivedBadCredentialsWhenCredentialsNotProvided() {
|
||||
// Test related to SEC-434
|
||||
// Test related to SEC-434
|
||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||
provider.setUserDetailsService(new MockAuthenticationDaoUserrod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null);
|
||||
try {
|
||||
provider.authenticate(authenticationToken);
|
||||
fail("Expected BadCredenialsException");
|
||||
} catch (BadCredentialsException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null);
|
||||
try {
|
||||
provider.authenticate(authenticationToken);
|
||||
fail("Expected BadCredenialsException");
|
||||
} catch (BadCredentialsException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testAuthenticateFailsIfAccountExpired() {
|
||||
@@ -263,8 +263,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
|
||||
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
|
||||
assertEquals(User.class, castResult.getPrincipal().getClass());
|
||||
assertEquals("koala", castResult.getCredentials());
|
||||
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
|
||||
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
|
||||
assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
|
||||
assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
|
||||
assertEquals("192.168.0.1", castResult.getDetails());
|
||||
}
|
||||
|
||||
@@ -313,8 +313,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
|
||||
|
||||
// We expect original credentials user submitted to be returned
|
||||
assertEquals("koala", castResult.getCredentials());
|
||||
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
|
||||
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
|
||||
assertEquals("ROLE_ONE", castResult.getAuthorities().get(0).getAuthority());
|
||||
assertEquals("ROLE_TWO", castResult.getAuthorities().get(1).getAuthority());
|
||||
}
|
||||
|
||||
public void testAuthenticatesWithForcePrincipalAsString() {
|
||||
|
||||
+23
-29
@@ -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() {
|
||||
|
||||
+9
-7
@@ -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() {
|
||||
|
||||
+35
-36
@@ -9,49 +9,48 @@ import java.util.Collection;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author TSARDD
|
||||
* @since 18-okt-2007
|
||||
*/
|
||||
public class PreAuthenticatedAuthenticationTokenTests extends TestCase {
|
||||
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
Object details = "dummyDetails";
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
|
||||
token.setDetails(details);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertEquals(details, token.getDetails());
|
||||
assertNull(token.getAuthorities());
|
||||
}
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
Object details = "dummyDetails";
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
|
||||
token.setDetails(details);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertEquals(details, token.getDetails());
|
||||
assertNull(token.getAuthorities());
|
||||
}
|
||||
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertNull(token.getDetails());
|
||||
assertNull(token.getAuthorities());
|
||||
}
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertNull(token.getDetails());
|
||||
assertNull(token.getAuthorities());
|
||||
}
|
||||
|
||||
public void testPreAuthenticatedAuthenticationTokenResponse() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1") };
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials, gas);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertNull(token.getDetails());
|
||||
assertNotNull(token.getAuthorities());
|
||||
Collection expectedColl = Arrays.asList(gas);
|
||||
Collection resultColl = Arrays.asList(token.getAuthorities());
|
||||
assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
|
||||
.containsAll(resultColl)
|
||||
&& resultColl.containsAll(expectedColl));
|
||||
public void testPreAuthenticatedAuthenticationTokenResponse() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1") };
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials, gas);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertNull(token.getDetails());
|
||||
assertNotNull(token.getAuthorities());
|
||||
Collection expectedColl = Arrays.asList(gas);
|
||||
Collection resultColl = token.getAuthorities();
|
||||
assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl,
|
||||
expectedColl.containsAll(resultColl) && resultColl.containsAll(expectedColl));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+57
-60
@@ -1,80 +1,77 @@
|
||||
package org.springframework.security.providers.preauth;
|
||||
|
||||
import org.springframework.security.GrantedAuthoritiesContainer;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.userdetails.UserDetails;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.GrantedAuthoritiesContainer;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.userdetails.UserDetails;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author TSARDD
|
||||
* @since 18-okt-2007
|
||||
*/
|
||||
public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests extends TestCase {
|
||||
public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
|
||||
|
||||
public final void testGetUserDetailsInvalidType() {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
|
||||
token.setDetails(new Object());
|
||||
try {
|
||||
svc.loadUserDetails(token);
|
||||
fail("Expected exception didn't occur");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testGetUserDetailsInvalidType() {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
|
||||
token.setDetails(new Object());
|
||||
svc.loadUserDetails(token);
|
||||
}
|
||||
|
||||
public final void testGetUserDetailsNoDetails() {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
|
||||
token.setDetails(null);
|
||||
try {
|
||||
svc.loadUserDetails(token);
|
||||
fail("Expected exception didn't occur");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testGetUserDetailsNoDetails() {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
|
||||
token.setDetails(null);
|
||||
svc.loadUserDetails(token);
|
||||
}
|
||||
|
||||
public final void testGetUserDetailsEmptyAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
final GrantedAuthority[] gas = new GrantedAuthority[] {};
|
||||
testGetUserDetails(userName, gas);
|
||||
}
|
||||
@Test
|
||||
public void testGetUserDetailsEmptyAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
testGetUserDetails(userName, AuthorityUtils.NO_AUTHORITIES);
|
||||
}
|
||||
|
||||
public final void testGetUserDetailsWithAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
final GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1"), new GrantedAuthorityImpl("Role2") };
|
||||
testGetUserDetails(userName, gas);
|
||||
}
|
||||
@Test
|
||||
public void testGetUserDetailsWithAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
testGetUserDetails(userName, AuthorityUtils.createAuthorityList("Role1", "Role2"));
|
||||
}
|
||||
|
||||
private void testGetUserDetails(final String userName, final GrantedAuthority[] gas) {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userName, "dummy");
|
||||
token.setDetails(new GrantedAuthoritiesContainer() {
|
||||
public GrantedAuthority[] getGrantedAuthorities() {
|
||||
return gas;
|
||||
}
|
||||
});
|
||||
UserDetails ud = svc.loadUserDetails(token);
|
||||
assertTrue(ud.isAccountNonExpired());
|
||||
assertTrue(ud.isAccountNonLocked());
|
||||
assertTrue(ud.isCredentialsNonExpired());
|
||||
assertTrue(ud.isEnabled());
|
||||
assertEquals(ud.getUsername(), userName);
|
||||
private void testGetUserDetails(final String userName, final List<GrantedAuthority> gas) {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userName, "dummy");
|
||||
token.setDetails(new GrantedAuthoritiesContainer() {
|
||||
public List<GrantedAuthority> getGrantedAuthorities() {
|
||||
return gas;
|
||||
}
|
||||
});
|
||||
UserDetails ud = svc.loadUserDetails(token);
|
||||
assertTrue(ud.isAccountNonExpired());
|
||||
assertTrue(ud.isAccountNonLocked());
|
||||
assertTrue(ud.isCredentialsNonExpired());
|
||||
assertTrue(ud.isEnabled());
|
||||
assertEquals(ud.getUsername(), userName);
|
||||
|
||||
//Password is not saved by
|
||||
// PreAuthenticatedGrantedAuthoritiesUserDetailsService
|
||||
//assertEquals(ud.getPassword(),password);
|
||||
//Password is not saved by
|
||||
// PreAuthenticatedGrantedAuthoritiesUserDetailsService
|
||||
//assertEquals(ud.getPassword(),password);
|
||||
|
||||
Collection expectedColl = Arrays.asList(gas);
|
||||
Collection resultColl = Arrays.asList(ud.getAuthorities());
|
||||
assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
|
||||
.containsAll(resultColl)
|
||||
&& resultColl.containsAll(expectedColl));
|
||||
}
|
||||
Collection expectedColl = Arrays.asList(gas);
|
||||
Collection resultColl = Arrays.asList(ud.getAuthorities());
|
||||
assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl
|
||||
.containsAll(resultColl)
|
||||
&& resultColl.containsAll(expectedColl));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-2
@@ -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 {
|
||||
|
||||
+1
-1
@@ -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() {
|
||||
|
||||
+1
-2
@@ -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
|
||||
|
||||
+2
-13
@@ -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")});
|
||||
|
||||
-131
@@ -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")});
|
||||
}
|
||||
}
|
||||
}
|
||||
-52
@@ -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());
|
||||
}
|
||||
}
|
||||
-89
@@ -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));
|
||||
}
|
||||
}
|
||||
-146
@@ -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());
|
||||
|
||||
+44
-47
@@ -1,68 +1,65 @@
|
||||
package org.springframework.security.ui.preauth;
|
||||
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
|
||||
/**
|
||||
* @author TSARDD
|
||||
*/
|
||||
public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests extends TestCase {
|
||||
public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
|
||||
List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1", "Role2");
|
||||
|
||||
public final void testToString() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}));
|
||||
GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1"), new GrantedAuthorityImpl("Role2") };
|
||||
details.setGrantedAuthorities(gas);
|
||||
String toString = details.toString();
|
||||
assertTrue("toString should contain Role1", toString.contains("Role1"));
|
||||
assertTrue("toString should contain Role2", toString.contains("Role2"));
|
||||
}
|
||||
@Test
|
||||
public void testToString() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}));
|
||||
details.setGrantedAuthorities(gas);
|
||||
String toString = details.toString();
|
||||
assertTrue("toString should contain Role1", toString.contains("Role1"));
|
||||
assertTrue("toString should contain Role2", toString.contains("Role2"));
|
||||
}
|
||||
|
||||
public final void testGetSetPreAuthenticatedGrantedAuthorities() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}));
|
||||
GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1"), new GrantedAuthorityImpl("Role2") };
|
||||
Collection expectedGas = Arrays.asList(gas);
|
||||
@Test
|
||||
public void testGetSetPreAuthenticatedGrantedAuthorities() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}));
|
||||
|
||||
details.setGrantedAuthorities(gas);
|
||||
Collection returnedGas = Arrays.asList(details.getGrantedAuthorities());
|
||||
assertTrue("Collections do not contain same elements; expected: " + expectedGas + ", returned: " + returnedGas,
|
||||
expectedGas.containsAll(returnedGas) && returnedGas.containsAll(expectedGas));
|
||||
}
|
||||
Collection expectedGas = Arrays.asList(gas);
|
||||
|
||||
public final void testGetWithoutSetPreAuthenticatedGrantedAuthorities() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}));
|
||||
try {
|
||||
GrantedAuthority[] gas = details.getGrantedAuthorities();
|
||||
fail("Expected exception didn't occur");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
} catch (Exception unexpected) {
|
||||
fail("Unexpected exception: " + unexpected.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private final HttpServletRequest getRequest(final String userName,final String[] aRoles)
|
||||
{
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set roles = new HashSet(Arrays.asList(aRoles));
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(userName);
|
||||
return req;
|
||||
}
|
||||
details.setGrantedAuthorities(gas);
|
||||
Collection returnedGas = Arrays.asList(details.getGrantedAuthorities());
|
||||
assertTrue("Collections do not contain same elements; expected: " + expectedGas + ", returned: " + returnedGas,
|
||||
expectedGas.containsAll(returnedGas) && returnedGas.containsAll(expectedGas));
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testGetWithoutSetPreAuthenticatedGrantedAuthorities() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}));
|
||||
List<GrantedAuthority> gas = details.getGrantedAuthorities();
|
||||
}
|
||||
|
||||
private HttpServletRequest getRequest(final String userName,final String[] aRoles) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set roles = new HashSet(Arrays.asList(aRoles));
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(userName);
|
||||
return req;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+108
-107
@@ -3,6 +3,7 @@ package org.springframework.security.ui.preauth.j2ee;
|
||||
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;
|
||||
@@ -24,125 +25,125 @@ import org.springframework.mock.web.MockHttpServletRequest;
|
||||
*/
|
||||
public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extends TestCase {
|
||||
|
||||
public final void testAfterPropertiesSetException() {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
try {
|
||||
t.afterPropertiesSet();
|
||||
fail("AfterPropertiesSet didn't throw expected exception");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
} catch (Exception unexpected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
}
|
||||
public final void testAfterPropertiesSetException() {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
try {
|
||||
t.afterPropertiesSet();
|
||||
fail("AfterPropertiesSet didn't throw expected exception");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
} catch (Exception unexpected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedNoUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] {};
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedNoUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] {};
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] { "Role1", "Role2" };
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] { "Role1", "Role2" };
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestNoUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] {};
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestNoUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] {};
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestAllUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestAllUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4", "Role5" };
|
||||
String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4", "Role5" };
|
||||
String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestPartialUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3" };
|
||||
String[] expectedRoles = new String[] { "Role2", "Role3" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestPartialUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3" };
|
||||
String[] expectedRoles = new String[] { "Role2", "Role3" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestPartialAndUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3", "Role5" };
|
||||
String[] expectedRoles = new String[] { "Role2", "Role3" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestPartialAndUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3", "Role5" };
|
||||
String[] expectedRoles = new String[] { "Role2", "Role3" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
private void testDetails(String[] mappedRoles, String[] userRoles, String[] expectedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(mappedRoles);
|
||||
Object o = src.buildDetails(getRequest("testUser", userRoles));
|
||||
assertNotNull(o);
|
||||
assertTrue("Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: " + o.getClass(),
|
||||
o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails);
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = (PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails) o;
|
||||
GrantedAuthority[] gas = details.getGrantedAuthorities();
|
||||
assertNotNull("Granted authorities should not be null", gas);
|
||||
assertTrue("Number of granted authorities should be " + expectedRoles.length, gas.length == expectedRoles.length);
|
||||
private void testDetails(String[] mappedRoles, String[] userRoles, String[] expectedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(mappedRoles);
|
||||
Object o = src.buildDetails(getRequest("testUser", userRoles));
|
||||
assertNotNull(o);
|
||||
assertTrue("Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: " + o.getClass(),
|
||||
o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails);
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = (PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails) o;
|
||||
List<GrantedAuthority> gas = details.getGrantedAuthorities();
|
||||
assertNotNull("Granted authorities should not be null", gas);
|
||||
assertEquals(expectedRoles.length, gas.size());
|
||||
|
||||
Collection expectedRolesColl = Arrays.asList(expectedRoles);
|
||||
Collection gasRolesSet = new HashSet();
|
||||
for (int i = 0; i < gas.length; i++) {
|
||||
gasRolesSet.add(gas[i].getAuthority());
|
||||
}
|
||||
assertTrue("Granted Authorities do not match expected roles", expectedRolesColl.containsAll(gasRolesSet)
|
||||
&& gasRolesSet.containsAll(expectedRolesColl));
|
||||
}
|
||||
Collection expectedRolesColl = Arrays.asList(expectedRoles);
|
||||
Collection gasRolesSet = new HashSet();
|
||||
for (int i = 0; i < gas.size(); i++) {
|
||||
gasRolesSet.add(gas.get(i).getAuthority());
|
||||
}
|
||||
assertTrue("Granted Authorities do not match expected roles", expectedRolesColl.containsAll(gasRolesSet)
|
||||
&& gasRolesSet.containsAll(expectedRolesColl));
|
||||
}
|
||||
|
||||
private final J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(
|
||||
String[] mappedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
|
||||
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
|
||||
result.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class);
|
||||
private final J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(
|
||||
String[] mappedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
|
||||
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
|
||||
result.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class);
|
||||
|
||||
try {
|
||||
result.afterPropertiesSet();
|
||||
} catch (Exception expected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
result.afterPropertiesSet();
|
||||
} catch (Exception expected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private MappableAttributesRetriever getMappableRolesRetriever(String[] mappedRoles) {
|
||||
SimpleMappableAttributesRetriever result = new SimpleMappableAttributesRetriever();
|
||||
result.setMappableAttributes(mappedRoles);
|
||||
return result;
|
||||
}
|
||||
private MappableAttributesRetriever getMappableRolesRetriever(String[] mappedRoles) {
|
||||
SimpleMappableAttributesRetriever result = new SimpleMappableAttributesRetriever();
|
||||
result.setMappableAttributes(mappedRoles);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Attributes2GrantedAuthoritiesMapper getJ2eeUserRoles2GrantedAuthoritiesMapper() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper result = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
result.setAddPrefixIfAlreadyExisting(false);
|
||||
result.setConvertAttributeToLowerCase(false);
|
||||
result.setConvertAttributeToUpperCase(false);
|
||||
result.setAttributePrefix("");
|
||||
return result;
|
||||
}
|
||||
private Attributes2GrantedAuthoritiesMapper getJ2eeUserRoles2GrantedAuthoritiesMapper() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper result = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
result.setAddPrefixIfAlreadyExisting(false);
|
||||
result.setConvertAttributeToLowerCase(false);
|
||||
result.setConvertAttributeToUpperCase(false);
|
||||
result.setAttributePrefix("");
|
||||
return result;
|
||||
}
|
||||
|
||||
private final HttpServletRequest getRequest(final String userName,final String[] aRoles)
|
||||
{
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set roles = new HashSet(Arrays.asList(aRoles));
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(userName);
|
||||
return req;
|
||||
}
|
||||
private final HttpServletRequest getRequest(final String userName,final String[] aRoles)
|
||||
{
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set roles = new HashSet(Arrays.asList(aRoles));
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(userName);
|
||||
return req;
|
||||
}
|
||||
}
|
||||
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package org.springframework.security.ui.preauth.x509;
|
||||
|
||||
import org.springframework.security.providers.x509.X509TestUtils;
|
||||
import org.springframework.security.SpringSecurityMessageSource;
|
||||
import org.springframework.security.BadCredentialsException;
|
||||
|
||||
|
||||
+1
-5
@@ -13,7 +13,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.providers.x509;
|
||||
package org.springframework.security.ui.preauth.x509;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
@@ -99,8 +99,4 @@ public class X509TestUtils {
|
||||
|
||||
return (X509Certificate) cf.generateCertificate(in);
|
||||
}
|
||||
|
||||
public static X509AuthenticationToken createToken() throws Exception {
|
||||
return new X509AuthenticationToken(buildTestCertificate());
|
||||
}
|
||||
}
|
||||
+16
-30
@@ -15,19 +15,7 @@
|
||||
|
||||
package org.springframework.security.ui.rememberme;
|
||||
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.MockAuthenticationManager;
|
||||
import org.springframework.security.MockFilterConfig;
|
||||
import org.springframework.security.AuthenticationException;
|
||||
import org.springframework.security.MockApplicationEventPublisher;
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
@@ -37,7 +25,18 @@ import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.AuthenticationException;
|
||||
import org.springframework.security.MockApplicationEventPublisher;
|
||||
import org.springframework.security.MockAuthenticationManager;
|
||||
import org.springframework.security.MockFilterConfig;
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
|
||||
/**
|
||||
@@ -47,14 +46,7 @@ import java.io.IOException;
|
||||
* @version $Id$
|
||||
*/
|
||||
public class RememberMeProcessingFilterTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public RememberMeProcessingFilterTests() {
|
||||
}
|
||||
|
||||
public RememberMeProcessingFilterTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
Authentication remembered = new TestingAuthenticationToken("remembered", "password","ROLE_REMEMBERED");
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
@@ -118,13 +110,10 @@ public class RememberMeProcessingFilterTests extends TestCase {
|
||||
|
||||
public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception {
|
||||
// Put an Authentication object into the SecurityContextHolder
|
||||
Authentication originalAuth = new TestingAuthenticationToken("user", "password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
|
||||
Authentication originalAuth = new TestingAuthenticationToken("user", "password","ROLE_A");
|
||||
SecurityContextHolder.getContext().setAuthentication(originalAuth);
|
||||
|
||||
// Setup our filter correctly
|
||||
Authentication remembered = new TestingAuthenticationToken("remembered", "password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_REMEMBERED")});
|
||||
RememberMeProcessingFilter filter = new RememberMeProcessingFilter();
|
||||
filter.setAuthenticationManager(new MockAuthenticationManager());
|
||||
filter.setRememberMeServices(new MockRememberMeServices(remembered));
|
||||
@@ -141,8 +130,7 @@ public class RememberMeProcessingFilterTests extends TestCase {
|
||||
}
|
||||
|
||||
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
|
||||
Authentication remembered = new TestingAuthenticationToken("remembered", "password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_REMEMBERED")});
|
||||
|
||||
RememberMeProcessingFilter filter = new RememberMeProcessingFilter();
|
||||
filter.setAuthenticationManager(new MockAuthenticationManager());
|
||||
filter.setRememberMeServices(new MockRememberMeServices(remembered));
|
||||
@@ -158,8 +146,6 @@ public class RememberMeProcessingFilterTests extends TestCase {
|
||||
}
|
||||
|
||||
public void testOnunsuccessfulLoginIsCalledWhenProviderRejectsAuth() throws Exception {
|
||||
Authentication remembered = new TestingAuthenticationToken("remembered", "password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_REMEMBERED")});
|
||||
final Authentication failedAuth = new TestingAuthenticationToken("failed", "");
|
||||
|
||||
RememberMeProcessingFilter filter = new RememberMeProcessingFilter() {
|
||||
|
||||
+3
-9
@@ -332,9 +332,7 @@ public class TokenBasedRememberMeServicesTests extends TestCase {
|
||||
request.addParameter(TokenBasedRememberMeServices.DEFAULT_PARAMETER, "false");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginSuccess(request, response,
|
||||
new TestingAuthenticationToken("someone", "password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ABC")}));
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password","ROLE_ABC"));
|
||||
|
||||
Cookie cookie = response.getCookie(TokenBasedRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNull(cookie);
|
||||
@@ -349,9 +347,7 @@ public class TokenBasedRememberMeServicesTests extends TestCase {
|
||||
request.addParameter(TokenBasedRememberMeServices.DEFAULT_PARAMETER, "true");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginSuccess(request, response,
|
||||
new TestingAuthenticationToken("someone", "password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ABC")}));
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password","ROLE_ABC"));
|
||||
|
||||
Cookie cookie = response.getCookie(TokenBasedRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
String expiryTime = services.decodeCookie(cookie.getValue())[1];
|
||||
@@ -373,9 +369,7 @@ public class TokenBasedRememberMeServicesTests extends TestCase {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
UserDetails user = new User("someone", "password", true, true, true, true,
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ABC")});
|
||||
services.loginSuccess(request, response,
|
||||
new TestingAuthenticationToken(user, "ignored",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ABC")}));
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password","ROLE_ABC"));
|
||||
|
||||
Cookie cookie = response.getCookie(TokenBasedRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(cookie);
|
||||
|
||||
+20
-20
@@ -56,12 +56,12 @@ public class SwitchUserProcessingFilterTests {
|
||||
@Before
|
||||
public void authenticateCurrentUser() {
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
}
|
||||
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
private MockHttpServletRequest createMockSwitchRequest() {
|
||||
@@ -72,7 +72,7 @@ public class SwitchUserProcessingFilterTests {
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
|
||||
private Authentication switchToUser(String name) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(SwitchUserProcessingFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, name);
|
||||
@@ -81,9 +81,9 @@ public class SwitchUserProcessingFilterTests {
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
|
||||
return filter.attemptSwitchUser(request);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void requiresExitUserMatchesCorrectly() {
|
||||
SwitchUserProcessingFilter filter = new SwitchUserProcessingFilter();
|
||||
@@ -101,11 +101,11 @@ public class SwitchUserProcessingFilterTests {
|
||||
filter.setSwitchUserUrl("/j_spring_security_my_switch_user");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/j_spring_security_my_switch_user");
|
||||
|
||||
request.setRequestURI("/j_spring_security_my_switch_user");
|
||||
|
||||
assertTrue(filter.requiresSwitchUser(request));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test(expected=UsernameNotFoundException.class)
|
||||
public void attemptSwitchToUnknownUserFails() throws Exception {
|
||||
|
||||
@@ -119,27 +119,27 @@ public class SwitchUserProcessingFilterTests {
|
||||
|
||||
@Test(expected=DisabledException.class)
|
||||
public void attemptSwitchToUserThatIsDisabledFails() throws Exception {
|
||||
switchToUser("mcgarrett");
|
||||
switchToUser("mcgarrett");
|
||||
}
|
||||
|
||||
@Test(expected=AccountExpiredException.class)
|
||||
public void attemptSwitchToUserWithAccountExpiredFails() throws Exception {
|
||||
switchToUser("wofat");
|
||||
switchToUser("wofat");
|
||||
}
|
||||
|
||||
@Test(expected=CredentialsExpiredException.class)
|
||||
public void attemptSwitchToUserWithExpiredCredentialsFails() throws Exception {
|
||||
switchToUser("steve");
|
||||
switchToUser("steve");
|
||||
}
|
||||
|
||||
@Test(expected=UsernameNotFoundException.class)
|
||||
public void switchUserWithNullUsernameThrowsException() throws Exception {
|
||||
switchToUser(null);
|
||||
}
|
||||
|
||||
switchToUser(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void attemptSwitchUserIsSuccessfulWithValidUser() throws Exception {
|
||||
assertNotNull(switchToUser("jacklord"));
|
||||
assertNotNull(switchToUser("jacklord"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -177,7 +177,7 @@ public class SwitchUserProcessingFilterTests {
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testBadConfigMissingTargetUrl() throws Exception {
|
||||
SwitchUserProcessingFilter filter = new SwitchUserProcessingFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
@@ -342,8 +342,8 @@ public class SwitchUserProcessingFilterTests {
|
||||
|
||||
Authentication result = filter.attemptSwitchUser(request);
|
||||
assertTrue(result != null);
|
||||
assertEquals(2, result.getAuthorities().length);
|
||||
assertEquals("ROLE_NEW", result.getAuthorities()[0].getAuthority());
|
||||
assertEquals(2, result.getAuthorities().size());
|
||||
assertEquals("ROLE_NEW", result.getAuthorities().get(0).getAuthority());
|
||||
}
|
||||
|
||||
|
||||
|
||||
-59
@@ -1,59 +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 junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.BadCredentialsException;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link X509ProcessingFilterEntryPoint}.
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @version $Id$
|
||||
*/
|
||||
public class X509ProcessingFilterEntryPointTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public X509ProcessingFilterEntryPointTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public X509ProcessingFilterEntryPointTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
X509ProcessingFilterEntryPoint entryPoint = new X509ProcessingFilterEntryPoint();
|
||||
|
||||
entryPoint.commence(request, response, new BadCredentialsException("As thrown by security enforcement filter"));
|
||||
assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
|
||||
}
|
||||
}
|
||||
-191
@@ -1,191 +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 junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.AuthenticationManager;
|
||||
import org.springframework.security.BadCredentialsException;
|
||||
import org.springframework.security.MockAuthenticationManager;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.providers.x509.X509AuthenticationToken;
|
||||
import org.springframework.security.providers.x509.X509TestUtils;
|
||||
|
||||
import org.springframework.security.ui.AbstractProcessingFilter;
|
||||
|
||||
import org.springframework.security.util.MockFilterChain;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link org.springframework.security.ui.x509.X509ProcessingFilter}.
|
||||
*
|
||||
* @author Luke Taylor
|
||||
* @version $Id$
|
||||
*/
|
||||
public class X509ProcessingFilterTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public X509ProcessingFilterTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public X509ProcessingFilterTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testAuthenticationIsNullWithNoCertificate()
|
||||
throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(true);
|
||||
|
||||
AuthenticationManager authMgr = new MockX509AuthenticationManager();
|
||||
X509ProcessingFilter filter = new X509ProcessingFilter();
|
||||
|
||||
filter.setAuthenticationManager(authMgr);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
Object lastException = request.getSession()
|
||||
.getAttribute(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);
|
||||
|
||||
assertNull("Authentication should be null", SecurityContextHolder.getContext().getAuthentication());
|
||||
assertTrue("BadCredentialsException should have been thrown", lastException instanceof BadCredentialsException);
|
||||
}
|
||||
|
||||
public void testDoFilterWithNonHttpServletRequestDetected()
|
||||
throws Exception {
|
||||
X509ProcessingFilter filter = new X509ProcessingFilter();
|
||||
|
||||
try {
|
||||
filter.doFilter(null, new MockHttpServletResponse(), new MockFilterChain(false));
|
||||
fail("Should have thrown ServletException");
|
||||
} catch (ServletException expected) {
|
||||
assertEquals("Can only process HttpServletRequest", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testDoFilterWithNonHttpServletResponseDetected()
|
||||
throws Exception {
|
||||
X509ProcessingFilter filter = new X509ProcessingFilter();
|
||||
|
||||
try {
|
||||
filter.doFilter(new MockHttpServletRequest(null, null), null, new MockFilterChain(false));
|
||||
fail("Should have thrown ServletException");
|
||||
} catch (ServletException expected) {
|
||||
assertEquals("Can only process HttpServletResponse", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testFailedAuthentication() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(true);
|
||||
|
||||
request.setAttribute("javax.servlet.request.X509Certificate",
|
||||
new X509Certificate[] {X509TestUtils.buildTestCertificate()});
|
||||
|
||||
AuthenticationManager authMgr = new MockAuthenticationManager(false);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
X509ProcessingFilter filter = new X509ProcessingFilter();
|
||||
|
||||
filter.setAuthenticationManager(authMgr);
|
||||
filter.afterPropertiesSet();
|
||||
filter.init(null);
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.destroy();
|
||||
|
||||
Authentication result = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
public void testNeedsAuthenticationManager() throws Exception {
|
||||
X509ProcessingFilter filter = new X509ProcessingFilter();
|
||||
|
||||
try {
|
||||
filter.afterPropertiesSet();
|
||||
fail("Expected IllegalArgumentException");
|
||||
} catch (IllegalArgumentException failed) {
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = new MockFilterChain(true);
|
||||
|
||||
request.setAttribute("javax.servlet.request.X509Certificate",
|
||||
new X509Certificate[] {X509TestUtils.buildTestCertificate()});
|
||||
|
||||
AuthenticationManager authMgr = new MockX509AuthenticationManager();
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
X509ProcessingFilter filter = new X509ProcessingFilter();
|
||||
|
||||
filter.setAuthenticationManager(authMgr);
|
||||
filter.afterPropertiesSet();
|
||||
filter.init(null);
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.destroy();
|
||||
|
||||
Authentication result = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private static class MockX509AuthenticationManager implements AuthenticationManager {
|
||||
public Authentication authenticate(Authentication a) {
|
||||
if (!(a instanceof X509AuthenticationToken)) {
|
||||
TestCase.fail("Needed an X509Authentication token but found " + a);
|
||||
}
|
||||
|
||||
if (a.getCredentials() == null) {
|
||||
throw new BadCredentialsException("Mock authentication manager rejecting null certificate");
|
||||
}
|
||||
|
||||
return a;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,12 +126,12 @@ public class UserTests extends TestCase {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
UserDetails user = new User("rod", "koala", true, true, true, true, null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
// try {
|
||||
// UserDetails user = new User("rod", "koala", true, true, true, true, null);
|
||||
// fail("Should have thrown IllegalArgumentException");
|
||||
// } catch (IllegalArgumentException expected) {
|
||||
// assertTrue(true);
|
||||
// }
|
||||
|
||||
try {
|
||||
UserDetails user = new User("rod", "koala", true, true, true, true,
|
||||
@@ -162,8 +162,8 @@ public class UserTests extends TestCase {
|
||||
assertEquals("rod", user.getUsername());
|
||||
assertEquals("koala", user.getPassword());
|
||||
assertTrue(user.isEnabled());
|
||||
assertEquals(new GrantedAuthorityImpl("ROLE_ONE"), user.getAuthorities()[0]);
|
||||
assertEquals(new GrantedAuthorityImpl("ROLE_TWO"), user.getAuthorities()[1]);
|
||||
assertEquals(new GrantedAuthorityImpl("ROLE_ONE"), user.getAuthorities().get(0));
|
||||
assertEquals(new GrantedAuthorityImpl("ROLE_TWO"), user.getAuthorities().get(1));
|
||||
assertTrue(user.toString().indexOf("rod") != -1);
|
||||
}
|
||||
|
||||
|
||||
+6
-9
@@ -14,7 +14,6 @@
|
||||
|
||||
package org.springframework.security.userdetails.hierarchicalroles;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
@@ -27,17 +26,15 @@ import org.apache.commons.collections.CollectionUtils;
|
||||
*/
|
||||
public abstract class HierarchicalRolesTestHelper {
|
||||
|
||||
public static boolean containTheSameGrantedAuthorities(GrantedAuthority[] authorities1, GrantedAuthority[] authorities2) {
|
||||
public static boolean containTheSameGrantedAuthorities(List<GrantedAuthority> authorities1, List<GrantedAuthority> authorities2) {
|
||||
if (authorities1 == null && authorities2 == null) {
|
||||
return true;
|
||||
} else if (authorities1 == null || authorities2 == null) {
|
||||
}
|
||||
|
||||
if (authorities1 == null || authorities2 == null) {
|
||||
return false;
|
||||
}
|
||||
List authoritiesList1 = new ArrayList();
|
||||
CollectionUtils.addAll(authoritiesList1, authorities1);
|
||||
List authoritiesList2 = new ArrayList();
|
||||
CollectionUtils.addAll(authoritiesList2, authorities2);
|
||||
return CollectionUtils.isEqualCollection(authoritiesList1, authoritiesList2);
|
||||
return CollectionUtils.isEqualCollection(authorities1, authorities2);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+19
-25
@@ -14,10 +14,12 @@
|
||||
|
||||
package org.springframework.security.userdetails.hierarchicalroles;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
|
||||
/**
|
||||
* Tests for {@link RoleHierarchyImpl}.
|
||||
@@ -26,17 +28,11 @@ import org.springframework.security.GrantedAuthorityImpl;
|
||||
*/
|
||||
public class RoleHierarchyImplTests extends TestCase {
|
||||
|
||||
public RoleHierarchyImplTests() {
|
||||
}
|
||||
|
||||
public RoleHierarchyImplTests(String testCaseName) {
|
||||
super(testCaseName);
|
||||
}
|
||||
|
||||
public void testSimpleRoleHierarchy() {
|
||||
GrantedAuthority[] authorities0 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_0") };
|
||||
GrantedAuthority[] authorities1 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A") };
|
||||
GrantedAuthority[] authorities2 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B") };
|
||||
|
||||
List<GrantedAuthority> authorities0 = AuthorityUtils.createAuthorityList("ROLE_0");
|
||||
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A");
|
||||
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A","ROLE_B");
|
||||
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
|
||||
@@ -47,10 +43,9 @@ public class RoleHierarchyImplTests extends TestCase {
|
||||
}
|
||||
|
||||
public void testTransitiveRoleHierarchies() {
|
||||
GrantedAuthority[] authorities1 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A") };
|
||||
GrantedAuthority[] authorities2 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B"), new GrantedAuthorityImpl("ROLE_C") };
|
||||
GrantedAuthority[] authorities3 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B"), new GrantedAuthorityImpl("ROLE_C"),
|
||||
new GrantedAuthorityImpl("ROLE_D") };
|
||||
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A");
|
||||
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A","ROLE_B","ROLE_C");
|
||||
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A","ROLE_B","ROLE_C","ROLE_D");
|
||||
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
|
||||
@@ -62,15 +57,14 @@ public class RoleHierarchyImplTests extends TestCase {
|
||||
}
|
||||
|
||||
public void testComplexRoleHierarchy() {
|
||||
GrantedAuthority[] authoritiesInput1 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A") };
|
||||
GrantedAuthority[] authoritiesOutput1 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B"), new GrantedAuthorityImpl("ROLE_C"),
|
||||
new GrantedAuthorityImpl("ROLE_D") };
|
||||
GrantedAuthority[] authoritiesInput2 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_B") };
|
||||
GrantedAuthority[] authoritiesOutput2 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_B"), new GrantedAuthorityImpl("ROLE_D") };
|
||||
GrantedAuthority[] authoritiesInput3 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_C") };
|
||||
GrantedAuthority[] authoritiesOutput3 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_C"), new GrantedAuthorityImpl("ROLE_D") };
|
||||
GrantedAuthority[] authoritiesInput4 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_D") };
|
||||
GrantedAuthority[] authoritiesOutput4 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_D") };
|
||||
List<GrantedAuthority> authoritiesInput1 = AuthorityUtils.createAuthorityList("ROLE_A");
|
||||
List<GrantedAuthority> authoritiesOutput1 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B","ROLE_C", "ROLE_D");
|
||||
List<GrantedAuthority> authoritiesInput2 = AuthorityUtils.createAuthorityList("ROLE_B");
|
||||
List<GrantedAuthority> authoritiesOutput2 = AuthorityUtils.createAuthorityList("ROLE_B","ROLE_D");
|
||||
List<GrantedAuthority> authoritiesInput3 = AuthorityUtils.createAuthorityList("ROLE_C");
|
||||
List<GrantedAuthority> authoritiesOutput3 = AuthorityUtils.createAuthorityList("ROLE_C","ROLE_D");
|
||||
List<GrantedAuthority> authoritiesInput4 = AuthorityUtils.createAuthorityList("ROLE_D");
|
||||
List<GrantedAuthority> authoritiesOutput4 = AuthorityUtils.createAuthorityList("ROLE_D");
|
||||
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
|
||||
@@ -115,4 +109,4 @@ public class RoleHierarchyImplTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+13
-15
@@ -14,31 +14,29 @@
|
||||
|
||||
package org.springframework.security.userdetails.hierarchicalroles;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
|
||||
/**
|
||||
* Tests for {@link HierarchicalRolesTestHelper}.
|
||||
*
|
||||
* @author Michael Mayr
|
||||
*/
|
||||
public class TestHelperTests extends TestCase {
|
||||
|
||||
public TestHelperTests() {
|
||||
}
|
||||
|
||||
public TestHelperTests(String testCaseName) {
|
||||
super(testCaseName);
|
||||
}
|
||||
public class TestHelperTests {
|
||||
|
||||
@Test
|
||||
public void testContainTheSameGrantedAuthorities() {
|
||||
GrantedAuthority[] authorities1 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B") };
|
||||
GrantedAuthority[] authorities2 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_B"), new GrantedAuthorityImpl("ROLE_A") };
|
||||
GrantedAuthority[] authorities3 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_C") };
|
||||
GrantedAuthority[] authorities4 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A") };
|
||||
GrantedAuthority[] authorities5 = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_A") };
|
||||
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A","ROLE_B");
|
||||
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_B","ROLE_A");
|
||||
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A","ROLE_C");
|
||||
List<GrantedAuthority> authorities4 = AuthorityUtils.createAuthorityList("ROLE_A");
|
||||
List<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList("ROLE_A","ROLE_A");
|
||||
|
||||
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, null));
|
||||
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities1));
|
||||
|
||||
+5
-2
@@ -1,11 +1,14 @@
|
||||
package org.springframework.security.userdetails.hierarchicalroles;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.userdetails.User;
|
||||
import org.springframework.security.userdetails.UserDetails;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
|
||||
/**
|
||||
* Tests for {@link UserDetailsWrapper}.
|
||||
@@ -48,7 +51,7 @@ public class UserDetailsWrapperTests extends TestCase {
|
||||
}
|
||||
|
||||
public void testGetAuthorities() {
|
||||
GrantedAuthority[] expectedAuthorities = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B") };
|
||||
List<GrantedAuthority> expectedAuthorities = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B");
|
||||
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(userDetailsWrapper1.getAuthorities(), expectedAuthorities));
|
||||
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(userDetailsWrapper2.getAuthorities(), expectedAuthorities));
|
||||
}
|
||||
@@ -78,4 +81,4 @@ public class UserDetailsWrapperTests extends TestCase {
|
||||
assertTrue(userDetailsWrapper2.getUnwrappedUserDetails() == userDetails2);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+9
-17
@@ -73,8 +73,8 @@ public class JdbcDaoImplTests extends TestCase {
|
||||
assertTrue(user.isEnabled());
|
||||
|
||||
HashSet authorities = new HashSet(2);
|
||||
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_TELLER"));
|
||||
assertTrue(authorities.contains("ROLE_SUPERVISOR"));
|
||||
}
|
||||
@@ -82,8 +82,8 @@ public class JdbcDaoImplTests extends TestCase {
|
||||
public void testCheckDaoOnlyReturnsGrantedAuthoritiesGrantedToUser() throws Exception {
|
||||
JdbcDaoImpl dao = makePopulatedJdbcDao();
|
||||
UserDetails user = dao.loadUserByUsername("scott");
|
||||
assertEquals("ROLE_TELLER", user.getAuthorities()[0].getAuthority());
|
||||
assertEquals(1, user.getAuthorities().length);
|
||||
assertEquals("ROLE_TELLER", user.getAuthorities().get(0).getAuthority());
|
||||
assertEquals(1, user.getAuthorities().size());
|
||||
}
|
||||
|
||||
public void testCheckDaoReturnsCorrectDisabledProperty() throws Exception {
|
||||
@@ -135,11 +135,11 @@ public class JdbcDaoImplTests extends TestCase {
|
||||
|
||||
UserDetails user = dao.loadUserByUsername("rod");
|
||||
assertEquals("rod", user.getUsername());
|
||||
assertEquals(2, user.getAuthorities().length);
|
||||
assertEquals(2, user.getAuthorities().size());
|
||||
|
||||
HashSet authorities = new HashSet(2);
|
||||
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("ARBITRARY_PREFIX_ROLE_TELLER"));
|
||||
assertTrue(authorities.contains("ARBITRARY_PREFIX_ROLE_SUPERVISOR"));
|
||||
}
|
||||
@@ -150,7 +150,7 @@ public class JdbcDaoImplTests extends TestCase {
|
||||
dao.setEnableGroups(true);
|
||||
|
||||
UserDetails jerry = dao.loadUserByUsername("jerry");
|
||||
assertEquals(3, jerry.getAuthorities().length);
|
||||
assertEquals(3, jerry.getAuthorities().size());
|
||||
}
|
||||
|
||||
public void testDuplicateGroupAuthoritiesAreRemoved() throws Exception {
|
||||
@@ -159,7 +159,7 @@ public class JdbcDaoImplTests extends TestCase {
|
||||
dao.setEnableGroups(true);
|
||||
// Tom has roles A, B, C and B, C duplicates
|
||||
UserDetails tom = dao.loadUserByUsername("tom");
|
||||
assertEquals(3, tom.getAuthorities().length);
|
||||
assertEquals(3, tom.getAuthorities().size());
|
||||
}
|
||||
|
||||
public void testStartupFailsIfDataSourceNotSet() throws Exception {
|
||||
@@ -184,12 +184,4 @@ public class JdbcDaoImplTests extends TestCase {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockMappingSqlQuery extends MappingSqlQuery {
|
||||
protected Object mapRow(ResultSet arg0, int arg1) throws SQLException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+5
-7
@@ -41,7 +41,7 @@ public class JdbcUserDetailsManagerTests {
|
||||
private static final String SELECT_JOE_AUTHORITIES_SQL = "select * from authorities where username = 'joe'";
|
||||
|
||||
private static final UserDetails joe = new User("joe", "password", true, true, true, true,
|
||||
AuthorityUtils.stringArrayToAuthorityArray(new String[]{"A","C","B"}));
|
||||
AuthorityUtils.createAuthorityList("A","C","B"));
|
||||
|
||||
private static TestDataSource dataSource;
|
||||
private JdbcUserDetailsManager manager;
|
||||
@@ -116,7 +116,7 @@ public class JdbcUserDetailsManagerTests {
|
||||
public void updateUserChangesDataCorrectlyAndClearsCache() {
|
||||
insertJoe();
|
||||
User newJoe = new User("joe","newpassword",false,true,true,true,
|
||||
AuthorityUtils.stringArrayToAuthorityArray(new String[]{"D","F","E"}));
|
||||
AuthorityUtils.createAuthorityList(new String[]{"D","F","E"}));
|
||||
|
||||
manager.updateUser(newJoe);
|
||||
|
||||
@@ -213,7 +213,7 @@ public class JdbcUserDetailsManagerTests {
|
||||
|
||||
@Test
|
||||
public void createGroupInsertsCorrectData() {
|
||||
manager.createGroup("TEST_GROUP", AuthorityUtils.stringArrayToAuthorityArray(new String[] {"ROLE_X", "ROLE_Y"}));
|
||||
manager.createGroup("TEST_GROUP", AuthorityUtils.createAuthorityList("ROLE_X", "ROLE_Y"));
|
||||
|
||||
List roles = template.queryForList(
|
||||
"select ga.authority from groups g, group_authorities ga " +
|
||||
@@ -258,9 +258,7 @@ public class JdbcUserDetailsManagerTests {
|
||||
|
||||
@Test
|
||||
public void findGroupAuthoritiesReturnsCorrectAuthorities() throws Exception {
|
||||
GrantedAuthority[] authorities = manager.findGroupAuthorities("GROUP_0");
|
||||
|
||||
assertEquals("ROLE_A", authorities[0].getAuthority());
|
||||
assertEquals(AuthorityUtils.createAuthorityList("ROLE_A"), manager.findGroupAuthorities("GROUP_0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -278,7 +276,7 @@ public class JdbcUserDetailsManagerTests {
|
||||
assertEquals(0, template.queryForList("select authority from group_authorities where group_id = 0").size());
|
||||
|
||||
manager.removeGroupAuthority("GROUP_2", auth);
|
||||
assertEquals(2, template.queryForList("select authority from group_authorities where group_id = 2").size());
|
||||
assertEquals(2, template.queryForList("select authority from group_authorities where group_id = 2").size());
|
||||
}
|
||||
|
||||
private Authentication authenticateJoe() {
|
||||
|
||||
+15
-11
@@ -14,28 +14,32 @@
|
||||
*/
|
||||
package org.springframework.security.userdetails.ldap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.ldap.core.DirContextAdapter;
|
||||
import org.springframework.security.BadCredentialsException;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
import org.springframework.security.ldap.AbstractLdapIntegrationTests;
|
||||
import org.springframework.security.ldap.DefaultLdapUsernameToDnMapper;
|
||||
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
|
||||
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.ldap.core.DirContextAdapter;
|
||||
|
||||
import org.junit.After;
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
* @version $Id$
|
||||
*/
|
||||
public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests {
|
||||
private static final GrantedAuthority[] TEST_AUTHORITIES = new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_CLOWNS"),
|
||||
new GrantedAuthorityImpl("ROLE_ACROBATS")};
|
||||
private static final List<GrantedAuthority> TEST_AUTHORITIES = AuthorityUtils.createAuthorityList("ROLE_CLOWNS","ROLE_ACROBATS");
|
||||
private LdapUserDetailsManager mgr;
|
||||
private SpringSecurityLdapTemplate template;
|
||||
|
||||
@@ -94,7 +98,7 @@ public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests {
|
||||
assertEquals("uid=bob, ou=people, dc=springframework, dc=org", bob.getDn());
|
||||
assertEquals("bobspassword", bob.getPassword());
|
||||
|
||||
assertEquals(1, bob.getAuthorities().length);
|
||||
assertEquals(1, bob.getAuthorities().size());
|
||||
}
|
||||
|
||||
@Test(expected = UsernameNotFoundException.class)
|
||||
@@ -150,7 +154,7 @@ public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests {
|
||||
|
||||
InetOrgPerson don = (InetOrgPerson) mgr.loadUserByUsername("don");
|
||||
|
||||
assertEquals(2, don.getAuthorities().length);
|
||||
assertEquals(2, don.getAuthorities().size());
|
||||
|
||||
mgr.deleteUser("don");
|
||||
|
||||
@@ -162,7 +166,7 @@ public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests {
|
||||
}
|
||||
|
||||
// Check that no authorities are left
|
||||
assertEquals(0, mgr.getUserAuthorities(mgr.usernameMapper.buildDn("don"), "don").length);
|
||||
assertEquals(0, mgr.getUserAuthorities(mgr.usernameMapper.buildDn("don"), "don").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+10
-26
@@ -15,14 +15,14 @@
|
||||
|
||||
package org.springframework.security.userdetails.ldap;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import javax.naming.directory.BasicAttributes;
|
||||
import javax.naming.directory.BasicAttribute;
|
||||
import javax.naming.directory.BasicAttributes;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.ldap.core.DirContextAdapter;
|
||||
import org.springframework.ldap.core.DistinguishedName;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
|
||||
/**
|
||||
* Tests {@link LdapUserDetailsMapper}.
|
||||
@@ -32,7 +32,6 @@ import org.springframework.security.GrantedAuthority;
|
||||
*/
|
||||
public class LdapUserDetailsMapperTests extends TestCase {
|
||||
|
||||
|
||||
public void testMultipleRoleAttributeValuesAreMappedToAuthorities() throws Exception {
|
||||
LdapUserDetailsMapper mapper = new LdapUserDetailsMapper();
|
||||
mapper.setConvertToUpperCase(false);
|
||||
@@ -45,9 +44,9 @@ public class LdapUserDetailsMapperTests extends TestCase {
|
||||
ctx.setAttributeValues("userRole", new String[] {"X", "Y", "Z"});
|
||||
ctx.setAttributeValue("uid", "ani");
|
||||
|
||||
LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", new GrantedAuthority[0]);
|
||||
LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES);
|
||||
|
||||
assertEquals(3, user.getAuthorities().length);
|
||||
assertEquals(3, user.getAuthorities().size());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -64,27 +63,12 @@ public class LdapUserDetailsMapperTests extends TestCase {
|
||||
DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName("cn=someName"));
|
||||
ctx.setAttributeValue("uid", "ani");
|
||||
|
||||
LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", new GrantedAuthority[0]);
|
||||
LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES);
|
||||
|
||||
assertEquals(1, user.getAuthorities().length);
|
||||
assertEquals("ROLE_X", user.getAuthorities()[0].getAuthority());
|
||||
assertEquals(1, user.getAuthorities().size());
|
||||
assertEquals("ROLE_X", user.getAuthorities().get(0).getAuthority());
|
||||
}
|
||||
|
||||
// public void testNonStringRoleAttributeIsIgnoredByDefault() throws Exception {
|
||||
// LdapUserDetailsMapper mapper = new LdapUserDetailsMapper();
|
||||
//
|
||||
// mapper.setRoleAttributes(new String[] {"userRole"});
|
||||
//
|
||||
// BasicAttributes attrs = new BasicAttributes();
|
||||
// attrs.put(new BasicAttribute("userRole", new GrantedAuthorityImpl("X")));
|
||||
//
|
||||
// DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName("cn=someName"));
|
||||
//
|
||||
// LdapUserDetailsImpl.Essence user = (LdapUserDetailsImpl.Essence) mapper.mapFromContext(ctx);
|
||||
//
|
||||
// assertEquals(0, user.getGrantedAuthorities().length);
|
||||
// }
|
||||
|
||||
public void testPasswordAttributeIsMappedCorrectly() throws Exception {
|
||||
LdapUserDetailsMapper mapper = new LdapUserDetailsMapper();
|
||||
|
||||
@@ -95,7 +79,7 @@ public class LdapUserDetailsMapperTests extends TestCase {
|
||||
DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName("cn=someName"));
|
||||
ctx.setAttributeValue("uid", "ani");
|
||||
|
||||
LdapUserDetails user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", new GrantedAuthority[0]);
|
||||
LdapUserDetails user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES);
|
||||
|
||||
assertEquals("mypassword", user.getPassword());
|
||||
}
|
||||
|
||||
+12
-11
@@ -1,19 +1,20 @@
|
||||
package org.springframework.security.userdetails.ldap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.ldap.core.DirContextAdapter;
|
||||
import org.springframework.ldap.core.DirContextOperations;
|
||||
import org.springframework.ldap.core.DistinguishedName;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.ldap.LdapAuthoritiesPopulator;
|
||||
import org.springframework.security.providers.ldap.authenticator.MockUserSearch;
|
||||
import org.springframework.security.userdetails.UserDetails;
|
||||
import org.springframework.security.util.AuthorityUtils;
|
||||
import org.springframework.ldap.core.DirContextAdapter;
|
||||
import org.springframework.ldap.core.DirContextOperations;
|
||||
import org.springframework.ldap.core.DistinguishedName;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Tests for {@link LdapUserDetailsService}
|
||||
@@ -49,8 +50,8 @@ public class LdapUserDetailsServiceTests {
|
||||
}
|
||||
|
||||
class MockAuthoritiesPopulator implements LdapAuthoritiesPopulator {
|
||||
public GrantedAuthority[] getGrantedAuthorities(DirContextOperations userCtx, String username) {
|
||||
return new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_FROM_POPULATOR")};
|
||||
public List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userCtx, String username) {
|
||||
return AuthorityUtils.createAuthorityList("ROLE_FROM_POPULATOR");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -63,8 +63,8 @@ public class UserMapEditorTests extends TestCase {
|
||||
UserMap map = (UserMap) editor.getValue();
|
||||
assertEquals("rod", map.getUser("rod").getUsername());
|
||||
assertEquals("koala", map.getUser("rod").getPassword());
|
||||
assertEquals("ROLE_ONE", map.getUser("rod").getAuthorities()[0].getAuthority());
|
||||
assertEquals("ROLE_TWO", map.getUser("rod").getAuthorities()[1].getAuthority());
|
||||
assertEquals("ROLE_ONE", map.getUser("rod").getAuthorities().get(0).getAuthority());
|
||||
assertEquals("ROLE_TWO", map.getUser("rod").getAuthorities().get(1).getAuthority());
|
||||
assertTrue(map.getUser("rod").isEnabled());
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
@@ -39,7 +40,7 @@ public class AuthorityUtilsTests {
|
||||
@Test
|
||||
public void userHasAuthorityReturnsTrueWhenUserHasCorrectAuthority() {
|
||||
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "password",
|
||||
AuthorityUtils.stringArrayToAuthorityArray(new String[] {"A", "B"})));
|
||||
AuthorityUtils.createAuthorityList("A", "B")));
|
||||
assertTrue(AuthorityUtils.userHasAuthority("A"));
|
||||
assertTrue(AuthorityUtils.userHasAuthority("B"));
|
||||
assertFalse(AuthorityUtils.userHasAuthority("C"));
|
||||
@@ -50,7 +51,7 @@ public class AuthorityUtilsTests {
|
||||
GrantedAuthority[] authorityArray =
|
||||
AuthorityUtils.commaSeparatedStringToAuthorityArray(" ROLE_A, B, C, ROLE_D, E ");
|
||||
|
||||
Set authorities = AuthorityUtils.authorityArrayToSet(authorityArray);
|
||||
Set authorities = AuthorityUtils.authorityArrayToSet(Arrays.asList(authorityArray));
|
||||
|
||||
assertTrue(authorities.contains("B"));
|
||||
assertTrue(authorities.contains("C"));
|
||||
|
||||
@@ -22,8 +22,6 @@ import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.AccessDeniedException;
|
||||
import org.springframework.security.ConfigAttribute;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.SecurityConfig;
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
@@ -69,17 +67,11 @@ public class UnanimousBasedTests extends TestCase {
|
||||
}
|
||||
|
||||
private TestingAuthenticationToken makeTestToken() {
|
||||
return new TestingAuthenticationToken("somebody", "password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_1"), new GrantedAuthorityImpl("ROLE_2")});
|
||||
return new TestingAuthenticationToken("somebody", "password", "ROLE_1", "ROLE_2");
|
||||
}
|
||||
|
||||
private TestingAuthenticationToken makeTestTokenWithFooBarPrefix() {
|
||||
return new TestingAuthenticationToken("somebody", "password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("FOOBAR_1"), new GrantedAuthorityImpl("FOOBAR_2")});
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
return new TestingAuthenticationToken("somebody", "password", "FOOBAR_1", "FOOBAR_2");
|
||||
}
|
||||
|
||||
public void testOneAffirmativeVoteOneDenyVoteOneAbstainVoteDeniesAccess() throws Exception {
|
||||
|
||||
+4
-9
@@ -19,7 +19,6 @@ import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
import org.springframework.security.userdetails.User;
|
||||
@@ -51,8 +50,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
}
|
||||
|
||||
public void testCorrectOperationWithStringBasedPrincipal() throws Exception {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_FOO")});
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala","ROLE_FOO");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@@ -67,8 +65,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
}
|
||||
|
||||
public void testUseOfRolePrefixMeansItIsntNeededWhenCallngIsUserInRole() {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_FOO")});
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", "ROLE_FOO");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@@ -81,8 +78,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
|
||||
public void testCorrectOperationWithUserDetailsBasedPrincipal() throws Exception {
|
||||
Authentication auth = new TestingAuthenticationToken(new User("rodAsUserDetails", "koala", true, true,
|
||||
true, true, new GrantedAuthority[] {}), "koala",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_HELLO"), new GrantedAuthorityImpl("ROLE_FOOBAR")});
|
||||
true, true, new GrantedAuthority[] {}), "koala", "ROLE_HELLO", "ROLE_FOOBAR");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@@ -111,8 +107,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
}
|
||||
|
||||
public void testRolesArentHeldIfAuthenticationPrincipalIsNull() throws Exception {
|
||||
Authentication auth = new TestingAuthenticationToken(null, "koala",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_HELLO"), new GrantedAuthorityImpl("ROLE_FOOBAR")});
|
||||
Authentication auth = new TestingAuthenticationToken(null, "koala","ROLE_HELLO","ROLE_FOOBAR");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
Reference in New Issue
Block a user