Remove blank lines from all tests
Remove all blank lines from test code so that test methods are visually grouped together. This generally helps to make the test classes easer to scan, however, the "given" / "when" / "then" blocks used by some tests are now not as easy to discern. Issue gh-8945
This commit is contained in:
@@ -37,14 +37,12 @@ public final class PopulatedDatabase {
|
||||
if (dataSource == null) {
|
||||
setupDataSource();
|
||||
}
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
private static void setupDataSource() {
|
||||
dataSource = new TestDataSource("springsecuritytest");
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource);
|
||||
|
||||
template.execute(
|
||||
"CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(500) NOT NULL,ENABLED BOOLEAN NOT NULL)");
|
||||
template.execute(
|
||||
@@ -77,18 +75,15 @@ public final class PopulatedDatabase {
|
||||
"INSERT INTO acl_object_identity VALUES (5, 'org.springframework.security.acl.DomainObject:5', 3, 'org.springframework.security.acl.basic.SimpleAclEntry');");
|
||||
template.execute(
|
||||
"INSERT INTO acl_object_identity VALUES (6, 'org.springframework.security.acl.DomainObject:6', 3, 'org.springframework.security.acl.basic.SimpleAclEntry');");
|
||||
|
||||
// ----- BEGIN deviation from normal sample data load script -----
|
||||
template.execute(
|
||||
"INSERT INTO acl_object_identity VALUES (7, 'org.springframework.security.acl.DomainObject:7', 3, 'some.invalid.acl.entry.class');");
|
||||
|
||||
// ----- FINISH deviation from normal sample data load script -----
|
||||
template.execute("INSERT INTO acl_permission VALUES (null, 1, 'ROLE_SUPERVISOR', 1);");
|
||||
template.execute("INSERT INTO acl_permission VALUES (null, 2, 'ROLE_SUPERVISOR', 0);");
|
||||
template.execute("INSERT INTO acl_permission VALUES (null, 2, 'rod', 2);");
|
||||
template.execute("INSERT INTO acl_permission VALUES (null, 3, 'scott', 14);");
|
||||
template.execute("INSERT INTO acl_permission VALUES (null, 6, 'scott', 1);");
|
||||
|
||||
createGroupTables(template);
|
||||
insertGroupData(template);
|
||||
}
|
||||
@@ -106,13 +101,11 @@ public final class PopulatedDatabase {
|
||||
public static void insertGroupData(JdbcTemplate template) {
|
||||
template.execute("INSERT INTO USERS VALUES('jerry','password',TRUE)");
|
||||
template.execute("INSERT INTO USERS VALUES('tom','password',TRUE)");
|
||||
|
||||
template.execute("INSERT INTO GROUPS VALUES (0, 'GROUP_0')");
|
||||
template.execute("INSERT INTO GROUPS VALUES (1, 'GROUP_1')");
|
||||
template.execute("INSERT INTO GROUPS VALUES (2, 'GROUP_2')");
|
||||
// Group 3 isn't used
|
||||
template.execute("INSERT INTO GROUPS VALUES (3, 'GROUP_3')");
|
||||
|
||||
template.execute("INSERT INTO GROUP_AUTHORITIES VALUES (0, 'ROLE_A')");
|
||||
template.execute("INSERT INTO GROUP_AUTHORITIES VALUES (1, 'ROLE_B')");
|
||||
template.execute("INSERT INTO GROUP_AUTHORITIES VALUES (1, 'ROLE_C')");
|
||||
@@ -121,7 +114,6 @@ public final class PopulatedDatabase {
|
||||
template.execute("INSERT INTO GROUP_AUTHORITIES VALUES (2, 'ROLE_C')");
|
||||
template.execute("INSERT INTO GROUP_AUTHORITIES VALUES (3, 'ROLE_D')");
|
||||
template.execute("INSERT INTO GROUP_AUTHORITIES VALUES (3, 'ROLE_E')");
|
||||
|
||||
template.execute("INSERT INTO GROUP_MEMBERS VALUES (0, 'jerry', 0)");
|
||||
template.execute("INSERT INTO GROUP_MEMBERS VALUES (1, 'jerry', 1)");
|
||||
// tom has groups with overlapping roles
|
||||
|
||||
@@ -47,7 +47,6 @@ public class TargetObject implements ITargetObject {
|
||||
@Override
|
||||
public String makeLowerCase(String input) {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (auth == null) {
|
||||
return input.toLowerCase() + " Authentication empty";
|
||||
}
|
||||
@@ -67,7 +66,6 @@ public class TargetObject implements ITargetObject {
|
||||
@Override
|
||||
public String makeUpperCase(String input) {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
return input.toUpperCase() + " " + auth.getClass().getName() + " " + auth.isAuthenticated();
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ public class AuthorizedEventTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testRejectsNulls2() {
|
||||
|
||||
new AuthorizedEvent(new SimpleMethodInvocation(), null, new UsernamePasswordAuthenticationToken("foo", "bar"));
|
||||
}
|
||||
|
||||
|
||||
@@ -53,23 +53,17 @@ public class SecurityConfigTests {
|
||||
SecurityConfig security1 = new SecurityConfig("TEST");
|
||||
SecurityConfig security2 = new SecurityConfig("TEST");
|
||||
assertThat(security2).isEqualTo(security1);
|
||||
|
||||
// SEC-311: Must observe symmetry requirement of Object.equals(Object) contract
|
||||
String securityString1 = "TEST";
|
||||
assertThat(securityString1).isNotSameAs(security1);
|
||||
|
||||
String securityString2 = "NOT_EQUAL";
|
||||
assertThat(!security1.equals(securityString2)).isTrue();
|
||||
|
||||
SecurityConfig security3 = new SecurityConfig("NOT_EQUAL");
|
||||
assertThat(!security1.equals(security3)).isTrue();
|
||||
|
||||
MockConfigAttribute mock1 = new MockConfigAttribute("TEST");
|
||||
assertThat(security1).isEqualTo(mock1);
|
||||
|
||||
MockConfigAttribute mock2 = new MockConfigAttribute("NOT_EQUAL");
|
||||
assertThat(security1).isNotEqualTo(mock2);
|
||||
|
||||
Integer int1 = 987;
|
||||
assertThat(security1).isNotEqualTo(int1);
|
||||
}
|
||||
|
||||
@@ -75,7 +75,6 @@ public class BusinessServiceImpl<E extends Entity> implements BusinessService {
|
||||
|
||||
@Override
|
||||
public void rolesAllowedUser() {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -71,12 +71,10 @@ public class ExpressionProtectedBusinessServiceImpl implements BusinessService {
|
||||
|
||||
@PreAuthorize("#x == 'x' and @number.intValue() == 1294 ")
|
||||
public void methodWithBeanNamePropertyAccessExpression(String x) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rolesAllowedUser() {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -76,7 +76,6 @@ public class Jsr250BusinessServiceImpl implements BusinessService {
|
||||
@Override
|
||||
@RolesAllowed({ "USER" })
|
||||
public void rolesAllowedUser() {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -91,7 +91,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void customDefaultRolePrefix() throws Exception {
|
||||
this.mds.setDefaultRolePrefix("CUSTOMPREFIX_");
|
||||
|
||||
ConfigAttribute[] accessAttributes = findAttributes("adminMethod");
|
||||
assertThat(accessAttributes).hasSize(1);
|
||||
assertThat(accessAttributes[0].toString()).isEqualTo("CUSTOMPREFIX_ADMIN");
|
||||
@@ -100,7 +99,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void emptyDefaultRolePrefix() throws Exception {
|
||||
this.mds.setDefaultRolePrefix("");
|
||||
|
||||
ConfigAttribute[] accessAttributes = findAttributes("adminMethod");
|
||||
assertThat(accessAttributes).hasSize(1);
|
||||
assertThat(accessAttributes[0].toString()).isEqualTo("ADMIN");
|
||||
@@ -109,7 +107,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void nullDefaultRolePrefix() throws Exception {
|
||||
this.mds.setDefaultRolePrefix(null);
|
||||
|
||||
ConfigAttribute[] accessAttributes = findAttributes("adminMethod");
|
||||
assertThat(accessAttributes).hasSize(1);
|
||||
assertThat(accessAttributes[0].toString()).isEqualTo("ADMIN");
|
||||
@@ -123,7 +120,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
}
|
||||
|
||||
// JSR-250 Spec Tests
|
||||
|
||||
/**
|
||||
* Class-level annotations only affect the class they annotate and their members, that
|
||||
* is, its methods and fields. They never affect a member declared by a superclass,
|
||||
@@ -134,7 +130,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
public void classLevelAnnotationsOnlyAffectTheClassTheyAnnotateAndTheirMembers() throws Exception {
|
||||
Child target = new Child();
|
||||
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "notOverriden");
|
||||
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
|
||||
assertThat(accessAttributes).isNull();
|
||||
}
|
||||
@@ -143,7 +138,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
public void classLevelAnnotationsOnlyAffectTheClassTheyAnnotateAndTheirMembersOverriden() throws Exception {
|
||||
Child target = new Child();
|
||||
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "overriden");
|
||||
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
|
||||
assertThat(accessAttributes).hasSize(1);
|
||||
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_DERIVED");
|
||||
@@ -153,7 +147,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
public void classLevelAnnotationsImpactMemberLevel() throws Exception {
|
||||
Child target = new Child();
|
||||
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "defaults");
|
||||
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
|
||||
assertThat(accessAttributes).hasSize(1);
|
||||
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_DERIVED");
|
||||
@@ -163,7 +156,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
public void classLevelAnnotationsIgnoredByExplicitMemberAnnotation() throws Exception {
|
||||
Child target = new Child();
|
||||
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "explicitMethod");
|
||||
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
|
||||
assertThat(accessAttributes).hasSize(1);
|
||||
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_EXPLICIT");
|
||||
@@ -178,7 +170,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
public void interfacesNeverContributeAnnotationsMethodLevel() throws Exception {
|
||||
Parent target = new Parent();
|
||||
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "interfaceMethod");
|
||||
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
|
||||
assertThat(accessAttributes).isEmpty();
|
||||
}
|
||||
@@ -187,7 +178,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
public void interfacesNeverContributeAnnotationsClassLevel() throws Exception {
|
||||
Parent target = new Parent();
|
||||
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "notOverriden");
|
||||
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
|
||||
assertThat(accessAttributes).isEmpty();
|
||||
}
|
||||
@@ -196,7 +186,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
public void annotationsOnOverriddenMemberIgnored() throws Exception {
|
||||
Child target = new Child();
|
||||
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "overridenIgnored");
|
||||
|
||||
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
|
||||
assertThat(accessAttributes).hasSize(1);
|
||||
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_DERIVED");
|
||||
@@ -234,7 +223,6 @@ public class Jsr250MethodSecurityMetadataSourceTests {
|
||||
}
|
||||
|
||||
// JSR-250 Spec
|
||||
|
||||
@RolesAllowed("IPARENT")
|
||||
interface IParent {
|
||||
|
||||
|
||||
@@ -38,21 +38,17 @@ public class Jsr250VoterTests {
|
||||
public void supportsMultipleRolesCorrectly() {
|
||||
List<ConfigAttribute> attrs = new ArrayList<>();
|
||||
Jsr250Voter voter = new Jsr250Voter();
|
||||
|
||||
attrs.add(new Jsr250SecurityConfig("A"));
|
||||
attrs.add(new Jsr250SecurityConfig("B"));
|
||||
attrs.add(new Jsr250SecurityConfig("C"));
|
||||
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "A"), new Object(), attrs))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "B"), new Object(), attrs))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "C"), new Object(), attrs))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "NONE"), new Object(), attrs))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
|
||||
|
||||
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "A"), new Object(),
|
||||
SecurityConfig.createList("A", "B", "C"))).isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
|
||||
}
|
||||
|
||||
@@ -54,39 +54,29 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void genericsSuperclassDeclarationsAreIncludedWhenSubclassesOverride() {
|
||||
Method method = null;
|
||||
|
||||
try {
|
||||
method = DepartmentServiceImpl.class.getMethod("someUserMethod3", new Class[] { Department.class });
|
||||
}
|
||||
catch (NoSuchMethodException unexpected) {
|
||||
fail("Should be a superMethod called 'someUserMethod3' on class!");
|
||||
}
|
||||
|
||||
Collection<ConfigAttribute> attrs = this.mds.findAttributes(method, DepartmentServiceImpl.class);
|
||||
|
||||
assertThat(attrs).isNotNull();
|
||||
|
||||
// expect 1 attribute
|
||||
assertThat(attrs.size() == 1).as("Did not find 1 attribute").isTrue();
|
||||
|
||||
// should have 1 SecurityConfig
|
||||
for (ConfigAttribute sc : attrs) {
|
||||
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo("ROLE_ADMIN");
|
||||
}
|
||||
|
||||
Method superMethod = null;
|
||||
|
||||
try {
|
||||
superMethod = DepartmentServiceImpl.class.getMethod("someUserMethod3", new Class[] { Entity.class });
|
||||
}
|
||||
catch (NoSuchMethodException unexpected) {
|
||||
fail("Should be a superMethod called 'someUserMethod3' on class!");
|
||||
}
|
||||
|
||||
Collection<ConfigAttribute> superAttrs = this.mds.findAttributes(superMethod, DepartmentServiceImpl.class);
|
||||
|
||||
assertThat(superAttrs).isNotNull();
|
||||
|
||||
// This part of the test relates to SEC-274
|
||||
// expect 1 attribute
|
||||
assertThat(superAttrs).as("Did not find 1 attribute").hasSize(1);
|
||||
@@ -99,41 +89,31 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void classLevelAttributesAreFound() {
|
||||
Collection<ConfigAttribute> attrs = this.mds.findAttributes(BusinessService.class);
|
||||
|
||||
assertThat(attrs).isNotNull();
|
||||
|
||||
// expect 1 annotation
|
||||
assertThat(attrs).hasSize(1);
|
||||
|
||||
// should have 1 SecurityConfig
|
||||
SecurityConfig sc = (SecurityConfig) attrs.toArray()[0];
|
||||
|
||||
assertThat(sc.getAttribute()).isEqualTo("ROLE_USER");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void methodLevelAttributesAreFound() {
|
||||
Method method = null;
|
||||
|
||||
try {
|
||||
method = BusinessService.class.getMethod("someUserAndAdminMethod", new Class[] {});
|
||||
}
|
||||
catch (NoSuchMethodException unexpected) {
|
||||
fail("Should be a method called 'someUserAndAdminMethod' on class!");
|
||||
}
|
||||
|
||||
Collection<ConfigAttribute> attrs = this.mds.findAttributes(method, BusinessService.class);
|
||||
|
||||
// expect 2 attributes
|
||||
assertThat(attrs).hasSize(2);
|
||||
|
||||
boolean user = false;
|
||||
boolean admin = false;
|
||||
|
||||
// should have 2 SecurityConfigs
|
||||
for (ConfigAttribute sc : attrs) {
|
||||
assertThat(sc).isInstanceOf(SecurityConfig.class);
|
||||
|
||||
if (sc.getAttribute().equals("ROLE_USER")) {
|
||||
user = true;
|
||||
}
|
||||
@@ -141,7 +121,6 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
|
||||
admin = true;
|
||||
}
|
||||
}
|
||||
|
||||
// expect to have ROLE_USER and ROLE_ADMIN
|
||||
assertThat(user).isEqualTo(admin).isTrue();
|
||||
}
|
||||
@@ -159,9 +138,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
|
||||
public void annotatedAnnotationAtClassLevelIsDetected() throws Exception {
|
||||
MockMethodInvocation annotatedAtClassLevel = new MockMethodInvocation(new AnnotatedAnnotationAtClassLevel(),
|
||||
ReturnVoid.class, "doSomething", List.class);
|
||||
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(annotatedAtClassLevel).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
assertThat(attrs).extracting("attribute").containsOnly("CUSTOM");
|
||||
}
|
||||
@@ -170,9 +147,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
|
||||
public void annotatedAnnotationAtInterfaceLevelIsDetected() throws Exception {
|
||||
MockMethodInvocation annotatedAtInterfaceLevel = new MockMethodInvocation(
|
||||
new AnnotatedAnnotationAtInterfaceLevel(), ReturnVoid2.class, "doSomething", List.class);
|
||||
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(annotatedAtInterfaceLevel).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
assertThat(attrs).extracting("attribute").containsOnly("CUSTOM");
|
||||
}
|
||||
@@ -182,7 +157,6 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
|
||||
MockMethodInvocation annotatedAtMethodLevel = new MockMethodInvocation(new AnnotatedAnnotationAtMethodLevel(),
|
||||
ReturnVoid.class, "doSomething", List.class);
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(annotatedAtMethodLevel).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
assertThat(attrs).extracting("attribute").containsOnly("CUSTOM");
|
||||
}
|
||||
@@ -223,7 +197,6 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
|
||||
}
|
||||
|
||||
// SEC-1491 Related classes. PoC for custom annotation with enum value.
|
||||
|
||||
@CustomSecurityAnnotation(SecurityEnum.ADMIN)
|
||||
interface CustomAnnotatedService {
|
||||
|
||||
@@ -262,7 +235,6 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
|
||||
@Override
|
||||
public Collection<? extends ConfigAttribute> extractAttributes(CustomSecurityAnnotation securityAnnotation) {
|
||||
SecurityEnum[] values = securityAnnotation.value();
|
||||
|
||||
return EnumSet.copyOf(Arrays.asList(values));
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ public class AbstractSecurityExpressionHandlerTests {
|
||||
@Test
|
||||
public void beanNamesAreCorrectlyResolved() {
|
||||
this.handler.setApplicationContext(new AnnotationConfigApplicationContext(TestConfiguration.class));
|
||||
|
||||
Expression expression = this.handler.getExpressionParser()
|
||||
.parseExpression("@number10.compareTo(@number20) < 0");
|
||||
assertThat(expression.getValue(this.handler.createEvaluationContext(mock(Authentication.class), new Object())))
|
||||
|
||||
@@ -64,7 +64,6 @@ public class SecurityExpressionRootTests {
|
||||
@Test
|
||||
public void roleHierarchySupportIsCorrectlyUsedInEvaluatingRoles() {
|
||||
this.root.setRoleHierarchy((authorities) -> AuthorityUtils.createAuthorityList("ROLE_C"));
|
||||
|
||||
assertThat(this.root.hasRole("C")).isTrue();
|
||||
assertThat(this.root.hasAuthority("ROLE_C")).isTrue();
|
||||
assertThat(this.root.hasRole("A")).isFalse();
|
||||
@@ -98,7 +97,6 @@ public class SecurityExpressionRootTests {
|
||||
public void hasRoleDoesNotAddDefaultPrefixForAlreadyPrefixedRoles() {
|
||||
SecurityExpressionRoot root = new SecurityExpressionRoot(JOE) {
|
||||
};
|
||||
|
||||
assertThat(root.hasRole("ROLE_A")).isTrue();
|
||||
assertThat(root.hasRole("ROLE_NO")).isFalse();
|
||||
}
|
||||
|
||||
@@ -77,11 +77,9 @@ public class DefaultMethodSecurityExpressionHandlerTests {
|
||||
@Test
|
||||
public void createEvaluationContextCustomTrustResolver() {
|
||||
this.handler.setTrustResolver(this.trustResolver);
|
||||
|
||||
Expression expression = this.handler.getExpressionParser().parseExpression("anonymous");
|
||||
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
|
||||
expression.getValue(context, Boolean.class);
|
||||
|
||||
verify(this.trustResolver).isAnonymous(this.authentication);
|
||||
}
|
||||
|
||||
@@ -92,13 +90,9 @@ public class DefaultMethodSecurityExpressionHandlerTests {
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
map.put("key3", "value3");
|
||||
|
||||
Expression expression = this.handler.getExpressionParser().parseExpression("filterObject.key eq 'key2'");
|
||||
|
||||
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
|
||||
|
||||
Object filtered = this.handler.filter(map, expression, context);
|
||||
|
||||
assertThat(filtered == map);
|
||||
Map<String, String> result = ((Map<String, String>) filtered);
|
||||
assertThat(result.size() == 1);
|
||||
@@ -113,13 +107,9 @@ public class DefaultMethodSecurityExpressionHandlerTests {
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
map.put("key3", "value3");
|
||||
|
||||
Expression expression = this.handler.getExpressionParser().parseExpression("filterObject.value eq 'value3'");
|
||||
|
||||
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
|
||||
|
||||
Object filtered = this.handler.filter(map, expression, context);
|
||||
|
||||
assertThat(filtered == map);
|
||||
Map<String, String> result = ((Map<String, String>) filtered);
|
||||
assertThat(result.size() == 1);
|
||||
@@ -134,14 +124,10 @@ public class DefaultMethodSecurityExpressionHandlerTests {
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
map.put("key3", "value3");
|
||||
|
||||
Expression expression = this.handler.getExpressionParser()
|
||||
.parseExpression("(filterObject.key eq 'key1') or (filterObject.value eq 'value2')");
|
||||
|
||||
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
|
||||
|
||||
Object filtered = this.handler.filter(map, expression, context);
|
||||
|
||||
assertThat(filtered == map);
|
||||
Map<String, String> result = ((Map<String, String>) filtered);
|
||||
assertThat(result.size() == 2);
|
||||
@@ -153,13 +139,9 @@ public class DefaultMethodSecurityExpressionHandlerTests {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void filterWhenUsingStreamThenFiltersStream() {
|
||||
final Stream<String> stream = Stream.of("1", "2", "3");
|
||||
|
||||
Expression expression = this.handler.getExpressionParser().parseExpression("filterObject ne '2'");
|
||||
|
||||
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
|
||||
|
||||
Object filtered = this.handler.filter(stream, expression, context);
|
||||
|
||||
assertThat(filtered).isInstanceOf(Stream.class);
|
||||
List<String> list = ((Stream<String>) filtered).collect(Collectors.toList());
|
||||
assertThat(list).containsExactly("1", "3");
|
||||
@@ -169,11 +151,8 @@ public class DefaultMethodSecurityExpressionHandlerTests {
|
||||
public void filterStreamWhenClosedThenUpstreamGetsClosed() {
|
||||
final Stream<?> upstream = mock(Stream.class);
|
||||
doReturn(Stream.<String>empty()).when(upstream).filter(any());
|
||||
|
||||
Expression expression = this.handler.getExpressionParser().parseExpression("true");
|
||||
|
||||
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
|
||||
|
||||
((Stream) this.handler.filter(upstream, expression, context)).close();
|
||||
verify(upstream).close();
|
||||
}
|
||||
|
||||
@@ -113,9 +113,8 @@ public class MethodExpressionVoterTests {
|
||||
@Test
|
||||
public void ruleDefinedInAClassMethodIsApplied() throws Exception {
|
||||
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAString(), "joe");
|
||||
assertThat(
|
||||
|
||||
this.am.vote(this.joe, mi, createAttributes(new PreInvocationExpressionAttribute(null, null,
|
||||
assertThat(this.am.vote(this.joe, mi,
|
||||
createAttributes(new PreInvocationExpressionAttribute(null, null,
|
||||
"T(org.springframework.security.access.expression.method.SecurityRules).isJoe(#argument)"))))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
}
|
||||
|
||||
@@ -64,7 +64,6 @@ public class MethodSecurityExpressionRootTests {
|
||||
public void canCallMethodsOnVariables() {
|
||||
this.ctx.setVariable("var", "somestring");
|
||||
Expression e = this.parser.parseExpression("#var.length() == 10");
|
||||
|
||||
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();
|
||||
}
|
||||
|
||||
@@ -87,9 +86,7 @@ public class MethodSecurityExpressionRootTests {
|
||||
this.ctx.setVariable("domainObject", dummyDomainObject);
|
||||
this.root.setPermissionEvaluator(pe);
|
||||
given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(false);
|
||||
|
||||
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isFalse();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -99,7 +96,6 @@ public class MethodSecurityExpressionRootTests {
|
||||
this.ctx.setVariable("domainObject", dummyDomainObject);
|
||||
this.root.setPermissionEvaluator(pe);
|
||||
given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(true);
|
||||
|
||||
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isTrue();
|
||||
}
|
||||
|
||||
@@ -110,7 +106,6 @@ public class MethodSecurityExpressionRootTests {
|
||||
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
|
||||
this.root.setPermissionEvaluator(pe);
|
||||
given(pe.hasPermission(eq(this.user), eq(dummyDomainObject), any(Integer.class))).willReturn(true, true, false);
|
||||
|
||||
Expression e = this.parser.parseExpression("hasPermission(#domainObject, 0xA)");
|
||||
// evaluator returns true
|
||||
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();
|
||||
@@ -135,12 +130,10 @@ public class MethodSecurityExpressionRootTests {
|
||||
this.root.setPermissionEvaluator(pe);
|
||||
given(pe.hasPermission(this.user, targetObject, i)).willReturn(true, false);
|
||||
given(pe.hasPermission(this.user, "x", i)).willReturn(true);
|
||||
|
||||
Expression e = this.parser.parseExpression("hasPermission(this, 2)");
|
||||
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();
|
||||
e = this.parser.parseExpression("hasPermission(this, 2)");
|
||||
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isFalse();
|
||||
|
||||
e = this.parser.parseExpression("hasPermission(this.x, 2)");
|
||||
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();
|
||||
}
|
||||
|
||||
@@ -88,7 +88,6 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void classLevelPreAnnotationIsPickedUpWhenNoMethodLevelExists() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.voidImpl1).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
|
||||
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
|
||||
@@ -100,7 +99,6 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void mixedClassAndMethodPreAnnotationsAreBothIncluded() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.voidImpl2).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
|
||||
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
|
||||
@@ -112,7 +110,6 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void methodWithPreFilterOnlyIsAllowed() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.voidImpl3).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
|
||||
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
|
||||
@@ -124,7 +121,6 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void methodWithPostFilterOnlyIsAllowed() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.listImpl1).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(2);
|
||||
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
|
||||
assertThat(attrs[1] instanceof PostInvocationExpressionAttribute).isTrue();
|
||||
@@ -138,7 +134,6 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void interfaceAttributesAreIncluded() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.notherListImpl1).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
|
||||
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
|
||||
@@ -151,7 +146,6 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void classAttributesTakesPrecedeceOverInterfaceAttributes() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.notherListImpl2).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
|
||||
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
|
||||
@@ -164,7 +158,6 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
|
||||
@Test
|
||||
public void customAnnotationAtClassLevelIsDetected() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtClassLevel).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
}
|
||||
|
||||
@@ -172,14 +165,12 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
|
||||
public void customAnnotationAtInterfaceLevelIsDetected() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtInterfaceLevel)
|
||||
.toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customAnnotationAtMethodLevelIsDetected() {
|
||||
ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtMethodLevel).toArray(new ConfigAttribute[0]);
|
||||
|
||||
assertThat(attrs).hasSize(1);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ public abstract class HierarchicalRolesTestHelper {
|
||||
if (authorities1 == null && authorities2 == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (authorities1 == null || authorities2 == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -48,7 +47,6 @@ public abstract class HierarchicalRolesTestHelper {
|
||||
if (authorities1 == null && authorities2 == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (authorities1 == null || authorities2 == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -60,7 +58,6 @@ public abstract class HierarchicalRolesTestHelper {
|
||||
if (authorities == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<String> result = new ArrayList<>(authorities.size());
|
||||
for (GrantedAuthority authority : authorities) {
|
||||
result.add(authority.getAuthority());
|
||||
@@ -70,12 +67,10 @@ public abstract class HierarchicalRolesTestHelper {
|
||||
|
||||
public static List<GrantedAuthority> createAuthorityList(final String... roles) {
|
||||
List<GrantedAuthority> authorities = new ArrayList<>(roles.length);
|
||||
|
||||
for (final String role : roles) {
|
||||
// Use non SimpleGrantedAuthority (SEC-863)
|
||||
authorities.add((GrantedAuthority) () -> role);
|
||||
}
|
||||
|
||||
return authorities;
|
||||
}
|
||||
|
||||
|
||||
@@ -35,16 +35,11 @@ public class RoleHierarchyAuthoritiesMapperTests {
|
||||
RoleHierarchyImpl rh = new RoleHierarchyImpl();
|
||||
rh.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C");
|
||||
RoleHierarchyAuthoritiesMapper mapper = new RoleHierarchyAuthoritiesMapper(rh);
|
||||
|
||||
Collection<? extends GrantedAuthority> authorities = mapper
|
||||
.mapAuthorities(AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_D"));
|
||||
|
||||
assertThat(authorities).hasSize(4);
|
||||
|
||||
mapper = new RoleHierarchyAuthoritiesMapper(new NullRoleHierarchy());
|
||||
|
||||
authorities = mapper.mapAuthorities(AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_D"));
|
||||
|
||||
assertThat(authorities).hasSize(2);
|
||||
}
|
||||
|
||||
|
||||
@@ -38,27 +38,21 @@ public class RoleHierarchyImplTests {
|
||||
public void testRoleHierarchyWithNullOrEmptyAuthorities() {
|
||||
List<GrantedAuthority> authorities0 = null;
|
||||
List<GrantedAuthority> authorities1 = new ArrayList<>();
|
||||
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
|
||||
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isNotNull();
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isEmpty();
|
||||
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isNotNull();
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSimpleRoleHierarchy() {
|
||||
|
||||
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");
|
||||
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), authorities0)).isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
@@ -73,13 +67,10 @@ public class RoleHierarchyImplTests {
|
||||
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();
|
||||
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
|
||||
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_D");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities3)).isTrue();
|
||||
@@ -96,10 +87,8 @@ public class RoleHierarchyImplTests {
|
||||
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");
|
||||
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput1), authoritiesOutput1)).isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
@@ -113,28 +102,24 @@ public class RoleHierarchyImplTests {
|
||||
@Test
|
||||
public void testCyclesInRoleHierarchy() {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
|
||||
try {
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_A");
|
||||
fail("Cycle in role hierarchy was not detected!");
|
||||
}
|
||||
catch (CycleInRoleHierarchyException ex) {
|
||||
}
|
||||
|
||||
try {
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_A");
|
||||
fail("Cycle in role hierarchy was not detected!");
|
||||
}
|
||||
catch (CycleInRoleHierarchyException ex) {
|
||||
}
|
||||
|
||||
try {
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A");
|
||||
fail("Cycle in role hierarchy was not detected!");
|
||||
}
|
||||
catch (CycleInRoleHierarchyException ex) {
|
||||
}
|
||||
|
||||
try {
|
||||
roleHierarchyImpl.setHierarchy(
|
||||
"ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B");
|
||||
@@ -142,7 +127,6 @@ public class RoleHierarchyImplTests {
|
||||
}
|
||||
catch (CycleInRoleHierarchyException ex) {
|
||||
}
|
||||
|
||||
try {
|
||||
roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B");
|
||||
fail("Cycle in role hierarchy was not detected!");
|
||||
@@ -154,7 +138,6 @@ public class RoleHierarchyImplTests {
|
||||
@Test
|
||||
public void testNoCyclesInRoleHierarchy() {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
|
||||
try {
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
|
||||
}
|
||||
@@ -166,14 +149,11 @@ public class RoleHierarchyImplTests {
|
||||
// SEC-863
|
||||
@Test
|
||||
public void testSimpleRoleHierarchyWithCustomGrantedAuthorityImplementation() {
|
||||
|
||||
List<GrantedAuthority> authorities0 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_0");
|
||||
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A");
|
||||
List<GrantedAuthority> authorities2 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A", "ROLE_B");
|
||||
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
|
||||
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), authorities0)).isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
|
||||
@@ -188,13 +168,10 @@ public class RoleHierarchyImplTests {
|
||||
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();
|
||||
|
||||
roleHierarchyImpl.setHierarchy("ROLE A > ROLE B\nROLE B > ROLE>C");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
|
||||
|
||||
roleHierarchyImpl.setHierarchy("ROLE A > ROLE B\nROLE B > ROLE>C\nROLE>C > ROLE D");
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
|
||||
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities3)).isTrue();
|
||||
@@ -209,7 +186,6 @@ public class RoleHierarchyImplTests {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy(
|
||||
"ROLE_A > ROLE_B\n" + "ROLE_B > ROLE_AUTHENTICATED\n" + "ROLE_AUTHENTICATED > ROLE_UNAUTHENTICATED");
|
||||
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
|
||||
.containsExactlyInAnyOrderElementsOf(allAuthorities);
|
||||
}
|
||||
@@ -223,7 +199,6 @@ public class RoleHierarchyImplTests {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl
|
||||
.setHierarchy("ROLE_HIGHEST > ROLE_HIGHER\n" + "ROLE_HIGHER > ROLE_LOW\n" + "ROLE_LOW > ROLE_LOWER");
|
||||
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
|
||||
.containsExactlyInAnyOrderElementsOf(allAuthorities);
|
||||
}
|
||||
@@ -236,7 +211,6 @@ public class RoleHierarchyImplTests {
|
||||
"ROLE_LOW", "ROLE_LOWER");
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_HIGHEST > ROLE_HIGHER > ROLE_LOW > ROLE_LOWER");
|
||||
|
||||
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
|
||||
.containsExactlyInAnyOrderElementsOf(allAuthorities);
|
||||
}
|
||||
|
||||
@@ -44,14 +44,11 @@ public class RoleHierarchyUtilsTests {
|
||||
"ROLE_B > ROLE_D" + EOL +
|
||||
"ROLE_C > ROLE_D" + EOL;
|
||||
// @formatter:on
|
||||
|
||||
Map<String, List<String>> roleHierarchyMap = new TreeMap<>();
|
||||
roleHierarchyMap.put("ROLE_A", Arrays.asList("ROLE_B", "ROLE_C"));
|
||||
roleHierarchyMap.put("ROLE_B", Arrays.asList("ROLE_D"));
|
||||
roleHierarchyMap.put("ROLE_C", Arrays.asList("ROLE_D"));
|
||||
|
||||
String roleHierarchy = RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
|
||||
|
||||
assertThat(roleHierarchy).isEqualTo(expectedRoleHierarchy);
|
||||
}
|
||||
|
||||
@@ -69,7 +66,6 @@ public class RoleHierarchyUtilsTests {
|
||||
public void roleHierarchyFromMapWhenRoleNullThenThrowsIllegalArgumentException() {
|
||||
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
|
||||
roleHierarchyMap.put(null, Arrays.asList("ROLE_B", "ROLE_C"));
|
||||
|
||||
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
|
||||
}
|
||||
|
||||
@@ -77,7 +73,6 @@ public class RoleHierarchyUtilsTests {
|
||||
public void roleHierarchyFromMapWhenRoleEmptyThenThrowsIllegalArgumentException() {
|
||||
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
|
||||
roleHierarchyMap.put("", Arrays.asList("ROLE_B", "ROLE_C"));
|
||||
|
||||
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
|
||||
}
|
||||
|
||||
@@ -85,7 +80,6 @@ public class RoleHierarchyUtilsTests {
|
||||
public void roleHierarchyFromMapWhenImpliedRolesNullThenThrowsIllegalArgumentException() {
|
||||
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
|
||||
roleHierarchyMap.put("ROLE_A", null);
|
||||
|
||||
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
|
||||
}
|
||||
|
||||
@@ -93,7 +87,6 @@ public class RoleHierarchyUtilsTests {
|
||||
public void roleHierarchyFromMapWhenImpliedRolesEmptyThenThrowsIllegalArgumentException() {
|
||||
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
|
||||
roleHierarchyMap.put("ROLE_A", Collections.<String>emptyList());
|
||||
|
||||
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
|
||||
}
|
||||
|
||||
|
||||
@@ -42,12 +42,10 @@ public class TestHelperTests {
|
||||
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");
|
||||
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, null)).isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities1)).isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities2)).isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities2, authorities1)).isTrue();
|
||||
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, authorities1)).isFalse();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, null)).isFalse();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities3)).isFalse();
|
||||
@@ -65,42 +63,32 @@ public class TestHelperTests {
|
||||
Collection<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_C");
|
||||
Collection<GrantedAuthority> authorities4 = AuthorityUtils.createAuthorityList("ROLE_A");
|
||||
Collection<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_A");
|
||||
|
||||
List<String> authoritiesStrings1 = new ArrayList<>();
|
||||
authoritiesStrings1.add("ROLE_A");
|
||||
authoritiesStrings1.add("ROLE_B");
|
||||
|
||||
List<String> authoritiesStrings2 = new ArrayList<>();
|
||||
authoritiesStrings2.add("ROLE_B");
|
||||
authoritiesStrings2.add("ROLE_A");
|
||||
|
||||
List<String> authoritiesStrings3 = new ArrayList<>();
|
||||
authoritiesStrings3.add("ROLE_A");
|
||||
authoritiesStrings3.add("ROLE_C");
|
||||
|
||||
List<String> authoritiesStrings4 = new ArrayList<>();
|
||||
authoritiesStrings4.add("ROLE_A");
|
||||
|
||||
List<String> authoritiesStrings5 = new ArrayList<>();
|
||||
authoritiesStrings5.add("ROLE_A");
|
||||
authoritiesStrings5.add("ROLE_A");
|
||||
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities1), authoritiesStrings1))
|
||||
.isTrue();
|
||||
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities2), authoritiesStrings2))
|
||||
.isTrue();
|
||||
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities3), authoritiesStrings3))
|
||||
.isTrue();
|
||||
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities4), authoritiesStrings4))
|
||||
.isTrue();
|
||||
|
||||
assertThat(CollectionUtils.isEqualCollection(
|
||||
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities5), authoritiesStrings5))
|
||||
.isTrue();
|
||||
@@ -114,12 +102,10 @@ public class TestHelperTests {
|
||||
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");
|
||||
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, null)).isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities1)).isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities2)).isTrue();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities2, authorities1)).isTrue();
|
||||
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, authorities1)).isFalse();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, null)).isFalse();
|
||||
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities3)).isFalse();
|
||||
@@ -144,7 +130,6 @@ public class TestHelperTests {
|
||||
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A");
|
||||
assertThat(authorities1).hasSize(1);
|
||||
assertThat(authorities1.get(0).getAuthority()).isEqualTo("ROLE_A");
|
||||
|
||||
List<GrantedAuthority> authorities2 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A", "ROLE_C");
|
||||
assertThat(authorities2).hasSize(2);
|
||||
assertThat(authorities2.get(0).getAuthority()).isEqualTo("ROLE_A");
|
||||
|
||||
@@ -36,7 +36,6 @@ public class AbstractSecurityInterceptorTests {
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void detectsIfInvocationPassedIncompatibleSecureObject() {
|
||||
MockSecurityInterceptorWhichOnlySupportsStrings si = new MockSecurityInterceptorWhichOnlySupportsStrings();
|
||||
|
||||
si.setRunAsManager(mock(RunAsManager.class));
|
||||
si.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
si.setAfterInvocationManager(mock(AfterInvocationManager.class));
|
||||
|
||||
@@ -51,25 +51,19 @@ public class AfterInvocationProviderManagerTests {
|
||||
manager.setProviders(list);
|
||||
assertThat(manager.getProviders()).isEqualTo(list);
|
||||
manager.afterPropertiesSet();
|
||||
|
||||
List<ConfigAttribute> attr1 = SecurityConfig.createList(new String[] { "GIVE_ME_SWAP1" });
|
||||
List<ConfigAttribute> attr2 = SecurityConfig.createList(new String[] { "GIVE_ME_SWAP2" });
|
||||
List<ConfigAttribute> attr3 = SecurityConfig.createList(new String[] { "GIVE_ME_SWAP3" });
|
||||
List<ConfigAttribute> attr2and3 = SecurityConfig.createList(new String[] { "GIVE_ME_SWAP2", "GIVE_ME_SWAP3" });
|
||||
List<ConfigAttribute> attr4 = SecurityConfig.createList(new String[] { "NEVER_CAUSES_SWAP" });
|
||||
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr1, "content-before-swapping"))
|
||||
.isEqualTo("swap1");
|
||||
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2, "content-before-swapping"))
|
||||
.isEqualTo("swap2");
|
||||
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr3, "content-before-swapping"))
|
||||
.isEqualTo("swap3");
|
||||
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr4, "content-before-swapping"))
|
||||
.isEqualTo("content-before-swapping");
|
||||
|
||||
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2and3, "content-before-swapping"))
|
||||
.isEqualTo("swap3");
|
||||
}
|
||||
@@ -78,7 +72,6 @@ public class AfterInvocationProviderManagerTests {
|
||||
public void testRejectsEmptyProvidersList() {
|
||||
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
|
||||
List list = new Vector();
|
||||
|
||||
try {
|
||||
manager.setProviders(list);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
@@ -95,7 +88,6 @@ public class AfterInvocationProviderManagerTests {
|
||||
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
|
||||
list.add(45);
|
||||
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
|
||||
|
||||
try {
|
||||
manager.setProviders(list);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
@@ -108,7 +100,6 @@ public class AfterInvocationProviderManagerTests {
|
||||
@Test
|
||||
public void testRejectsNullProvidersList() throws Exception {
|
||||
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
|
||||
|
||||
try {
|
||||
manager.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
@@ -127,7 +118,6 @@ public class AfterInvocationProviderManagerTests {
|
||||
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
|
||||
manager.setProviders(list);
|
||||
manager.afterPropertiesSet();
|
||||
|
||||
assertThat(manager.supports(new SecurityConfig("UNKNOWN_ATTRIB"))).isFalse();
|
||||
assertThat(manager.supports(new SecurityConfig("GIVE_ME_SWAP2"))).isTrue();
|
||||
}
|
||||
@@ -141,7 +131,6 @@ public class AfterInvocationProviderManagerTests {
|
||||
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
|
||||
manager.setProviders(list);
|
||||
manager.afterPropertiesSet();
|
||||
|
||||
// assertFalse(manager.supports(FilterInvocation.class));
|
||||
assertThat(manager.supports(MethodInvocation.class)).isTrue();
|
||||
}
|
||||
@@ -171,7 +160,6 @@ public class AfterInvocationProviderManagerTests {
|
||||
if (config.contains(this.configAttribute)) {
|
||||
return this.forceReturnObject;
|
||||
}
|
||||
|
||||
return returnedObject;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,6 @@ public class InterceptorStatusTokenTests {
|
||||
MethodInvocation mi = new SimpleMethodInvocation();
|
||||
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
|
||||
InterceptorStatusToken token = new InterceptorStatusToken(ctx, true, attr, mi);
|
||||
|
||||
assertThat(token.isContextHolderRefreshRequired()).isTrue();
|
||||
assertThat(token.getAttributes()).isEqualTo(attr);
|
||||
assertThat(token.getSecureObject()).isEqualTo(mi);
|
||||
|
||||
@@ -38,7 +38,6 @@ public class RunAsImplAuthenticationProviderTests {
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class);
|
||||
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
|
||||
provider.setKey("hello_world");
|
||||
|
||||
provider.authenticate(token);
|
||||
}
|
||||
|
||||
@@ -48,11 +47,8 @@ public class RunAsImplAuthenticationProviderTests {
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class);
|
||||
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
|
||||
provider.setKey("my_password");
|
||||
|
||||
Authentication result = provider.authenticate(token);
|
||||
|
||||
Assert.assertTrue("Should have returned RunAsUserToken", result instanceof RunAsUserToken);
|
||||
|
||||
RunAsUserToken resultCast = (RunAsUserToken) result;
|
||||
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
|
||||
}
|
||||
@@ -60,7 +56,6 @@ public class RunAsImplAuthenticationProviderTests {
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testStartupFailsIfNoKey() throws Exception {
|
||||
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
|
||||
|
||||
provider.afterPropertiesSet();
|
||||
}
|
||||
|
||||
|
||||
@@ -45,10 +45,8 @@ public class RunAsManagerImplTests {
|
||||
public void testDoesNotReturnAdditionalAuthoritiesIfCalledWithoutARunAsSetting() {
|
||||
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||
|
||||
RunAsManagerImpl runAs = new RunAsManagerImpl();
|
||||
runAs.setKey("my_password");
|
||||
|
||||
Authentication resultingToken = runAs.buildRunAs(inputToken, new Object(),
|
||||
SecurityConfig.createList("SOMETHING_WE_IGNORE"));
|
||||
assertThat(resultingToken).isNull();
|
||||
@@ -58,23 +56,18 @@ public class RunAsManagerImplTests {
|
||||
public void testRespectsRolePrefix() {
|
||||
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password",
|
||||
AuthorityUtils.createAuthorityList("ONE", "TWO"));
|
||||
|
||||
RunAsManagerImpl runAs = new RunAsManagerImpl();
|
||||
runAs.setKey("my_password");
|
||||
runAs.setRolePrefix("FOOBAR_");
|
||||
|
||||
Authentication result = runAs.buildRunAs(inputToken, new Object(),
|
||||
SecurityConfig.createList("RUN_AS_SOMETHING"));
|
||||
|
||||
assertThat(result instanceof RunAsUserToken).withFailMessage("Should have returned a RunAsUserToken").isTrue();
|
||||
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
|
||||
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
|
||||
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
|
||||
|
||||
assertThat(authorities.contains("FOOBAR_RUN_AS_SOMETHING")).isTrue();
|
||||
assertThat(authorities.contains("ONE")).isTrue();
|
||||
assertThat(authorities.contains("TWO")).isTrue();
|
||||
|
||||
RunAsUserToken resultCast = (RunAsUserToken) result;
|
||||
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
|
||||
}
|
||||
@@ -83,25 +76,19 @@ public class RunAsManagerImplTests {
|
||||
public void testReturnsAdditionalGrantedAuthorities() {
|
||||
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||
|
||||
RunAsManagerImpl runAs = new RunAsManagerImpl();
|
||||
runAs.setKey("my_password");
|
||||
|
||||
Authentication result = runAs.buildRunAs(inputToken, new Object(),
|
||||
SecurityConfig.createList("RUN_AS_SOMETHING"));
|
||||
|
||||
if (!(result instanceof RunAsUserToken)) {
|
||||
fail("Should have returned a RunAsUserToken");
|
||||
}
|
||||
|
||||
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
|
||||
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
|
||||
|
||||
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
|
||||
assertThat(authorities.contains("ROLE_RUN_AS_SOMETHING")).isTrue();
|
||||
assertThat(authorities.contains("ROLE_ONE")).isTrue();
|
||||
assertThat(authorities.contains("ROLE_TWO")).isTrue();
|
||||
|
||||
RunAsUserToken resultCast = (RunAsUserToken) result;
|
||||
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
|
||||
}
|
||||
@@ -109,13 +96,11 @@ public class RunAsManagerImplTests {
|
||||
@Test
|
||||
public void testStartupDetectsMissingKey() throws Exception {
|
||||
RunAsManagerImpl runAs = new RunAsManagerImpl();
|
||||
|
||||
try {
|
||||
runAs.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,6 @@ public class RunAsUserTokenTests {
|
||||
@Test
|
||||
public void testNoArgConstructorDoesntExist() {
|
||||
Class<RunAsUserToken> clazz = RunAsUserToken.class;
|
||||
|
||||
try {
|
||||
clazz.getDeclaredConstructor((Class[]) null);
|
||||
fail("Should have thrown NoSuchMethodException");
|
||||
|
||||
@@ -198,7 +198,6 @@ public class MethodSecurityInterceptorTests {
|
||||
given(this.adm.supports(MethodInvocation.class)).willReturn(true);
|
||||
given(this.mds.supports(MethodInvocation.class)).willReturn(true);
|
||||
given(this.mds.getAllConfigAttributes()).willReturn(null);
|
||||
|
||||
this.interceptor.setValidateConfigAttributes(true);
|
||||
this.interceptor.afterPropertiesSet();
|
||||
verify(this.adm, never()).supports(any(ConfigAttribute.class));
|
||||
@@ -224,10 +223,8 @@ public class MethodSecurityInterceptorTests {
|
||||
public void callIsntMadeWhenAuthenticationManagerRejectsAuthentication() {
|
||||
final TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password");
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
|
||||
mdsReturnsUserRole();
|
||||
given(this.authman.authenticate(token)).willThrow(new BadCredentialsException("rejected"));
|
||||
|
||||
this.advisedTarget.makeLowerCase("HELLO");
|
||||
}
|
||||
|
||||
@@ -237,9 +234,7 @@ public class MethodSecurityInterceptorTests {
|
||||
this.interceptor.setPublishAuthorizationSuccess(true);
|
||||
SecurityContextHolder.getContext().setAuthentication(this.token);
|
||||
mdsReturnsUserRole();
|
||||
|
||||
String result = this.advisedTarget.makeLowerCase("HELLO");
|
||||
|
||||
// Note we check the isAuthenticated remained true in following line
|
||||
assertThat(result)
|
||||
.isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken true");
|
||||
@@ -256,7 +251,6 @@ public class MethodSecurityInterceptorTests {
|
||||
given(this.authman.authenticate(this.token)).willReturn(this.token);
|
||||
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(any(Authentication.class),
|
||||
any(MethodInvocation.class), any(List.class));
|
||||
|
||||
try {
|
||||
this.advisedTarget.makeUpperCase("HELLO");
|
||||
fail("Expected Exception");
|
||||
@@ -282,7 +276,6 @@ public class MethodSecurityInterceptorTests {
|
||||
this.interceptor.setRunAsManager(runAs);
|
||||
mdsReturnsUserRole();
|
||||
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
|
||||
|
||||
String result = this.advisedTarget.makeUpperCase("hello");
|
||||
assertThat(result).isEqualTo("HELLO org.springframework.security.access.intercept.RunAsUserToken true");
|
||||
// Check we've changed back
|
||||
@@ -304,14 +297,12 @@ public class MethodSecurityInterceptorTests {
|
||||
this.interceptor.setRunAsManager(runAs);
|
||||
mdsReturnsUserRole();
|
||||
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
|
||||
|
||||
try {
|
||||
this.advisedTarget.makeUpperCase("hello");
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (RuntimeException success) {
|
||||
}
|
||||
|
||||
// Check we've changed back
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
|
||||
@@ -329,19 +320,15 @@ public class MethodSecurityInterceptorTests {
|
||||
this.token.setAuthenticated(true);
|
||||
SecurityContextHolder.getContext().setAuthentication(this.token);
|
||||
mdsReturnsUserRole();
|
||||
|
||||
AfterInvocationManager aim = mock(AfterInvocationManager.class);
|
||||
this.interceptor.setAfterInvocationManager(aim);
|
||||
|
||||
given(mi.proceed()).willThrow(new Throwable());
|
||||
|
||||
try {
|
||||
this.interceptor.invoke(mi);
|
||||
fail("Expected exception");
|
||||
}
|
||||
catch (Throwable expected) {
|
||||
}
|
||||
|
||||
verifyZeroInteractions(aim);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,6 @@ public class MethodSecurityMetadataSourceAdvisorTests {
|
||||
public void testAdvisorReturnsFalseWhenMethodInvocationNotDefined() throws Exception {
|
||||
Class<TargetObject> clazz = TargetObject.class;
|
||||
Method method = clazz.getMethod("makeLowerCase", new Class[] { String.class });
|
||||
|
||||
MethodSecurityMetadataSource mds = mock(MethodSecurityMetadataSource.class);
|
||||
given(mds.getAttributes(method, clazz)).willReturn(null);
|
||||
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor("", mds, "");
|
||||
@@ -50,7 +49,6 @@ public class MethodSecurityMetadataSourceAdvisorTests {
|
||||
public void testAdvisorReturnsTrueWhenMethodInvocationIsDefined() throws Exception {
|
||||
Class<TargetObject> clazz = TargetObject.class;
|
||||
Method method = clazz.getMethod("countLength", new Class[] { String.class });
|
||||
|
||||
MethodSecurityMetadataSource mds = mock(MethodSecurityMetadataSource.class);
|
||||
given(mds.getAttributes(method, clazz)).willReturn(SecurityConfig.createList("ROLE_A"));
|
||||
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor("", mds, "");
|
||||
|
||||
@@ -114,7 +114,6 @@ public class AspectJMethodSecurityInterceptorTests {
|
||||
SecurityContextHolder.getContext().setAuthentication(this.token);
|
||||
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
|
||||
verify(this.aspectJCallback).proceedWithObject();
|
||||
|
||||
// Just try the other method too
|
||||
this.interceptor.invoke(this.joinPoint);
|
||||
}
|
||||
@@ -123,7 +122,6 @@ public class AspectJMethodSecurityInterceptorTests {
|
||||
@Test
|
||||
public void callbackIsNotInvokedWhenPermissionDenied() {
|
||||
willThrow(new AccessDeniedException("denied")).given(this.adm).decide(any(), any(), any());
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(this.token);
|
||||
try {
|
||||
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
|
||||
@@ -138,7 +136,6 @@ public class AspectJMethodSecurityInterceptorTests {
|
||||
public void adapterHoldsCorrectData() {
|
||||
TargetObject to = new TargetObject();
|
||||
Method m = ClassUtils.getMethodIfAvailable(TargetObject.class, "countLength", new Class[] { String.class });
|
||||
|
||||
given(this.joinPoint.getTarget()).willReturn(to);
|
||||
given(this.joinPoint.getArgs()).willReturn(new Object[] { "Hi" });
|
||||
MethodInvocationAdapter mia = new MethodInvocationAdapter(this.joinPoint);
|
||||
@@ -152,19 +149,15 @@ public class AspectJMethodSecurityInterceptorTests {
|
||||
public void afterInvocationManagerIsNotInvokedIfExceptionIsRaised() {
|
||||
this.token.setAuthenticated(true);
|
||||
SecurityContextHolder.getContext().setAuthentication(this.token);
|
||||
|
||||
AfterInvocationManager aim = mock(AfterInvocationManager.class);
|
||||
this.interceptor.setAfterInvocationManager(aim);
|
||||
|
||||
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
|
||||
|
||||
try {
|
||||
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
|
||||
fail("Expected exception");
|
||||
}
|
||||
catch (RuntimeException expected) {
|
||||
}
|
||||
|
||||
verifyZeroInteractions(aim);
|
||||
}
|
||||
|
||||
@@ -181,14 +174,12 @@ public class AspectJMethodSecurityInterceptorTests {
|
||||
this.interceptor.setRunAsManager(runAs);
|
||||
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
|
||||
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
|
||||
|
||||
try {
|
||||
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (RuntimeException success) {
|
||||
}
|
||||
|
||||
// Check we've changed back
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
|
||||
@@ -207,14 +198,12 @@ public class AspectJMethodSecurityInterceptorTests {
|
||||
this.interceptor.setRunAsManager(runAs);
|
||||
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
|
||||
given(this.joinPoint.proceed()).willThrow(new RuntimeException());
|
||||
|
||||
try {
|
||||
this.interceptor.invoke(this.joinPoint);
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (RuntimeException success) {
|
||||
}
|
||||
|
||||
// Check we've changed back
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
|
||||
|
||||
@@ -64,7 +64,6 @@ public class MapBasedMethodSecurityMetadataSourceTests {
|
||||
public void methodsWithDifferentArgumentsAreMatchedCorrectly() {
|
||||
this.mds.addSecureMethod(MockService.class, this.someMethodInteger, this.ROLE_A);
|
||||
this.mds.addSecureMethod(MockService.class, this.someMethodString, this.ROLE_B);
|
||||
|
||||
assertThat(this.mds.getAttributes(this.someMethodInteger, MockService.class)).isEqualTo(this.ROLE_A);
|
||||
assertThat(this.mds.getAttributes(this.someMethodString, MockService.class)).isEqualTo(this.ROLE_B);
|
||||
}
|
||||
|
||||
@@ -78,13 +78,10 @@ public class MethodInvocationPrivilegeEvaluatorTests {
|
||||
public void allowsAccessUsingCreate() throws Exception {
|
||||
Object object = new TargetObject();
|
||||
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
|
||||
|
||||
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
|
||||
given(this.mds.getAttributes(mi)).willReturn(this.role);
|
||||
|
||||
mipe.setSecurityInterceptor(this.interceptor);
|
||||
mipe.afterPropertiesSet();
|
||||
|
||||
assertThat(mipe.isAllowed(mi, this.token)).isTrue();
|
||||
}
|
||||
|
||||
@@ -95,7 +92,6 @@ public class MethodInvocationPrivilegeEvaluatorTests {
|
||||
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
|
||||
mipe.setSecurityInterceptor(this.interceptor);
|
||||
given(this.mds.getAttributes(mi)).willReturn(this.role);
|
||||
|
||||
assertThat(mipe.isAllowed(mi, this.token)).isTrue();
|
||||
}
|
||||
|
||||
@@ -107,7 +103,6 @@ public class MethodInvocationPrivilegeEvaluatorTests {
|
||||
mipe.setSecurityInterceptor(this.interceptor);
|
||||
given(this.mds.getAttributes(mi)).willReturn(this.role);
|
||||
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(this.token, mi, this.role);
|
||||
|
||||
assertThat(mipe.isAllowed(mi, this.token)).isFalse();
|
||||
}
|
||||
|
||||
@@ -115,12 +110,10 @@ public class MethodInvocationPrivilegeEvaluatorTests {
|
||||
public void declinesAccessUsingCreateFromClass() {
|
||||
final MethodInvocation mi = MethodInvocationUtils.createFromClass(new OtherTargetObject(), ITargetObject.class,
|
||||
"makeLowerCase", new Class[] { String.class }, new Object[] { "helloWorld" });
|
||||
|
||||
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
|
||||
mipe.setSecurityInterceptor(this.interceptor);
|
||||
given(this.mds.getAttributes(mi)).willReturn(this.role);
|
||||
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(this.token, mi, this.role);
|
||||
|
||||
assertThat(mipe.isAllowed(mi, this.token)).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@@ -54,9 +54,7 @@ public class AbstractAccessDecisionManagerTests {
|
||||
List list = new Vector();
|
||||
list.add(new DenyVoter());
|
||||
list.add(new MockStringOnlyVoter());
|
||||
|
||||
MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list);
|
||||
|
||||
assertThat(mock.supports(String.class)).isTrue();
|
||||
assertThat(!mock.supports(Integer.class)).isTrue();
|
||||
}
|
||||
@@ -68,12 +66,9 @@ public class AbstractAccessDecisionManagerTests {
|
||||
DenyAgainVoter denyVoter = new DenyAgainVoter();
|
||||
list.add(voter);
|
||||
list.add(denyVoter);
|
||||
|
||||
MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list);
|
||||
|
||||
ConfigAttribute attr = new SecurityConfig("DENY_AGAIN_FOR_SURE");
|
||||
assertThat(mock.supports(attr)).isTrue();
|
||||
|
||||
ConfigAttribute badAttr = new SecurityConfig("WE_DONT_SUPPORT_THIS");
|
||||
assertThat(!mock.supports(badAttr)).isTrue();
|
||||
}
|
||||
@@ -92,13 +87,11 @@ public class AbstractAccessDecisionManagerTests {
|
||||
@Test
|
||||
public void testRejectsEmptyList() {
|
||||
List list = new Vector();
|
||||
|
||||
try {
|
||||
new MockDecisionManagerImpl(list);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,7 +102,6 @@ public class AbstractAccessDecisionManagerTests {
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,7 +118,6 @@ public class AbstractAccessDecisionManagerTests {
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,11 +56,9 @@ public class AffirmativeBasedTests {
|
||||
@Before
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setup() {
|
||||
|
||||
this.grant = mock(AccessDecisionVoter.class);
|
||||
this.abstain = mock(AccessDecisionVoter.class);
|
||||
this.deny = mock(AccessDecisionVoter.class);
|
||||
|
||||
given(this.grant.vote(any(Authentication.class), any(Object.class), any(List.class)))
|
||||
.willReturn(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
given(this.abstain.vote(any(Authentication.class), any(Object.class), any(List.class)))
|
||||
@@ -71,7 +69,6 @@ public class AffirmativeBasedTests {
|
||||
|
||||
@Test
|
||||
public void oneAffirmativeVoteOneDenyVoteOneAbstainVoteGrantsAccess() throws Exception {
|
||||
|
||||
this.mgr = new AffirmativeBased(
|
||||
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.grant, this.deny, this.abstain));
|
||||
this.mgr.afterPropertiesSet();
|
||||
@@ -104,7 +101,6 @@ public class AffirmativeBasedTests {
|
||||
this.mgr = new AffirmativeBased(
|
||||
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.abstain, this.abstain, this.abstain));
|
||||
assertThat(!this.mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
|
||||
|
||||
this.mgr.decide(this.user, new Object(), this.attrs);
|
||||
}
|
||||
|
||||
@@ -114,7 +110,6 @@ public class AffirmativeBasedTests {
|
||||
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.abstain, this.abstain, this.abstain));
|
||||
this.mgr.setAllowIfAllAbstainDecisions(true);
|
||||
assertThat(this.mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
|
||||
|
||||
this.mgr.decide(this.user, new Object(), this.attrs);
|
||||
}
|
||||
|
||||
|
||||
@@ -82,13 +82,11 @@ public class AuthenticatedVoterTests {
|
||||
@Test
|
||||
public void testSetterRejectsNull() {
|
||||
AuthenticatedVoter voter = new AuthenticatedVoter();
|
||||
|
||||
try {
|
||||
voter.setAuthenticationTrustResolver(null);
|
||||
fail("Expected IAE");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,9 +43,7 @@ public class ConsensusBasedTests {
|
||||
ConsensusBased mgr = makeDecisionManager();
|
||||
mgr.setAllowIfEqualGrantedDeniedDecisions(false);
|
||||
assertThat(!mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check changed
|
||||
|
||||
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1", "DENY_FOR_SURE");
|
||||
|
||||
mgr.decide(auth, new Object(), config);
|
||||
}
|
||||
|
||||
@@ -53,29 +51,22 @@ public class ConsensusBasedTests {
|
||||
public void testOneAffirmativeVoteOneDenyVoteOneAbstainVoteGrantsAccessWithDefault() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
ConsensusBased mgr = makeDecisionManager();
|
||||
|
||||
assertThat(mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check default
|
||||
|
||||
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1", "DENY_FOR_SURE");
|
||||
|
||||
mgr.decide(auth, new Object(), config);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOneAffirmativeVoteTwoAbstainVotesGrantsAccess() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
ConsensusBased mgr = makeDecisionManager();
|
||||
|
||||
mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_2"));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
public void testOneDenyVoteTwoAbstainVotesDeniesAccess() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
ConsensusBased mgr = makeDecisionManager();
|
||||
|
||||
mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE"));
|
||||
fail("Should have thrown AccessDeniedException");
|
||||
}
|
||||
@@ -84,9 +75,7 @@ public class ConsensusBasedTests {
|
||||
public void testThreeAbstainVotesDeniesAccessWithDefault() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
ConsensusBased mgr = makeDecisionManager();
|
||||
|
||||
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
|
||||
|
||||
mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL"));
|
||||
}
|
||||
|
||||
@@ -96,7 +85,6 @@ public class ConsensusBasedTests {
|
||||
ConsensusBased mgr = makeDecisionManager();
|
||||
mgr.setAllowIfAllAbstainDecisions(true);
|
||||
assertThat(mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
|
||||
|
||||
mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL"));
|
||||
}
|
||||
|
||||
@@ -104,7 +92,6 @@ public class ConsensusBasedTests {
|
||||
public void testTwoAffirmativeVotesTwoAbstainVotesGrantsAccess() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
ConsensusBased mgr = makeDecisionManager();
|
||||
|
||||
mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_1", "ROLE_2"));
|
||||
}
|
||||
|
||||
@@ -116,7 +103,6 @@ public class ConsensusBasedTests {
|
||||
voters.add(roleVoter);
|
||||
voters.add(denyForSureVoter);
|
||||
voters.add(denyAgainForSureVoter);
|
||||
|
||||
return new ConsensusBased(voters);
|
||||
}
|
||||
|
||||
|
||||
@@ -48,15 +48,12 @@ public class DenyAgainVoter implements AccessDecisionVoter<Object> {
|
||||
@Override
|
||||
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
|
||||
Iterator<ConfigAttribute> iter = attributes.iterator();
|
||||
|
||||
while (iter.hasNext()) {
|
||||
ConfigAttribute attribute = iter.next();
|
||||
|
||||
if (this.supports(attribute)) {
|
||||
return ACCESS_DENIED;
|
||||
}
|
||||
}
|
||||
|
||||
return ACCESS_ABSTAIN;
|
||||
}
|
||||
|
||||
|
||||
@@ -50,15 +50,12 @@ public class DenyVoter implements AccessDecisionVoter<Object> {
|
||||
@Override
|
||||
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
|
||||
Iterator<ConfigAttribute> iter = attributes.iterator();
|
||||
|
||||
while (iter.hasNext()) {
|
||||
ConfigAttribute attribute = iter.next();
|
||||
|
||||
if (this.supports(attribute)) {
|
||||
return ACCESS_DENIED;
|
||||
}
|
||||
}
|
||||
|
||||
return ACCESS_ABSTAIN;
|
||||
}
|
||||
|
||||
|
||||
@@ -31,11 +31,9 @@ public class RoleHierarchyVoterTests {
|
||||
public void hierarchicalRoleIsIncludedInDecision() {
|
||||
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
|
||||
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
|
||||
|
||||
// User has role A, role B is required
|
||||
TestingAuthenticationToken auth = new TestingAuthenticationToken("user", "password", "ROLE_A");
|
||||
RoleHierarchyVoter voter = new RoleHierarchyVoter(roleHierarchyImpl);
|
||||
|
||||
assertThat(voter.vote(auth, new Object(), SecurityConfig.createList("ROLE_B")))
|
||||
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
|
||||
}
|
||||
|
||||
@@ -51,7 +51,6 @@ public class UnanimousBasedTests {
|
||||
private UnanimousBased makeDecisionManagerWithFooBarPrefix() {
|
||||
RoleVoter roleVoter = new RoleVoter();
|
||||
roleVoter.setRolePrefix("FOOBAR_");
|
||||
|
||||
DenyVoter denyForSureVoter = new DenyVoter();
|
||||
DenyAgainVoter denyAgainForSureVoter = new DenyAgainVoter();
|
||||
List<AccessDecisionVoter<? extends Object>> voters = new Vector<>();
|
||||
@@ -73,9 +72,7 @@ public class UnanimousBasedTests {
|
||||
public void testOneAffirmativeVoteOneDenyVoteOneAbstainVoteDeniesAccess() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
UnanimousBased mgr = makeDecisionManager();
|
||||
|
||||
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1", "DENY_FOR_SURE" });
|
||||
|
||||
try {
|
||||
mgr.decide(auth, new Object(), config);
|
||||
fail("Should have thrown AccessDeniedException");
|
||||
@@ -88,9 +85,7 @@ public class UnanimousBasedTests {
|
||||
public void testOneAffirmativeVoteTwoAbstainVotesGrantsAccess() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
UnanimousBased mgr = makeDecisionManager();
|
||||
|
||||
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_2");
|
||||
|
||||
mgr.decide(auth, new Object(), config);
|
||||
}
|
||||
|
||||
@@ -98,9 +93,7 @@ public class UnanimousBasedTests {
|
||||
public void testOneDenyVoteTwoAbstainVotesDeniesAccess() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
UnanimousBased mgr = makeDecisionManager();
|
||||
|
||||
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE");
|
||||
|
||||
try {
|
||||
mgr.decide(auth, new Object(), config);
|
||||
fail("Should have thrown AccessDeniedException");
|
||||
@@ -113,9 +106,7 @@ public class UnanimousBasedTests {
|
||||
public void testRoleVoterPrefixObserved() {
|
||||
TestingAuthenticationToken auth = makeTestTokenWithFooBarPrefix();
|
||||
UnanimousBased mgr = makeDecisionManagerWithFooBarPrefix();
|
||||
|
||||
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "FOOBAR_1", "FOOBAR_2" });
|
||||
|
||||
mgr.decide(auth, new Object(), config);
|
||||
}
|
||||
|
||||
@@ -123,11 +114,8 @@ public class UnanimousBasedTests {
|
||||
public void testThreeAbstainVotesDeniesAccessWithDefault() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
UnanimousBased mgr = makeDecisionManager();
|
||||
|
||||
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
|
||||
|
||||
List<ConfigAttribute> config = SecurityConfig.createList("IGNORED_BY_ALL");
|
||||
|
||||
try {
|
||||
mgr.decide(auth, new Object(), config);
|
||||
fail("Should have thrown AccessDeniedException");
|
||||
@@ -142,9 +130,7 @@ public class UnanimousBasedTests {
|
||||
UnanimousBased mgr = makeDecisionManager();
|
||||
mgr.setAllowIfAllAbstainDecisions(true);
|
||||
assertThat(mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
|
||||
|
||||
List<ConfigAttribute> config = SecurityConfig.createList("IGNORED_BY_ALL");
|
||||
|
||||
mgr.decide(auth, new Object(), config);
|
||||
}
|
||||
|
||||
@@ -152,9 +138,7 @@ public class UnanimousBasedTests {
|
||||
public void testTwoAffirmativeVotesTwoAbstainVotesGrantsAccess() {
|
||||
TestingAuthenticationToken auth = makeTestToken();
|
||||
UnanimousBased mgr = makeDecisionManager();
|
||||
|
||||
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1", "ROLE_2" });
|
||||
|
||||
mgr.decide(auth, new Object(), config);
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ public class AbstractAuthenticationTokenTests {
|
||||
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", this.authorities);
|
||||
List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token.getAuthorities();
|
||||
assertThat(gotAuthorities).isNotSameAs(this.authorities);
|
||||
|
||||
gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER"));
|
||||
}
|
||||
|
||||
@@ -70,9 +69,7 @@ public class AbstractAuthenticationTokenTests {
|
||||
MockAuthenticationImpl token3 = new MockAuthenticationImpl(null, null, AuthorityUtils.NO_AUTHORITIES);
|
||||
assertThat(token2.hashCode()).isEqualTo(token1.hashCode());
|
||||
assertThat(token1.hashCode() != token3.hashCode()).isTrue();
|
||||
|
||||
token2.setAuthenticated(true);
|
||||
|
||||
assertThat(token1.hashCode() != token2.hashCode()).isTrue();
|
||||
}
|
||||
|
||||
@@ -81,25 +78,19 @@ public class AbstractAuthenticationTokenTests {
|
||||
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", this.authorities);
|
||||
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", this.authorities);
|
||||
assertThat(token2).isEqualTo(token1);
|
||||
|
||||
MockAuthenticationImpl token3 = new MockAuthenticationImpl("Test", "Password_Changed", this.authorities);
|
||||
assertThat(!token1.equals(token3)).isTrue();
|
||||
|
||||
MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed", "Password", this.authorities);
|
||||
assertThat(!token1.equals(token4)).isTrue();
|
||||
|
||||
MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test", "Password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO_CHANGED"));
|
||||
assertThat(!token1.equals(token5)).isTrue();
|
||||
|
||||
MockAuthenticationImpl token6 = new MockAuthenticationImpl("Test", "Password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE"));
|
||||
assertThat(!token1.equals(token6)).isTrue();
|
||||
|
||||
MockAuthenticationImpl token7 = new MockAuthenticationImpl("Test", "Password", null);
|
||||
assertThat(!token1.equals(token7)).isTrue();
|
||||
assertThat(!token7.equals(token1)).isTrue();
|
||||
|
||||
assertThat(!token1.equals(100)).isTrue();
|
||||
}
|
||||
|
||||
@@ -126,10 +117,8 @@ public class AbstractAuthenticationTokenTests {
|
||||
@Test
|
||||
public void testGetNameWhenPrincipalIsAuthenticatedPrincipal() {
|
||||
String principalName = "test";
|
||||
|
||||
AuthenticatedPrincipal principal = mock(AuthenticatedPrincipal.class);
|
||||
given(principal.getName()).willReturn(principalName);
|
||||
|
||||
MockAuthenticationImpl token = new MockAuthenticationImpl(principal, "Password", this.authorities);
|
||||
assertThat(token.getName()).isEqualTo(principalName);
|
||||
verify(principal, times(1)).getName();
|
||||
|
||||
@@ -55,11 +55,9 @@ public class AuthenticationTrustResolverImplTests {
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
|
||||
|
||||
assertThat(AnonymousAuthenticationToken.class).isEqualTo(trustResolver.getAnonymousClass());
|
||||
trustResolver.setAnonymousClass(TestingAuthenticationToken.class);
|
||||
assertThat(trustResolver.getAnonymousClass()).isEqualTo(TestingAuthenticationToken.class);
|
||||
|
||||
assertThat(RememberMeAuthenticationToken.class).isEqualTo(trustResolver.getRememberMeClass());
|
||||
trustResolver.setRememberMeClass(TestingAuthenticationToken.class);
|
||||
assertThat(trustResolver.getRememberMeClass()).isEqualTo(TestingAuthenticationToken.class);
|
||||
|
||||
@@ -57,7 +57,6 @@ public class DefaultAuthenticationEventPublisherTests {
|
||||
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
|
||||
this.publisher.setApplicationEventPublisher(appPublisher);
|
||||
Authentication a = mock(Authentication.class);
|
||||
|
||||
Exception cause = new Exception();
|
||||
Object extraInfo = new Object();
|
||||
this.publisher.publishAuthenticationFailure(new BadCredentialsException(""), a);
|
||||
@@ -94,7 +93,6 @@ public class DefaultAuthenticationEventPublisherTests {
|
||||
this.publisher.setApplicationEventPublisher(appPublisher);
|
||||
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
|
||||
verify(appPublisher).publishEvent(isA(AuthenticationSuccessEvent.class));
|
||||
|
||||
this.publisher.setApplicationEventPublisher(null);
|
||||
// Should be ignored with null app publisher
|
||||
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
|
||||
@@ -107,7 +105,6 @@ public class DefaultAuthenticationEventPublisherTests {
|
||||
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
|
||||
this.publisher.setAdditionalExceptionMappings(p);
|
||||
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
|
||||
|
||||
this.publisher.setApplicationEventPublisher(appPublisher);
|
||||
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"),
|
||||
mock(Authentication.class));
|
||||
@@ -129,7 +126,6 @@ public class DefaultAuthenticationEventPublisherTests {
|
||||
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
|
||||
this.publisher.setAdditionalExceptionMappings(p);
|
||||
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
|
||||
|
||||
this.publisher.setApplicationEventPublisher(appPublisher);
|
||||
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
|
||||
}, mock(Authentication.class));
|
||||
@@ -166,7 +162,6 @@ public class DefaultAuthenticationEventPublisherTests {
|
||||
mappings.put(MockAuthenticationException.class, AuthenticationFailureDisabledEvent.class);
|
||||
this.publisher.setAdditionalExceptionMappings(mappings);
|
||||
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
|
||||
|
||||
this.publisher.setApplicationEventPublisher(appPublisher);
|
||||
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"),
|
||||
mock(Authentication.class));
|
||||
@@ -184,7 +179,6 @@ public class DefaultAuthenticationEventPublisherTests {
|
||||
this.publisher = new DefaultAuthenticationEventPublisher();
|
||||
this.publisher.setDefaultAuthenticationFailureEvent(AuthenticationFailureBadCredentialsEvent.class);
|
||||
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
|
||||
|
||||
this.publisher.setApplicationEventPublisher(appPublisher);
|
||||
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
|
||||
}, mock(Authentication.class));
|
||||
|
||||
@@ -51,10 +51,8 @@ public class DelegatingReactiveAuthenticationManagerTests {
|
||||
public void authenticateWhenEmptyAndNotThenReturnsNotEmpty() {
|
||||
given(this.delegate1.authenticate(any())).willReturn(Mono.empty());
|
||||
given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
|
||||
|
||||
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
|
||||
this.delegate2);
|
||||
|
||||
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
|
||||
}
|
||||
|
||||
@@ -64,20 +62,16 @@ public class DelegatingReactiveAuthenticationManagerTests {
|
||||
// flatMap)
|
||||
given(this.delegate1.authenticate(any()))
|
||||
.willReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
|
||||
|
||||
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
|
||||
this.delegate2);
|
||||
|
||||
StepVerifier.create(manager.authenticate(this.authentication)).expectNext(this.authentication).verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenBadCredentialsThenDelegate2NotInvokedAndError() {
|
||||
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
|
||||
|
||||
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
|
||||
this.delegate2);
|
||||
|
||||
StepVerifier.create(manager.authenticate(this.authentication)).expectError(BadCredentialsException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@@ -69,7 +69,6 @@ public class ProviderManagerTests {
|
||||
ProviderManager mgr = makeProviderManager();
|
||||
Authentication result = mgr.authenticate(token);
|
||||
assertThat(result.getCredentials()).isNull();
|
||||
|
||||
mgr.setEraseCredentialsAfterAuthentication(false);
|
||||
token = new UsernamePasswordAuthenticationToken("Test", "Password");
|
||||
result = mgr.authenticate(token);
|
||||
@@ -82,7 +81,6 @@ public class ProviderManagerTests {
|
||||
ProviderManager mgr = new ProviderManager(createProviderWhichReturns(a));
|
||||
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
|
||||
mgr.setAuthenticationEventPublisher(publisher);
|
||||
|
||||
Authentication result = mgr.authenticate(a);
|
||||
assertThat(result).isEqualTo(a);
|
||||
verify(publisher).publishAuthenticationSuccess(result);
|
||||
@@ -95,7 +93,6 @@ public class ProviderManagerTests {
|
||||
Arrays.asList(createProviderWhichReturns(null), createProviderWhichReturns(a)));
|
||||
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
|
||||
mgr.setAuthenticationEventPublisher(publisher);
|
||||
|
||||
Authentication result = mgr.authenticate(a);
|
||||
assertThat(result).isSameAs(a);
|
||||
verify(publisher).publishAuthenticationSuccess(result);
|
||||
@@ -130,7 +127,6 @@ public class ProviderManagerTests {
|
||||
public void detailsAreNotSetOnAuthenticationTokenIfAlreadySetByProvider() {
|
||||
Object requestDetails = "(Request Details)";
|
||||
final Object resultDetails = "(Result Details)";
|
||||
|
||||
// A provider which sets the details object
|
||||
AuthenticationProvider provider = new AuthenticationProvider() {
|
||||
@Override
|
||||
@@ -144,12 +140,9 @@ public class ProviderManagerTests {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
ProviderManager authMgr = new ProviderManager(provider);
|
||||
|
||||
TestingAuthenticationToken request = createAuthenticationToken();
|
||||
request.setDetails(requestDetails);
|
||||
|
||||
Authentication result = authMgr.authenticate(request);
|
||||
assertThat(result.getDetails()).isEqualTo(resultDetails);
|
||||
}
|
||||
@@ -158,10 +151,8 @@ public class ProviderManagerTests {
|
||||
public void detailsAreSetOnAuthenticationTokenIfNotAlreadySetByProvider() {
|
||||
Object details = new Object();
|
||||
ProviderManager authMgr = makeProviderManager();
|
||||
|
||||
TestingAuthenticationToken request = createAuthenticationToken();
|
||||
request.setDetails(details);
|
||||
|
||||
Authentication result = authMgr.authenticate(request);
|
||||
assertThat(result.getCredentials()).isNotNull();
|
||||
assertThat(result.getDetails()).isSameAs(details);
|
||||
@@ -178,7 +169,6 @@ public class ProviderManagerTests {
|
||||
|
||||
@Test
|
||||
public void authenticationExceptionIsRethrownIfNoLaterProviderAuthenticates() {
|
||||
|
||||
ProviderManager mgr = new ProviderManager(Arrays
|
||||
.asList(createProviderWhichThrows(new BadCredentialsException("")), createProviderWhichReturns(null)));
|
||||
try {
|
||||
@@ -195,9 +185,7 @@ public class ProviderManagerTests {
|
||||
AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException("") {
|
||||
});
|
||||
AuthenticationProvider otherProvider = mock(AuthenticationProvider.class);
|
||||
|
||||
ProviderManager authMgr = new ProviderManager(Arrays.asList(iThrowAccountStatusException, otherProvider));
|
||||
|
||||
try {
|
||||
authMgr.authenticate(mock(Authentication.class));
|
||||
fail("Expected AccountStatusException");
|
||||
@@ -239,13 +227,11 @@ public class ProviderManagerTests {
|
||||
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
|
||||
AuthenticationManager parent = mock(AuthenticationManager.class);
|
||||
given(parent.authenticate(authReq)).willThrow(new ProviderNotFoundException(""));
|
||||
|
||||
// Set a provider that throws an exception - this is the exception we expect to be
|
||||
// propagated
|
||||
ProviderManager mgr = new ProviderManager(
|
||||
Collections.singletonList(createProviderWhichThrows(new BadCredentialsException(""))), parent);
|
||||
mgr.setAuthenticationEventPublisher(publisher);
|
||||
|
||||
try {
|
||||
mgr.authenticate(authReq);
|
||||
fail("Expected exception");
|
||||
@@ -302,7 +288,6 @@ public class ProviderManagerTests {
|
||||
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(expected),
|
||||
createProviderWhichThrows(new BadCredentialsException("Oops"))), null);
|
||||
final Authentication authReq = mock(Authentication.class);
|
||||
|
||||
try {
|
||||
mgr.authenticate(authReq);
|
||||
fail("Expected Exception");
|
||||
@@ -318,13 +303,10 @@ public class ProviderManagerTests {
|
||||
ProviderManager parentMgr = new ProviderManager(createProviderWhichThrows(badCredentialsExParent));
|
||||
ProviderManager childMgr = new ProviderManager(Collections.singletonList(
|
||||
createProviderWhichThrows(new BadCredentialsException("Bad Credentials in child"))), parentMgr);
|
||||
|
||||
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
|
||||
parentMgr.setAuthenticationEventPublisher(publisher);
|
||||
childMgr.setAuthenticationEventPublisher(publisher);
|
||||
|
||||
final Authentication authReq = mock(Authentication.class);
|
||||
|
||||
try {
|
||||
childMgr.authenticate(authReq);
|
||||
fail("Expected exception");
|
||||
@@ -341,7 +323,6 @@ public class ProviderManagerTests {
|
||||
AuthenticationProvider provider = mock(AuthenticationProvider.class);
|
||||
given(provider.supports(any(Class.class))).willReturn(true);
|
||||
given(provider.authenticate(any(Authentication.class))).willThrow(ex);
|
||||
|
||||
return provider;
|
||||
}
|
||||
|
||||
@@ -349,7 +330,6 @@ public class ProviderManagerTests {
|
||||
AuthenticationProvider provider = mock(AuthenticationProvider.class);
|
||||
given(provider.supports(any(Class.class))).willReturn(true);
|
||||
given(provider.authenticate(any(Authentication.class))).willReturn(a);
|
||||
|
||||
return provider;
|
||||
}
|
||||
|
||||
|
||||
@@ -64,27 +64,21 @@ public class ReactiveAuthenticationManagerAdapterTests {
|
||||
public void authenticateWhenSuccessThenSuccess() {
|
||||
given(this.delegate.authenticate(any())).willReturn(this.authentication);
|
||||
given(this.authentication.isAuthenticated()).willReturn(true);
|
||||
|
||||
Authentication result = this.manager.authenticate(this.authentication).block();
|
||||
|
||||
assertThat(result).isEqualTo(this.authentication);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenReturnNotAuthenticatedThenError() {
|
||||
given(this.delegate.authenticate(any())).willReturn(this.authentication);
|
||||
|
||||
Authentication result = this.manager.authenticate(this.authentication).block();
|
||||
|
||||
assertThat(result).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenBadCredentialsThenError() {
|
||||
given(this.delegate.authenticate(any())).willThrow(new BadCredentialsException("Failed"));
|
||||
|
||||
Mono<Authentication> result = this.manager.authenticate(this.authentication);
|
||||
|
||||
StepVerifier.create(result).expectError(BadCredentialsException.class).verify();
|
||||
}
|
||||
|
||||
|
||||
@@ -71,11 +71,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
|
||||
@Test
|
||||
public void authenticateWhenUserNotFoundThenBadCredentials() {
|
||||
given(this.repository.findByUsername(this.username)).willReturn(Mono.empty());
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
|
||||
this.password);
|
||||
Mono<Authentication> authentication = this.manager.authenticate(token);
|
||||
|
||||
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
|
||||
}
|
||||
|
||||
@@ -88,11 +86,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
|
||||
this.password + "INVALID");
|
||||
Mono<Authentication> authentication = this.manager.authenticate(token);
|
||||
|
||||
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
|
||||
}
|
||||
|
||||
@@ -105,11 +101,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
|
||||
this.password);
|
||||
Authentication authentication = this.manager.authenticate(token).block();
|
||||
|
||||
assertThat(authentication).isEqualTo(authentication);
|
||||
}
|
||||
|
||||
@@ -119,11 +113,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
|
||||
given(this.passwordEncoder.matches(any(), any())).willReturn(true);
|
||||
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
|
||||
this.password);
|
||||
Authentication authentication = this.manager.authenticate(token).block();
|
||||
|
||||
assertThat(authentication).isEqualTo(authentication);
|
||||
}
|
||||
|
||||
@@ -133,12 +125,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
|
||||
given(this.passwordEncoder.matches(any(), any())).willReturn(false);
|
||||
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
|
||||
this.password);
|
||||
|
||||
Mono<Authentication> authentication = this.manager.authenticate(token);
|
||||
|
||||
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
|
||||
}
|
||||
|
||||
|
||||
@@ -35,9 +35,7 @@ public class TestingAuthenticationProviderTests {
|
||||
TestingAuthenticationProvider provider = new TestingAuthenticationProvider();
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", "ROLE_ONE", "ROLE_TWO");
|
||||
Authentication result = provider.authenticate(token);
|
||||
|
||||
assertThat(result instanceof TestingAuthenticationToken).isTrue();
|
||||
|
||||
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
|
||||
assertThat(castResult.getPrincipal()).isEqualTo("Test");
|
||||
assertThat(castResult.getCredentials()).isEqualTo("Password");
|
||||
|
||||
@@ -32,7 +32,6 @@ public class TestingAuthenticationTokenTests {
|
||||
@Test
|
||||
public void constructorWhenNoAuthoritiesThenUnauthenticated() {
|
||||
TestingAuthenticationToken unauthenticated = new TestingAuthenticationToken("principal", "credentials");
|
||||
|
||||
assertThat(unauthenticated.isAuthenticated()).isFalse();
|
||||
}
|
||||
|
||||
@@ -40,7 +39,6 @@ public class TestingAuthenticationTokenTests {
|
||||
public void constructorWhenArityAuthoritiesThenAuthenticated() {
|
||||
TestingAuthenticationToken authenticated = new TestingAuthenticationToken("principal", "credentials",
|
||||
"authority");
|
||||
|
||||
assertThat(authenticated.isAuthenticated()).isTrue();
|
||||
}
|
||||
|
||||
@@ -48,7 +46,6 @@ public class TestingAuthenticationTokenTests {
|
||||
public void constructorWhenCollectionAuthoritiesThenAuthenticated() {
|
||||
TestingAuthenticationToken authenticated = new TestingAuthenticationToken("principal", "credentials",
|
||||
Arrays.asList(new SimpleGrantedAuthority("authority")));
|
||||
|
||||
assertThat(authenticated.isAuthenticated()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@@ -72,7 +72,6 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
.roles("USER")
|
||||
.build();
|
||||
// @formatter:on
|
||||
|
||||
private UserDetailsRepositoryReactiveAuthenticationManager manager;
|
||||
|
||||
@Before
|
||||
@@ -97,9 +96,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
this.manager.setPasswordEncoder(this.encoder);
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
|
||||
this.user.getPassword());
|
||||
|
||||
Authentication result = this.manager.authenticate(token).block();
|
||||
|
||||
verify(this.scheduler).schedule(any());
|
||||
}
|
||||
|
||||
@@ -115,9 +112,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
|
||||
this.user.getPassword());
|
||||
|
||||
Authentication result = this.manager.authenticate(token).block();
|
||||
|
||||
verify(this.encoder).encode(this.user.getPassword());
|
||||
verify(this.userDetailsPasswordService).updatePassword(eq(this.user), eq(encodedPassword));
|
||||
}
|
||||
@@ -130,9 +125,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
|
||||
this.user.getPassword());
|
||||
|
||||
assertThatThrownBy(() -> this.manager.authenticate(token).block()).isInstanceOf(BadCredentialsException.class);
|
||||
|
||||
verifyZeroInteractions(this.userDetailsPasswordService);
|
||||
}
|
||||
|
||||
@@ -145,9 +138,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
|
||||
this.user.getPassword());
|
||||
|
||||
Authentication result = this.manager.authenticate(token).block();
|
||||
|
||||
verifyZeroInteractions(this.userDetailsPasswordService);
|
||||
}
|
||||
|
||||
@@ -158,11 +149,9 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
given(this.encoder.matches(any(), any())).willReturn(true);
|
||||
this.manager.setPasswordEncoder(this.encoder);
|
||||
this.manager.setPostAuthenticationChecks(this.postAuthenticationChecks);
|
||||
|
||||
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager
|
||||
.authenticate(new UsernamePasswordAuthenticationToken(this.user, this.user.getPassword())).block())
|
||||
.withMessage("account is locked");
|
||||
|
||||
verify(this.postAuthenticationChecks).check(eq(this.user));
|
||||
}
|
||||
|
||||
@@ -171,12 +160,9 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
|
||||
given(this.encoder.matches(any(), any())).willReturn(true);
|
||||
this.manager.setPasswordEncoder(this.encoder);
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
|
||||
this.user.getPassword());
|
||||
|
||||
this.manager.authenticate(token).block();
|
||||
|
||||
verifyZeroInteractions(this.postAuthenticationChecks);
|
||||
}
|
||||
|
||||
@@ -191,10 +177,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(expiredUser));
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(expiredUser,
|
||||
expiredUser.getPassword());
|
||||
|
||||
this.manager.authenticate(token).block();
|
||||
}
|
||||
|
||||
@@ -209,17 +193,14 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(lockedUser));
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(lockedUser,
|
||||
lockedUser.getPassword());
|
||||
|
||||
this.manager.authenticate(token).block();
|
||||
}
|
||||
|
||||
@Test(expected = DisabledException.class)
|
||||
public void authenticateWhenAccountDisabledThenException() {
|
||||
this.manager.setPasswordEncoder(this.encoder);
|
||||
|
||||
// @formatter:off
|
||||
UserDetails disabledUser = User.withUsername("user")
|
||||
.password("password")
|
||||
@@ -228,10 +209,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(disabledUser));
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(disabledUser,
|
||||
disabledUser.getPassword());
|
||||
|
||||
this.manager.authenticate(token).block();
|
||||
}
|
||||
|
||||
|
||||
@@ -34,26 +34,20 @@ public class UsernamePasswordAuthenticationTokenTests {
|
||||
public void authenticatedPropertyContractIsSatisfied() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
|
||||
AuthorityUtils.NO_AUTHORITIES);
|
||||
|
||||
// check default given we passed some GrantedAuthorty[]s (well, we passed empty
|
||||
// list)
|
||||
assertThat(token.isAuthenticated()).isTrue();
|
||||
|
||||
// check explicit set to untrusted (we can safely go from trusted to untrusted,
|
||||
// but not the reverse)
|
||||
token.setAuthenticated(false);
|
||||
assertThat(!token.isAuthenticated()).isTrue();
|
||||
|
||||
// Now let's create a UsernamePasswordAuthenticationToken without any
|
||||
// GrantedAuthorty[]s (different constructor)
|
||||
token = new UsernamePasswordAuthenticationToken("Test", "Password");
|
||||
|
||||
assertThat(!token.isAuthenticated()).isTrue();
|
||||
|
||||
// check we're allowed to still set it to untrusted
|
||||
token.setAuthenticated(false);
|
||||
assertThat(!token.isAuthenticated()).isTrue();
|
||||
|
||||
// check denied changing it to trusted
|
||||
try {
|
||||
token.setAuthenticated(true);
|
||||
|
||||
@@ -38,10 +38,8 @@ public class AnonymousAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testDetectsAnInvalidKey() {
|
||||
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
|
||||
|
||||
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY", "Test",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||
|
||||
try {
|
||||
aap.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
@@ -57,7 +55,6 @@ public class AnonymousAuthenticationProviderTests {
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,10 +67,8 @@ public class AnonymousAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testIgnoresClassesItDoesNotSupport() {
|
||||
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
|
||||
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password", "ROLE_A");
|
||||
assertThat(aap.supports(TestingAuthenticationToken.class)).isFalse();
|
||||
|
||||
// Try it anyway
|
||||
assertThat(aap.authenticate(token)).isNull();
|
||||
}
|
||||
@@ -81,12 +76,9 @@ public class AnonymousAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testNormalOperation() {
|
||||
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
|
||||
|
||||
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("qwerty", "Test",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||
|
||||
Authentication result = aap.authenticate(token);
|
||||
|
||||
assertThat(token).isEqualTo(result);
|
||||
}
|
||||
|
||||
|
||||
@@ -46,21 +46,18 @@ public class AnonymousAuthenticationTokenTests {
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
new AnonymousAuthenticationToken("key", null, ROLES_12);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
new AnonymousAuthenticationToken("key", "Test", null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
@@ -73,14 +70,12 @@ public class AnonymousAuthenticationTokenTests {
|
||||
public void testEqualsWhenEqual() {
|
||||
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
|
||||
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
|
||||
|
||||
assertThat(token2).isEqualTo(token1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetters() {
|
||||
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
|
||||
|
||||
assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
|
||||
assertThat(token.getPrincipal()).isEqualTo("Test");
|
||||
assertThat(token.getCredentials()).isEqualTo("");
|
||||
@@ -91,7 +86,6 @@ public class AnonymousAuthenticationTokenTests {
|
||||
@Test
|
||||
public void testNoArgConstructorDoesntExist() {
|
||||
Class<?> clazz = AnonymousAuthenticationToken.class;
|
||||
|
||||
try {
|
||||
clazz.getDeclaredConstructor((Class[]) null);
|
||||
fail("Should have thrown NoSuchMethodException");
|
||||
@@ -104,7 +98,6 @@ public class AnonymousAuthenticationTokenTests {
|
||||
public void testNotEqualsDueToAbstractParentEqualsCheck() {
|
||||
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
|
||||
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key", "DIFFERENT_PRINCIPAL", ROLES_12);
|
||||
|
||||
assertThat(token1.equals(token2)).isFalse();
|
||||
}
|
||||
|
||||
@@ -113,16 +106,13 @@ public class AnonymousAuthenticationTokenTests {
|
||||
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
|
||||
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
|
||||
ROLES_12);
|
||||
|
||||
assertThat(token1.equals(token2)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEqualsDueToKey() {
|
||||
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
|
||||
|
||||
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("DIFFERENT_KEY", "Test", ROLES_12);
|
||||
|
||||
assertThat(token1.equals(token2)).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@@ -74,17 +74,14 @@ public class DaoAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testAuthenticateFailsForIncorrectPasswordCase() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "KOala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,105 +91,86 @@ public class DaoAuthenticationProviderTests {
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null);
|
||||
try {
|
||||
provider.authenticate(authenticationToken);
|
||||
fail("Expected BadCredenialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsIfAccountExpired() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountExpired());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown AccountExpiredException");
|
||||
}
|
||||
catch (AccountExpiredException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsIfAccountLocked() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountLocked());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown LockedException");
|
||||
}
|
||||
catch (LockedException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsIfCredentialsExpired() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterCredentialsExpired());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown CredentialsExpiredException");
|
||||
}
|
||||
catch (CredentialsExpiredException expected) {
|
||||
|
||||
}
|
||||
|
||||
// Check that wrong password causes BadCredentialsException, rather than
|
||||
// CredentialsExpiredException
|
||||
token = new UsernamePasswordAuthenticationToken("peter", "wrong_password");
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsIfUserDisabled() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserPeter());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown DisabledException");
|
||||
}
|
||||
catch (DisabledException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsWhenAuthenticationDaoHasBackendFailure() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceSimulateBackendError());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown InternalAuthenticationServiceException");
|
||||
@@ -204,116 +182,95 @@ public class DaoAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testAuthenticateFailsWithEmptyUsername() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(null, "koala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsWithInvalidPassword() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "INVALID_PASSWORD");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionFalse() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER", "koala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setHideUserNotFoundExceptions(false); // we want
|
||||
// UsernameNotFoundExceptions
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown UsernameNotFoundException");
|
||||
}
|
||||
catch (UsernameNotFoundException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionsWithDefaultOfTrue() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER", "koala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsWithInvalidUsernameAndChangePasswordEncoder() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER", "koala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
|
||||
}
|
||||
|
||||
provider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateFailsWithMixedCaseUsernameIfDefaultChanged() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("RoD", "koala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,17 +278,13 @@ public class DaoAuthenticationProviderTests {
|
||||
public void testAuthenticates() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
|
||||
token.setDetails("192.168.0.1");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
Authentication result = provider.authenticate(token);
|
||||
|
||||
if (!(result instanceof UsernamePasswordAuthenticationToken)) {
|
||||
fail("Should have returned instance of UsernamePasswordAuthenticationToken");
|
||||
}
|
||||
|
||||
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
|
||||
assertThat(castResult.getPrincipal().getClass()).isEqualTo(User.class);
|
||||
assertThat(castResult.getCredentials()).isEqualTo("koala");
|
||||
@@ -342,42 +295,32 @@ public class DaoAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testAuthenticatesASecondTime() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
|
||||
Authentication result = provider.authenticate(token);
|
||||
|
||||
if (!(result instanceof UsernamePasswordAuthenticationToken)) {
|
||||
fail("Should have returned instance of UsernamePasswordAuthenticationToken");
|
||||
}
|
||||
|
||||
// Now try to authenticate with the previous result (with its UserDetails)
|
||||
Authentication result2 = provider.authenticate(result);
|
||||
|
||||
if (!(result2 instanceof UsernamePasswordAuthenticationToken)) {
|
||||
fail("Should have returned instance of UsernamePasswordAuthenticationToken");
|
||||
}
|
||||
|
||||
assertThat(result2.getCredentials()).isEqualTo(result.getCredentials());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticatesWithForcePrincipalAsString() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
provider.setUserCache(new MockUserCache());
|
||||
provider.setForcePrincipalAsString(true);
|
||||
|
||||
Authentication result = provider.authenticate(token);
|
||||
|
||||
if (!(result instanceof UsernamePasswordAuthenticationToken)) {
|
||||
fail("Should have returned instance of UsernamePasswordAuthenticationToken");
|
||||
}
|
||||
|
||||
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
|
||||
assertThat(castResult.getPrincipal().getClass()).isEqualTo(String.class);
|
||||
assertThat(castResult.getPrincipal()).isEqualTo("rod");
|
||||
@@ -388,7 +331,6 @@ public class DaoAuthenticationProviderTests {
|
||||
String password = "password";
|
||||
String encodedPassword = "encoded";
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", password);
|
||||
|
||||
PasswordEncoder encoder = mock(PasswordEncoder.class);
|
||||
UserDetailsService userDetailsService = mock(UserDetailsService.class);
|
||||
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
|
||||
@@ -396,16 +338,13 @@ public class DaoAuthenticationProviderTests {
|
||||
provider.setPasswordEncoder(encoder);
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
provider.setUserDetailsPasswordService(passwordManager);
|
||||
|
||||
UserDetails user = PasswordEncodedUser.user();
|
||||
given(encoder.matches(any(), any())).willReturn(true);
|
||||
given(encoder.upgradeEncoding(any())).willReturn(true);
|
||||
given(encoder.encode(any())).willReturn(encodedPassword);
|
||||
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
|
||||
given(passwordManager.updatePassword(any(), any())).willReturn(user);
|
||||
|
||||
Authentication result = provider.authenticate(token);
|
||||
|
||||
verify(encoder).encode(password);
|
||||
verify(passwordManager).updatePassword(eq(user), eq(encodedPassword));
|
||||
}
|
||||
@@ -413,7 +352,6 @@ public class DaoAuthenticationProviderTests {
|
||||
@Test
|
||||
public void authenticateWhenBadCredentialsAndPasswordManagerThenNoUpdate() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
|
||||
|
||||
PasswordEncoder encoder = mock(PasswordEncoder.class);
|
||||
UserDetailsService userDetailsService = mock(UserDetailsService.class);
|
||||
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
|
||||
@@ -421,20 +359,16 @@ public class DaoAuthenticationProviderTests {
|
||||
provider.setPasswordEncoder(encoder);
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
provider.setUserDetailsPasswordService(passwordManager);
|
||||
|
||||
UserDetails user = PasswordEncodedUser.user();
|
||||
given(encoder.matches(any(), any())).willReturn(false);
|
||||
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
|
||||
|
||||
assertThatThrownBy(() -> provider.authenticate(token)).isInstanceOf(BadCredentialsException.class);
|
||||
|
||||
verifyZeroInteractions(passwordManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenNotUpgradeAndPasswordManagerThenNoUpdate() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
|
||||
|
||||
PasswordEncoder encoder = mock(PasswordEncoder.class);
|
||||
UserDetailsService userDetailsService = mock(UserDetailsService.class);
|
||||
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
|
||||
@@ -442,24 +376,19 @@ public class DaoAuthenticationProviderTests {
|
||||
provider.setPasswordEncoder(encoder);
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
provider.setUserDetailsPasswordService(passwordManager);
|
||||
|
||||
UserDetails user = PasswordEncodedUser.user();
|
||||
given(encoder.matches(any(), any())).willReturn(true);
|
||||
given(encoder.upgradeEncoding(any())).willReturn(false);
|
||||
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
|
||||
|
||||
Authentication result = provider.authenticate(token);
|
||||
|
||||
verifyZeroInteractions(passwordManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsNullBeingReturnedFromAuthenticationDao() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
|
||||
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceReturnsNull());
|
||||
|
||||
try {
|
||||
provider.authenticate(token);
|
||||
fail("Should have thrown AuthenticationServiceException");
|
||||
@@ -475,10 +404,8 @@ public class DaoAuthenticationProviderTests {
|
||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||
provider.setPasswordEncoder(new BCryptPasswordEncoder());
|
||||
assertThat(provider.getPasswordEncoder().getClass()).isEqualTo(BCryptPasswordEncoder.class);
|
||||
|
||||
provider.setUserCache(new EhCacheBasedUserCache());
|
||||
assertThat(provider.getUserCache().getClass()).isEqualTo(EhCacheBasedUserCache.class);
|
||||
|
||||
assertThat(provider.isForcePrincipalAsString()).isFalse();
|
||||
provider.setForcePrincipalAsString(true);
|
||||
assertThat(provider.isForcePrincipalAsString()).isTrue();
|
||||
@@ -487,26 +414,20 @@ public class DaoAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testGoesBackToAuthenticationDaoToObtainLatestPasswordIfCachedPasswordSeemsIncorrect() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
|
||||
|
||||
MockUserDetailsServiceUserRod authenticationDao = new MockUserDetailsServiceUserRod();
|
||||
MockUserCache cache = new MockUserCache();
|
||||
DaoAuthenticationProvider provider = createProvider();
|
||||
provider.setUserDetailsService(authenticationDao);
|
||||
provider.setUserCache(cache);
|
||||
|
||||
// This will work, as password still "koala"
|
||||
provider.authenticate(token);
|
||||
|
||||
// Check "rod = koala" ended up in the cache
|
||||
assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo("koala");
|
||||
|
||||
// Now change the password the AuthenticationDao will return
|
||||
authenticationDao.setPassword("easternLongNeckTurtle");
|
||||
|
||||
// Now try authentication again, with the new password
|
||||
token = new UsernamePasswordAuthenticationToken("rod", "easternLongNeckTurtle");
|
||||
provider.authenticate(token);
|
||||
|
||||
// To get this far, the new password was accepted
|
||||
// Check the cache was updated
|
||||
assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo("easternLongNeckTurtle");
|
||||
@@ -515,13 +436,11 @@ public class DaoAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testStartupFailsIfNoAuthenticationDao() throws Exception {
|
||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||
|
||||
try {
|
||||
provider.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -531,13 +450,11 @@ public class DaoAuthenticationProviderTests {
|
||||
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
|
||||
assertThat(provider.getUserCache().getClass()).isEqualTo(NullUserCache.class);
|
||||
provider.setUserCache(null);
|
||||
|
||||
try {
|
||||
provider.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -549,7 +466,6 @@ public class DaoAuthenticationProviderTests {
|
||||
provider.setUserCache(new MockUserCache());
|
||||
assertThat(provider.getUserDetailsService()).isEqualTo(userDetailsService);
|
||||
provider.afterPropertiesSet();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -576,7 +492,6 @@ public class DaoAuthenticationProviderTests {
|
||||
}
|
||||
catch (UsernameNotFoundException success) {
|
||||
}
|
||||
|
||||
// ensure encoder invoked w/ non-null strings since PasswordEncoder impls may fail
|
||||
// if encoded password is null
|
||||
verify(encoder).matches(isA(String.class), isA(String.class));
|
||||
@@ -629,16 +544,13 @@ public class DaoAuthenticationProviderTests {
|
||||
MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod();
|
||||
userDetailsService.password = encoder.encode((CharSequence) foundUser.getCredentials());
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
|
||||
int sampleSize = 100;
|
||||
|
||||
List<Long> userFoundTimes = new ArrayList<>(sampleSize);
|
||||
for (int i = 0; i < sampleSize; i++) {
|
||||
long start = System.currentTimeMillis();
|
||||
provider.authenticate(foundUser);
|
||||
userFoundTimes.add(System.currentTimeMillis() - start);
|
||||
}
|
||||
|
||||
List<Long> userNotFoundTimes = new ArrayList<>(sampleSize);
|
||||
for (int i = 0; i < sampleSize; i++) {
|
||||
long start = System.currentTimeMillis();
|
||||
@@ -650,7 +562,6 @@ public class DaoAuthenticationProviderTests {
|
||||
}
|
||||
userNotFoundTimes.add(System.currentTimeMillis() - start);
|
||||
}
|
||||
|
||||
double userFoundAvg = avg(userFoundTimes);
|
||||
double userNotFoundAvg = avg(userNotFoundTimes);
|
||||
assertThat(Math.abs(userNotFoundAvg - userFoundAvg) <= 3).withFailMessage("User not found average "
|
||||
@@ -679,7 +590,6 @@ public class DaoAuthenticationProviderTests {
|
||||
}
|
||||
catch (UsernameNotFoundException success) {
|
||||
}
|
||||
|
||||
verify(encoder, times(0)).matches(anyString(), anyString());
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ public class AuthenticationEventTests {
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal",
|
||||
"Credentials");
|
||||
authentication.setDetails("127.0.0.1");
|
||||
|
||||
return authentication;
|
||||
}
|
||||
|
||||
@@ -60,13 +59,11 @@ public class AuthenticationEventTests {
|
||||
@Test
|
||||
public void testRejectsNullAuthentication() {
|
||||
AuthenticationException exception = new DisabledException("TEST");
|
||||
|
||||
try {
|
||||
new AuthenticationFailureDisabledEvent(null, exception);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +74,6 @@ public class AuthenticationEventTests {
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,6 @@ public class LoggerListenerTests {
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal",
|
||||
"Credentials");
|
||||
authentication.setDetails("127.0.0.1");
|
||||
|
||||
return authentication;
|
||||
}
|
||||
|
||||
@@ -43,7 +42,6 @@ public class LoggerListenerTests {
|
||||
new LockedException("TEST"));
|
||||
LoggerListener listener = new LoggerListener();
|
||||
listener.onApplicationEvent(event);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -80,7 +80,6 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
given(configuration.getAppConfigurationEntry(this.provider.getLoginContextName())).willReturn(aces);
|
||||
this.token = new UsernamePasswordAuthenticationToken("user", "password");
|
||||
ReflectionTestUtils.setField(this.provider, "log", this.log);
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
@@ -119,7 +118,6 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
}
|
||||
catch (AuthenticationException success) {
|
||||
}
|
||||
|
||||
verifyFailedLogin();
|
||||
}
|
||||
|
||||
@@ -131,7 +129,6 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
}
|
||||
catch (AuthenticationException success) {
|
||||
}
|
||||
|
||||
verifyFailedLogin();
|
||||
}
|
||||
|
||||
@@ -141,13 +138,10 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
SecurityContext securityContext = mock(SecurityContext.class);
|
||||
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
|
||||
LoginContext context = mock(LoginContext.class);
|
||||
|
||||
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
|
||||
given(securityContext.getAuthentication()).willReturn(token);
|
||||
given(token.getLoginContext()).willReturn(context);
|
||||
|
||||
this.provider.onApplicationEvent(event);
|
||||
|
||||
verify(event).getSecurityContexts();
|
||||
verify(securityContext).getAuthentication();
|
||||
verify(token).getLoginContext();
|
||||
@@ -158,9 +152,7 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
@Test
|
||||
public void logoutNullSession() {
|
||||
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
|
||||
|
||||
this.provider.handleLogout(event);
|
||||
|
||||
verify(event).getSecurityContexts();
|
||||
verify(this.log).debug(anyString());
|
||||
verifyNoMoreInteractions(event);
|
||||
@@ -170,11 +162,8 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
public void logoutNullAuthentication() {
|
||||
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
|
||||
SecurityContext securityContext = mock(SecurityContext.class);
|
||||
|
||||
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
|
||||
|
||||
this.provider.handleLogout(event);
|
||||
|
||||
verify(event).getSecurityContexts();
|
||||
verify(event).getSecurityContexts();
|
||||
verify(securityContext).getAuthentication();
|
||||
@@ -185,12 +174,9 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
public void logoutNonJaasAuthentication() {
|
||||
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
|
||||
SecurityContext securityContext = mock(SecurityContext.class);
|
||||
|
||||
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
|
||||
given(securityContext.getAuthentication()).willReturn(this.token);
|
||||
|
||||
this.provider.handleLogout(event);
|
||||
|
||||
verify(event).getSecurityContexts();
|
||||
verify(event).getSecurityContexts();
|
||||
verify(securityContext).getAuthentication();
|
||||
@@ -202,15 +188,12 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
|
||||
SecurityContext securityContext = mock(SecurityContext.class);
|
||||
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
|
||||
|
||||
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
|
||||
given(securityContext.getAuthentication()).willReturn(token);
|
||||
|
||||
this.provider.onApplicationEvent(event);
|
||||
verify(event).getSecurityContexts();
|
||||
verify(securityContext).getAuthentication();
|
||||
verify(token).getLoginContext();
|
||||
|
||||
verifyNoMoreInteractions(event, securityContext, token);
|
||||
}
|
||||
|
||||
@@ -221,14 +204,11 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
|
||||
LoginContext context = mock(LoginContext.class);
|
||||
LoginException loginException = new LoginException("Failed Login");
|
||||
|
||||
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
|
||||
given(securityContext.getAuthentication()).willReturn(token);
|
||||
given(token.getLoginContext()).willReturn(context);
|
||||
willThrow(loginException).given(context).logout();
|
||||
|
||||
this.provider.onApplicationEvent(event);
|
||||
|
||||
verify(event).getSecurityContexts();
|
||||
verify(securityContext).getAuthentication();
|
||||
verify(token).getLoginContext();
|
||||
@@ -241,7 +221,6 @@ public class DefaultJaasAuthenticationProviderTests {
|
||||
public void publishNullPublisher() {
|
||||
this.provider.setApplicationEventPublisher(null);
|
||||
AuthenticationException ae = new BadCredentialsException("Failed to login");
|
||||
|
||||
this.provider.publishFailureEvent(this.token, ae);
|
||||
this.provider.publishSuccessEvent(this.token);
|
||||
}
|
||||
|
||||
@@ -79,7 +79,6 @@ public class JaasAuthenticationProviderTests {
|
||||
}
|
||||
catch (AuthenticationException ex) {
|
||||
}
|
||||
|
||||
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
|
||||
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
|
||||
.isNotNull();
|
||||
@@ -94,7 +93,6 @@ public class JaasAuthenticationProviderTests {
|
||||
}
|
||||
catch (AuthenticationException ex) {
|
||||
}
|
||||
|
||||
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
|
||||
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
|
||||
.isNotNull();
|
||||
@@ -105,9 +103,7 @@ public class JaasAuthenticationProviderTests {
|
||||
public void testConfigurationLoop() throws Exception {
|
||||
String resName = "/" + getClass().getName().replace('.', '/') + ".conf";
|
||||
URL url = getClass().getResource(resName);
|
||||
|
||||
Security.setProperty("login.config.url.1", url.toString());
|
||||
|
||||
setUp();
|
||||
testFull();
|
||||
}
|
||||
@@ -119,7 +115,6 @@ public class JaasAuthenticationProviderTests {
|
||||
myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters());
|
||||
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
|
||||
myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName());
|
||||
|
||||
try {
|
||||
myJaasProvider.afterPropertiesSet();
|
||||
fail("Should have thrown ApplicationContextException");
|
||||
@@ -136,7 +131,6 @@ public class JaasAuthenticationProviderTests {
|
||||
// Create temp directory with a space in the name
|
||||
File configDir = new File(System.getProperty("java.io.tmpdir") + File.separator + "jaas test");
|
||||
configDir.deleteOnExit();
|
||||
|
||||
if (configDir.exists()) {
|
||||
configDir.delete();
|
||||
}
|
||||
@@ -149,14 +143,12 @@ public class JaasAuthenticationProviderTests {
|
||||
"JAASTestBlah {" + "org.springframework.security.authentication.jaas.TestLoginModule required;" + "};");
|
||||
pw.flush();
|
||||
pw.close();
|
||||
|
||||
JaasAuthenticationProvider myJaasProvider = new JaasAuthenticationProvider();
|
||||
myJaasProvider.setApplicationEventPublisher(this.context);
|
||||
myJaasProvider.setLoginConfig(new FileSystemResource(configFile));
|
||||
myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters());
|
||||
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
|
||||
myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName());
|
||||
|
||||
myJaasProvider.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@@ -168,7 +160,6 @@ public class JaasAuthenticationProviderTests {
|
||||
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
|
||||
myJaasProvider.setLoginConfig(this.jaasProvider.getLoginConfig());
|
||||
myJaasProvider.setLoginContextName(null);
|
||||
|
||||
try {
|
||||
myJaasProvider.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
@@ -176,9 +167,7 @@ public class JaasAuthenticationProviderTests {
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertThat(expected.getMessage()).startsWith("loginContextName must be set on");
|
||||
}
|
||||
|
||||
myJaasProvider.setLoginContextName("");
|
||||
|
||||
try {
|
||||
myJaasProvider.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
@@ -192,25 +181,19 @@ public class JaasAuthenticationProviderTests {
|
||||
public void testFull() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE"));
|
||||
|
||||
assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
|
||||
|
||||
Authentication auth = this.jaasProvider.authenticate(token);
|
||||
|
||||
assertThat(this.jaasProvider.getAuthorityGranters()).isNotNull();
|
||||
assertThat(this.jaasProvider.getCallbackHandlers()).isNotNull();
|
||||
assertThat(this.jaasProvider.getLoginConfig()).isNotNull();
|
||||
assertThat(this.jaasProvider.getLoginContextName()).isNotNull();
|
||||
|
||||
Collection<? extends GrantedAuthority> list = auth.getAuthorities();
|
||||
Set<String> set = AuthorityUtils.authorityListToSet(list);
|
||||
|
||||
assertThat(set.contains("ROLE_ONE")).withFailMessage("GrantedAuthorities should not contain ROLE_ONE")
|
||||
.isFalse();
|
||||
assertThat(set.contains("ROLE_TEST1")).withFailMessage("GrantedAuthorities should contain ROLE_TEST1").isTrue();
|
||||
assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue();
|
||||
boolean foundit = false;
|
||||
|
||||
for (GrantedAuthority a : list) {
|
||||
if (a instanceof JaasGrantedAuthority) {
|
||||
JaasGrantedAuthority grant = (JaasGrantedAuthority) a;
|
||||
@@ -219,9 +202,7 @@ public class JaasAuthenticationProviderTests {
|
||||
foundit = true;
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(foundit).as("Could not find a JaasGrantedAuthority").isTrue();
|
||||
|
||||
assertThat(this.eventCheck.successEvent).as("Success event should be fired").isNotNull();
|
||||
assertThat(this.eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal")
|
||||
.isEqualTo(auth);
|
||||
@@ -237,7 +218,6 @@ public class JaasAuthenticationProviderTests {
|
||||
public void testLoginExceptionResolver() {
|
||||
assertThat(this.jaasProvider.getLoginExceptionResolver()).isNotNull();
|
||||
this.jaasProvider.setLoginExceptionResolver((e) -> new LockedException("This is just a test!"));
|
||||
|
||||
try {
|
||||
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
|
||||
}
|
||||
@@ -251,26 +231,19 @@ public class JaasAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testLogout() throws Exception {
|
||||
MockLoginContext loginContext = new MockLoginContext(this.jaasProvider.getLoginContextName());
|
||||
|
||||
JaasAuthenticationToken token = new JaasAuthenticationToken(null, null, loginContext);
|
||||
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(token);
|
||||
|
||||
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
|
||||
given(event.getSecurityContexts()).willReturn(Arrays.asList(context));
|
||||
|
||||
this.jaasProvider.handleLogout(event);
|
||||
|
||||
assertThat(loginContext.loggedOut).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullDefaultAuthorities() {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
|
||||
|
||||
assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
|
||||
|
||||
Authentication auth = this.jaasProvider.authenticate(token);
|
||||
assertThat(auth.getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned")
|
||||
.hasSize(2);
|
||||
|
||||
@@ -35,7 +35,6 @@ public class JaasEventCheck implements ApplicationListener<JaasAuthenticationEve
|
||||
if (event instanceof JaasAuthenticationFailedEvent) {
|
||||
this.failedEvent = (JaasAuthenticationFailedEvent) event;
|
||||
}
|
||||
|
||||
if (event instanceof JaasAuthenticationSuccessEvent) {
|
||||
this.successEvent = (JaasAuthenticationSuccessEvent) event;
|
||||
}
|
||||
|
||||
@@ -46,7 +46,6 @@ public class Sec760Tests {
|
||||
p1.setAuthorityGranters(new AuthorityGranter[] { new TestAuthorityGranter() });
|
||||
p1.afterPropertiesSet();
|
||||
testAuthenticate(p1);
|
||||
|
||||
p2.setLoginConfig(new ClassPathResource(resolveConfigFile("/test2.conf")));
|
||||
p2.setLoginContextName("test2");
|
||||
p2.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] { new TestCallbackHandler(),
|
||||
@@ -59,7 +58,6 @@ public class Sec760Tests {
|
||||
private void testAuthenticate(JaasAuthenticationProvider p1) {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||
|
||||
Authentication auth = p1.authenticate(token);
|
||||
assertThat(auth).isNotNull();
|
||||
}
|
||||
|
||||
@@ -95,7 +95,6 @@ public class SecurityContextLoginModuleTests {
|
||||
this.module.login();
|
||||
assertThat(this.module.logout()).as("Should return true as it succeeds").isTrue();
|
||||
assertThat(this.module.getAuthentication()).as("Authentication should be null").isNull();
|
||||
|
||||
assertThat(this.subject.getPrincipals().contains(this.auth))
|
||||
.withFailMessage("Principals should not contain the authentication after logout").isFalse();
|
||||
}
|
||||
@@ -114,10 +113,8 @@ public class SecurityContextLoginModuleTests {
|
||||
@Test
|
||||
public void testNullAuthenticationInSecurityContextIgnored() throws Exception {
|
||||
this.module = new SecurityContextLoginModule();
|
||||
|
||||
Map<String, String> options = new HashMap<>();
|
||||
options.put("ignoreMissingAuthentication", "true");
|
||||
|
||||
this.module.initialize(this.subject, null, null, options);
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
assertThat(this.module.login()).as("Should return false and ask to be ignored").isFalse();
|
||||
|
||||
@@ -28,12 +28,10 @@ public class TestAuthorityGranter implements AuthorityGranter {
|
||||
@Override
|
||||
public Set<String> grant(Principal principal) {
|
||||
Set<String> rtnSet = new HashSet<>();
|
||||
|
||||
if (principal.getName().equals("TEST_PRINCIPAL")) {
|
||||
rtnSet.add("ROLE_TEST1");
|
||||
rtnSet.add("ROLE_TEST2");
|
||||
}
|
||||
|
||||
return rtnSet;
|
||||
}
|
||||
|
||||
|
||||
@@ -52,14 +52,11 @@ public class TestLoginModule implements LoginModule {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
|
||||
this.subject = subject;
|
||||
|
||||
try {
|
||||
TextInputCallback textCallback = new TextInputCallback("prompt");
|
||||
NameCallback nameCallback = new NameCallback("prompt");
|
||||
PasswordCallback passwordCallback = new PasswordCallback("prompt", false);
|
||||
|
||||
callbackHandler.handle(new Callback[] { textCallback, nameCallback, passwordCallback });
|
||||
|
||||
this.password = new String(passwordCallback.getPassword());
|
||||
this.user = nameCallback.getName();
|
||||
}
|
||||
@@ -73,15 +70,11 @@ public class TestLoginModule implements LoginModule {
|
||||
if (!this.user.equals("user")) {
|
||||
throw new LoginException("Bad User");
|
||||
}
|
||||
|
||||
if (!this.password.equals("password")) {
|
||||
throw new LoginException("Bad Password");
|
||||
}
|
||||
|
||||
this.subject.getPrincipals().add(() -> "TEST_PRINCIPAL");
|
||||
|
||||
this.subject.getPrincipals().add(() -> "NULL_PRINCIPAL");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,6 @@ public class InMemoryConfigurationTests {
|
||||
public void setUp() {
|
||||
this.defaultEntries = new AppConfigurationEntry[] { new AppConfigurationEntry(TestLoginModule.class.getName(),
|
||||
LoginModuleControlFlag.REQUIRED, Collections.<String, Object>emptyMap()) };
|
||||
|
||||
this.mappedEntries = Collections.<String, AppConfigurationEntry[]>singletonMap("name",
|
||||
new AppConfigurationEntry[] { new AppConfigurationEntry(TestLoginModule.class.getName(),
|
||||
LoginModuleControlFlag.OPTIONAL, Collections.<String, Object>emptyMap()) });
|
||||
|
||||
@@ -41,24 +41,20 @@ public class RemoteAuthenticationManagerImplTests {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
|
||||
manager.setAuthenticationManager(am);
|
||||
|
||||
manager.attemptAuthentication("rod", "password");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartupChecksAuthenticationManagerSet() throws Exception {
|
||||
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
|
||||
|
||||
try {
|
||||
manager.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
manager.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
manager.afterPropertiesSet();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -67,7 +63,6 @@ public class RemoteAuthenticationManagerImplTests {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
given(am.authenticate(any(Authentication.class))).willReturn(new TestingAuthenticationToken("u", "p", "A"));
|
||||
manager.setAuthenticationManager(am);
|
||||
|
||||
manager.attemptAuthentication("rod", "password");
|
||||
}
|
||||
|
||||
|
||||
@@ -39,13 +39,11 @@ public class RemoteAuthenticationProviderTests {
|
||||
public void testExceptionsGetPassedBackToCaller() {
|
||||
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
|
||||
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
|
||||
|
||||
try {
|
||||
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
|
||||
fail("Should have thrown RemoteAuthenticationException");
|
||||
}
|
||||
catch (RemoteAuthenticationException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,25 +57,20 @@ public class RemoteAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testStartupChecksAuthenticationManagerSet() throws Exception {
|
||||
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
|
||||
|
||||
try {
|
||||
provider.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
|
||||
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true));
|
||||
provider.afterPropertiesSet();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessfulAuthenticationCreatesObject() {
|
||||
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
|
||||
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true));
|
||||
|
||||
Authentication result = provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
|
||||
assertThat(result.getPrincipal()).isEqualTo("rod");
|
||||
assertThat(result.getCredentials()).isEqualTo("password");
|
||||
@@ -88,14 +81,12 @@ public class RemoteAuthenticationProviderTests {
|
||||
public void testNullCredentialsDoesNotCauseNullPointerException() {
|
||||
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
|
||||
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
|
||||
|
||||
try {
|
||||
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", null));
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (RemoteAuthenticationException success) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -38,10 +38,8 @@ public class RememberMeAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testDetectsAnInvalidKey() {
|
||||
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
|
||||
|
||||
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("WRONG_KEY", "Test",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||
|
||||
try {
|
||||
aap.authenticate(token);
|
||||
fail("Should have thrown BadCredentialsException");
|
||||
@@ -57,7 +55,6 @@ public class RememberMeAuthenticationProviderTests {
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,10 +68,8 @@ public class RememberMeAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testIgnoresClassesItDoesNotSupport() {
|
||||
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
|
||||
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password", "ROLE_A");
|
||||
assertThat(aap.supports(TestingAuthenticationToken.class)).isFalse();
|
||||
|
||||
// Try it anyway
|
||||
assertThat(aap.authenticate(token)).isNull();
|
||||
}
|
||||
@@ -82,12 +77,9 @@ public class RememberMeAuthenticationProviderTests {
|
||||
@Test
|
||||
public void testNormalOperation() {
|
||||
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
|
||||
|
||||
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("qwerty", "Test",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||
|
||||
Authentication result = aap.authenticate(token);
|
||||
|
||||
assertThat(token).isEqualTo(result);
|
||||
}
|
||||
|
||||
|
||||
@@ -45,17 +45,13 @@ public class RememberMeAuthenticationTokenTests {
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
|
||||
try {
|
||||
new RememberMeAuthenticationToken("key", null, ROLES_12);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
|
||||
try {
|
||||
List<GrantedAuthority> authsContainingNull = new ArrayList<>();
|
||||
authsContainingNull.add(null);
|
||||
@@ -63,7 +59,6 @@ public class RememberMeAuthenticationTokenTests {
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,14 +66,12 @@ public class RememberMeAuthenticationTokenTests {
|
||||
public void testEqualsWhenEqual() {
|
||||
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
|
||||
RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
|
||||
|
||||
assertThat(token2).isEqualTo(token1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetters() {
|
||||
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
|
||||
|
||||
assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
|
||||
assertThat(token.getPrincipal()).isEqualTo("Test");
|
||||
assertThat(token.getCredentials()).isEqualTo("");
|
||||
@@ -92,7 +85,6 @@ public class RememberMeAuthenticationTokenTests {
|
||||
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
|
||||
RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("key", "DIFFERENT_PRINCIPAL",
|
||||
ROLES_12);
|
||||
|
||||
assertThat(token1.equals(token2)).isFalse();
|
||||
}
|
||||
|
||||
@@ -101,7 +93,6 @@ public class RememberMeAuthenticationTokenTests {
|
||||
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
|
||||
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
|
||||
ROLES_12);
|
||||
|
||||
assertThat(token1.equals(token2)).isFalse();
|
||||
}
|
||||
|
||||
@@ -109,7 +100,6 @@ public class RememberMeAuthenticationTokenTests {
|
||||
public void testNotEqualsDueToKey() {
|
||||
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
|
||||
RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("DIFFERENT_KEY", "Test", ROLES_12);
|
||||
|
||||
assertThat(token1.equals(token2)).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@@ -46,39 +46,32 @@ public class AuthenticatedReactiveAuthorizationManagerTests {
|
||||
@Test
|
||||
public void checkWhenAuthenticatedThenReturnTrue() {
|
||||
given(this.authentication.isAuthenticated()).willReturn(true);
|
||||
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenNotAuthenticatedThenReturnFalse() {
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenEmptyThenReturnFalse() {
|
||||
boolean granted = this.manager.check(Mono.empty(), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenAnonymousAuthenticatedThenReturnFalse() {
|
||||
AnonymousAuthenticationToken anonymousAuthenticationToken = mock(AnonymousAuthenticationToken.class);
|
||||
|
||||
boolean granted = this.manager.check(Mono.just(anonymousAuthenticationToken), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenErrorThenError() {
|
||||
Mono<AuthorizationDecision> result = this.manager.check(Mono.error(new RuntimeException("ooops")), null);
|
||||
|
||||
StepVerifier.create(result).expectError().verify();
|
||||
}
|
||||
|
||||
|
||||
@@ -46,21 +46,18 @@ public class AuthorityReactiveAuthorizationManagerTests {
|
||||
@Test
|
||||
public void checkWhenHasAuthorityAndNotAuthenticatedThenReturnFalse() {
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenHasAuthorityAndEmptyThenReturnFalse() {
|
||||
boolean granted = this.manager.check(Mono.empty(), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenHasAuthorityAndErrorThenError() {
|
||||
Mono<AuthorizationDecision> result = this.manager.check(Mono.error(new RuntimeException("ooops")), null);
|
||||
|
||||
StepVerifier.create(result).expectError().verify();
|
||||
}
|
||||
|
||||
@@ -68,27 +65,21 @@ public class AuthorityReactiveAuthorizationManagerTests {
|
||||
public void checkWhenHasAuthorityAndAuthenticatedAndNoAuthoritiesThenReturnFalse() {
|
||||
given(this.authentication.isAuthenticated()).willReturn(true);
|
||||
given(this.authentication.getAuthorities()).willReturn(Collections.emptyList());
|
||||
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenHasAuthorityAndAuthenticatedAndWrongAuthoritiesThenReturnFalse() {
|
||||
this.authentication = new TestingAuthenticationToken("rob", "secret", "ROLE_ADMIN");
|
||||
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWhenHasAuthorityAndAuthorizedThenReturnTrue() {
|
||||
this.authentication = new TestingAuthenticationToken("rob", "secret", "ADMIN");
|
||||
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isTrue();
|
||||
}
|
||||
|
||||
@@ -96,9 +87,7 @@ public class AuthorityReactiveAuthorizationManagerTests {
|
||||
public void checkWhenHasRoleAndAuthorizedThenReturnTrue() {
|
||||
this.manager = AuthorityReactiveAuthorizationManager.hasRole("ADMIN");
|
||||
this.authentication = new TestingAuthenticationToken("rob", "secret", "ROLE_ADMIN");
|
||||
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isTrue();
|
||||
}
|
||||
|
||||
@@ -106,9 +95,7 @@ public class AuthorityReactiveAuthorizationManagerTests {
|
||||
public void checkWhenHasRoleAndNotAuthorizedThenReturnFalse() {
|
||||
this.manager = AuthorityReactiveAuthorizationManager.hasRole("ADMIN");
|
||||
this.authentication = new TestingAuthenticationToken("rob", "secret", "ADMIN");
|
||||
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isFalse();
|
||||
}
|
||||
|
||||
@@ -117,9 +104,7 @@ public class AuthorityReactiveAuthorizationManagerTests {
|
||||
this.manager = AuthorityReactiveAuthorizationManager.hasAnyRole("GENERAL", "USER", "TEST");
|
||||
this.authentication = new TestingAuthenticationToken("rob", "secret", "ROLE_USER", "ROLE_AUDITING",
|
||||
"ROLE_ADMIN");
|
||||
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isTrue();
|
||||
}
|
||||
|
||||
@@ -127,9 +112,7 @@ public class AuthorityReactiveAuthorizationManagerTests {
|
||||
public void checkWhenHasAnyRoleAndNotAuthorizedThenReturnFalse() {
|
||||
this.manager = AuthorityReactiveAuthorizationManager.hasAnyRole("GENERAL", "USER", "TEST");
|
||||
this.authentication = new TestingAuthenticationToken("rob", "secret", "USER", "AUDITING", "ADMIN");
|
||||
|
||||
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
|
||||
|
||||
assertThat(granted).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@@ -66,7 +66,6 @@ public class DelegatingSecurityContextRunnableTests {
|
||||
assertThat(SecurityContextHolder.getContext()).isEqualTo(this.securityContext);
|
||||
return null;
|
||||
}).given(this.delegate).run();
|
||||
|
||||
this.executor = Executors.newFixedThreadPool(1);
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ public class DelegatingApplicationListenerTests {
|
||||
@Test
|
||||
public void processEventNull() {
|
||||
this.listener.onApplicationEvent(null);
|
||||
|
||||
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
|
||||
}
|
||||
|
||||
@@ -60,14 +59,12 @@ public class DelegatingApplicationListenerTests {
|
||||
given(this.delegate.supportsEventType(this.event.getClass())).willReturn(true);
|
||||
given(this.delegate.supportsSourceType(this.event.getSource().getClass())).willReturn(true);
|
||||
this.listener.onApplicationEvent(this.event);
|
||||
|
||||
verify(this.delegate).onApplicationEvent(this.event);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void processEventEventTypeNotSupported() {
|
||||
this.listener.onApplicationEvent(this.event);
|
||||
|
||||
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
|
||||
}
|
||||
|
||||
@@ -75,7 +72,6 @@ public class DelegatingApplicationListenerTests {
|
||||
public void processEventSourceTypeNotSupported() {
|
||||
given(this.delegate.supportsEventType(this.event.getClass())).willReturn(true);
|
||||
this.listener.onApplicationEvent(this.event);
|
||||
|
||||
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
|
||||
}
|
||||
|
||||
|
||||
@@ -63,20 +63,16 @@ public class SpringSecurityCoreVersionTests {
|
||||
public void springVersionIsUpToDate() {
|
||||
// Property is set by the build script
|
||||
String springVersion = System.getProperty("springVersion");
|
||||
|
||||
assertThat(SpringSecurityCoreVersion.MIN_SPRING_VERSION).isEqualTo(springVersion);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serialVersionMajorAndMinorVersionMatchBuildVersion() {
|
||||
String version = System.getProperty("springSecurityVersion");
|
||||
|
||||
// Strip patch version
|
||||
String serialVersion = String.valueOf(SpringSecurityCoreVersion.SERIAL_VERSION_UID).substring(0, 2);
|
||||
|
||||
assertThat(serialVersion.charAt(0)).isEqualTo(version.charAt(0));
|
||||
assertThat(serialVersion.charAt(1)).isEqualTo(version.charAt(2));
|
||||
|
||||
}
|
||||
|
||||
// SEC-2295
|
||||
@@ -87,9 +83,7 @@ public class SpringSecurityCoreVersionTests {
|
||||
PowerMockito.spy(SpringVersion.class);
|
||||
PowerMockito.doReturn(version).when(SpringSecurityCoreVersion.class, "getVersion");
|
||||
PowerMockito.doReturn(version).when(SpringVersion.class, "getVersion");
|
||||
|
||||
performChecks();
|
||||
|
||||
verifyZeroInteractions(this.logger);
|
||||
}
|
||||
|
||||
@@ -99,9 +93,7 @@ public class SpringSecurityCoreVersionTests {
|
||||
PowerMockito.spy(SpringVersion.class);
|
||||
PowerMockito.doReturn("1").when(SpringSecurityCoreVersion.class, "getVersion");
|
||||
PowerMockito.doReturn(null).when(SpringVersion.class, "getVersion");
|
||||
|
||||
performChecks();
|
||||
|
||||
verifyZeroInteractions(this.logger);
|
||||
}
|
||||
|
||||
@@ -111,9 +103,7 @@ public class SpringSecurityCoreVersionTests {
|
||||
PowerMockito.spy(SpringVersion.class);
|
||||
PowerMockito.doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion");
|
||||
PowerMockito.doReturn("2").when(SpringVersion.class, "getVersion");
|
||||
|
||||
performChecks();
|
||||
|
||||
verify(this.logger, times(1)).warn(any());
|
||||
}
|
||||
|
||||
@@ -123,9 +113,7 @@ public class SpringSecurityCoreVersionTests {
|
||||
PowerMockito.spy(SpringVersion.class);
|
||||
PowerMockito.doReturn("4.0.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion");
|
||||
PowerMockito.doReturn("4.0.0.RELEASE").when(SpringVersion.class, "getVersion");
|
||||
|
||||
performChecks();
|
||||
|
||||
verify(this.logger, never()).warn(any());
|
||||
}
|
||||
|
||||
@@ -137,9 +125,7 @@ public class SpringSecurityCoreVersionTests {
|
||||
PowerMockito.spy(SpringVersion.class);
|
||||
PowerMockito.doReturn("3.2.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion");
|
||||
PowerMockito.doReturn("3.2.10.RELEASE").when(SpringVersion.class, "getVersion");
|
||||
|
||||
performChecks(minSpringVersion);
|
||||
|
||||
verify(this.logger, never()).warn(any());
|
||||
}
|
||||
|
||||
@@ -150,9 +136,7 @@ public class SpringSecurityCoreVersionTests {
|
||||
PowerMockito.doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion");
|
||||
PowerMockito.doReturn("2").when(SpringVersion.class, "getVersion");
|
||||
System.setProperty(getDisableChecksProperty(), Boolean.TRUE.toString());
|
||||
|
||||
performChecks();
|
||||
|
||||
verifyZeroInteractions(this.logger);
|
||||
}
|
||||
|
||||
|
||||
@@ -42,12 +42,10 @@ public class SpringSecurityMessageSourceTests {
|
||||
// Change Locale to English
|
||||
Locale before = LocaleContextHolder.getLocale();
|
||||
LocaleContextHolder.setLocale(Locale.FRENCH);
|
||||
|
||||
// Cause a message to be generated
|
||||
MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
|
||||
assertThat("Le jeton nonce est compromis FOOBAR").isEqualTo(messages.getMessage(
|
||||
"DigestAuthenticationFilter.nonceCompromised", new Object[] { "FOOBAR" }, "ERROR - FAILED TO LOOKUP"));
|
||||
|
||||
// Revert to original Locale
|
||||
LocaleContextHolder.setLocale(before);
|
||||
}
|
||||
@@ -57,14 +55,11 @@ public class SpringSecurityMessageSourceTests {
|
||||
public void germanSystemLocaleWithEnglishLocaleContextHolder() {
|
||||
Locale beforeSystem = Locale.getDefault();
|
||||
Locale.setDefault(Locale.GERMAN);
|
||||
|
||||
Locale beforeHolder = LocaleContextHolder.getLocale();
|
||||
LocaleContextHolder.setLocale(Locale.US);
|
||||
|
||||
MessageSourceAccessor msgs = SpringSecurityMessageSource.getAccessor();
|
||||
assertThat("Access is denied")
|
||||
.isEqualTo(msgs.getMessage("AbstractAccessDecisionManager.accessDenied", "Ooops"));
|
||||
|
||||
// Revert to original Locale
|
||||
Locale.setDefault(beforeSystem);
|
||||
LocaleContextHolder.setLocale(beforeHolder);
|
||||
|
||||
@@ -34,9 +34,7 @@ public class AuthorityUtilsTests {
|
||||
public void commaSeparatedStringIsParsedCorrectly() {
|
||||
List<GrantedAuthority> authorityArray = AuthorityUtils
|
||||
.commaSeparatedStringToAuthorityList(" ROLE_A, B, C, ROLE_D\n,\n E ");
|
||||
|
||||
Set<String> authorities = AuthorityUtils.authorityListToSet(authorityArray);
|
||||
|
||||
assertThat(authorities.contains("B")).isTrue();
|
||||
assertThat(authorities.contains("C")).isTrue();
|
||||
assertThat(authorities.contains("E")).isTrue();
|
||||
|
||||
@@ -35,14 +35,10 @@ public class SimpleGrantedAuthorityTests {
|
||||
SimpleGrantedAuthority auth1 = new SimpleGrantedAuthority("TEST");
|
||||
assertThat(auth1).isEqualTo(auth1);
|
||||
assertThat(new SimpleGrantedAuthority("TEST")).isEqualTo(auth1);
|
||||
|
||||
assertThat(auth1.equals("TEST")).isFalse();
|
||||
|
||||
SimpleGrantedAuthority auth3 = new SimpleGrantedAuthority("NOT_EQUAL");
|
||||
assertThat(!auth1.equals(auth3)).isTrue();
|
||||
|
||||
assertThat(auth1.equals(mock(GrantedAuthority.class))).isFalse();
|
||||
|
||||
assertThat(auth1.equals(222)).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@@ -57,13 +57,11 @@ public class SimpleAuthoritiesMapperTests {
|
||||
assertThat(mapped).hasSize(2);
|
||||
assertThat(mapped.contains("AaA")).isTrue();
|
||||
assertThat(mapped.contains("Bbb")).isTrue();
|
||||
|
||||
mapper.setConvertToLowerCase(true);
|
||||
mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap));
|
||||
assertThat(mapped).hasSize(2);
|
||||
assertThat(mapped.contains("aaa")).isTrue();
|
||||
assertThat(mapped.contains("bbb")).isTrue();
|
||||
|
||||
mapper.setConvertToLowerCase(false);
|
||||
mapper.setConvertToUpperCase(true);
|
||||
mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap));
|
||||
@@ -76,7 +74,6 @@ public class SimpleAuthoritiesMapperTests {
|
||||
public void duplicatesAreRemoved() {
|
||||
SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
|
||||
mapper.setConvertToUpperCase(true);
|
||||
|
||||
Set<String> mapped = AuthorityUtils
|
||||
.authorityListToSet(mapper.mapAuthorities(AuthorityUtils.createAuthorityList("AaA", "AAA")));
|
||||
assertThat(mapped).hasSize(1);
|
||||
|
||||
@@ -32,7 +32,6 @@ public class ReactiveSecurityContextHolderTests {
|
||||
@Test
|
||||
public void getContextWhenEmpty() {
|
||||
Mono<SecurityContext> context = ReactiveSecurityContextHolder.getContext();
|
||||
|
||||
StepVerifier.create(context).verifyComplete();
|
||||
}
|
||||
|
||||
@@ -40,23 +39,19 @@ public class ReactiveSecurityContextHolderTests {
|
||||
public void setContextAndGetContextThenEmitsContext() {
|
||||
SecurityContext expectedContext = new SecurityContextImpl(
|
||||
new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
|
||||
Mono<SecurityContext> context = Mono.subscriberContext()
|
||||
.flatMap((c) -> ReactiveSecurityContextHolder.getContext())
|
||||
.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(expectedContext)));
|
||||
|
||||
StepVerifier.create(context).expectNext(expectedContext).verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void demo() {
|
||||
Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
|
||||
|
||||
Mono<String> messageByUsername = ReactiveSecurityContextHolder.getContext()
|
||||
.map(SecurityContext::getAuthentication).map(Authentication::getName)
|
||||
.flatMap(this::findMessageByUsername)
|
||||
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
|
||||
|
||||
StepVerifier.create(messageByUsername).expectNext("Hi user").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -68,23 +63,19 @@ public class ReactiveSecurityContextHolderTests {
|
||||
public void setContextAndClearAndGetContextThenEmitsEmpty() {
|
||||
SecurityContext expectedContext = new SecurityContextImpl(
|
||||
new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
|
||||
Mono<SecurityContext> context = Mono.subscriberContext()
|
||||
.flatMap((c) -> ReactiveSecurityContextHolder.getContext())
|
||||
.subscriberContext(ReactiveSecurityContextHolder.clearContext())
|
||||
.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(expectedContext)));
|
||||
|
||||
StepVerifier.create(context).verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAuthenticationAndGetContextThenEmitsContext() {
|
||||
Authentication expectedAuthentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
|
||||
|
||||
Mono<Authentication> authentication = Mono.subscriberContext()
|
||||
.flatMap((c) -> ReactiveSecurityContextHolder.getContext()).map(SecurityContext::getAuthentication)
|
||||
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(expectedAuthentication));
|
||||
|
||||
StepVerifier.create(authentication).expectNext(expectedAuthentication).verifyComplete();
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,6 @@ public class SecurityContextHolderTests {
|
||||
fail("Should have rejected null");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,15 +48,12 @@ public class DefaultSecurityParameterNameDiscovererTests {
|
||||
public void constructorDefault() {
|
||||
List<ParameterNameDiscoverer> discoverers = (List<ParameterNameDiscoverer>) ReflectionTestUtils
|
||||
.getField(this.discoverer, "parameterNameDiscoverers");
|
||||
|
||||
assertThat(discoverers).hasSize(2);
|
||||
|
||||
ParameterNameDiscoverer annotationDisc = discoverers.get(0);
|
||||
assertThat(annotationDisc).isInstanceOf(AnnotationParameterNameDiscoverer.class);
|
||||
Set<String> annotationsToUse = (Set<String>) ReflectionTestUtils.getField(annotationDisc,
|
||||
"annotationClassesToUse");
|
||||
assertThat(annotationsToUse).containsOnly("org.springframework.security.access.method.P", P.class.getName());
|
||||
|
||||
assertThat(discoverers.get(1).getClass()).isEqualTo(DefaultParameterNameDiscoverer.class);
|
||||
}
|
||||
|
||||
@@ -64,19 +61,15 @@ public class DefaultSecurityParameterNameDiscovererTests {
|
||||
public void constructorDiscoverers() {
|
||||
this.discoverer = new DefaultSecurityParameterNameDiscoverer(
|
||||
Arrays.asList(new LocalVariableTableParameterNameDiscoverer()));
|
||||
|
||||
List<ParameterNameDiscoverer> discoverers = (List<ParameterNameDiscoverer>) ReflectionTestUtils
|
||||
.getField(this.discoverer, "parameterNameDiscoverers");
|
||||
|
||||
assertThat(discoverers).hasSize(3);
|
||||
assertThat(discoverers.get(0)).isInstanceOf(LocalVariableTableParameterNameDiscoverer.class);
|
||||
|
||||
ParameterNameDiscoverer annotationDisc = discoverers.get(1);
|
||||
assertThat(annotationDisc).isInstanceOf(AnnotationParameterNameDiscoverer.class);
|
||||
Set<String> annotationsToUse = (Set<String>) ReflectionTestUtils.getField(annotationDisc,
|
||||
"annotationClassesToUse");
|
||||
assertThat(annotationsToUse).containsOnly("org.springframework.security.access.method.P", P.class.getName());
|
||||
|
||||
assertThat(discoverers.get(2)).isInstanceOf(DefaultParameterNameDiscoverer.class);
|
||||
}
|
||||
|
||||
|
||||
@@ -34,16 +34,12 @@ public class SessionInformationTests {
|
||||
Object principal = "Some principal object";
|
||||
String sessionId = "1234567890";
|
||||
Date currentDate = new Date();
|
||||
|
||||
SessionInformation info = new SessionInformation(principal, sessionId, currentDate);
|
||||
assertThat(info.getPrincipal()).isEqualTo(principal);
|
||||
assertThat(info.getSessionId()).isEqualTo(sessionId);
|
||||
assertThat(info.getLastRequest()).isEqualTo(currentDate);
|
||||
|
||||
Thread.sleep(10);
|
||||
|
||||
info.refreshLastRequest();
|
||||
|
||||
assertThat(info.getLastRequest().after(currentDate)).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@@ -44,10 +44,8 @@ public class SessionRegistryImplTests {
|
||||
public void sessionDestroyedEventRemovesSessionFromRegistry() {
|
||||
Object principal = "Some principal object";
|
||||
final String sessionId = "zzzz";
|
||||
|
||||
// Register new Session
|
||||
this.sessionRegistry.registerNewSession(sessionId, principal);
|
||||
|
||||
// De-register session via an ApplicationEvent
|
||||
this.sessionRegistry.onApplicationEvent(new SessionDestroyedEvent("") {
|
||||
@Override
|
||||
@@ -60,7 +58,6 @@ public class SessionRegistryImplTests {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
// Check attempts to retrieve cleared session return null
|
||||
assertThat(this.sessionRegistry.getSessionInformation(sessionId)).isNull();
|
||||
}
|
||||
@@ -70,10 +67,8 @@ public class SessionRegistryImplTests {
|
||||
Object principal = "Some principal object";
|
||||
final String sessionId = "zzzz";
|
||||
final String newSessionId = "123";
|
||||
|
||||
// Register new Session
|
||||
this.sessionRegistry.registerNewSession(sessionId, principal);
|
||||
|
||||
// De-register session via an ApplicationEvent
|
||||
this.sessionRegistry.onApplicationEvent(new SessionIdChangedEvent("") {
|
||||
@Override
|
||||
@@ -86,7 +81,6 @@ public class SessionRegistryImplTests {
|
||||
return newSessionId;
|
||||
}
|
||||
});
|
||||
|
||||
assertThat(this.sessionRegistry.getSessionInformation(sessionId)).isNull();
|
||||
assertThat(this.sessionRegistry.getSessionInformation(newSessionId)).isNotNull();
|
||||
assertThat(this.sessionRegistry.getSessionInformation(newSessionId).getPrincipal()).isEqualTo(principal);
|
||||
@@ -99,11 +93,9 @@ public class SessionRegistryImplTests {
|
||||
String sessionId1 = "1234567890";
|
||||
String sessionId2 = "9876543210";
|
||||
String sessionId3 = "5432109876";
|
||||
|
||||
this.sessionRegistry.registerNewSession(sessionId1, principal1);
|
||||
this.sessionRegistry.registerNewSession(sessionId2, principal1);
|
||||
this.sessionRegistry.registerNewSession(sessionId3, principal2);
|
||||
|
||||
assertThat(this.sessionRegistry.getAllPrincipals()).hasSize(2);
|
||||
assertThat(this.sessionRegistry.getAllPrincipals().contains(principal1)).isTrue();
|
||||
assertThat(this.sessionRegistry.getAllPrincipals().contains(principal2)).isTrue();
|
||||
@@ -115,32 +107,24 @@ public class SessionRegistryImplTests {
|
||||
String sessionId = "1234567890";
|
||||
// Register new Session
|
||||
this.sessionRegistry.registerNewSession(sessionId, principal);
|
||||
|
||||
// Retrieve existing session by session ID
|
||||
Date currentDateTime = this.sessionRegistry.getSessionInformation(sessionId).getLastRequest();
|
||||
assertThat(this.sessionRegistry.getSessionInformation(sessionId).getPrincipal()).isEqualTo(principal);
|
||||
assertThat(this.sessionRegistry.getSessionInformation(sessionId).getSessionId()).isEqualTo(sessionId);
|
||||
assertThat(this.sessionRegistry.getSessionInformation(sessionId).getLastRequest()).isNotNull();
|
||||
|
||||
// Retrieve existing session by principal
|
||||
assertThat(this.sessionRegistry.getAllSessions(principal, false)).hasSize(1);
|
||||
|
||||
// Sleep to ensure SessionRegistryImpl will update time
|
||||
Thread.sleep(1000);
|
||||
|
||||
// Update request date/time
|
||||
this.sessionRegistry.refreshLastRequest(sessionId);
|
||||
|
||||
Date retrieved = this.sessionRegistry.getSessionInformation(sessionId).getLastRequest();
|
||||
assertThat(retrieved.after(currentDateTime)).isTrue();
|
||||
|
||||
// Check it retrieves correctly when looked up via principal
|
||||
assertThat(this.sessionRegistry.getAllSessions(principal, false).get(0).getLastRequest()).isCloseTo(retrieved,
|
||||
2000L);
|
||||
|
||||
// Clear session information
|
||||
this.sessionRegistry.removeSessionInformation(sessionId);
|
||||
|
||||
// Check attempts to retrieve cleared session return null
|
||||
assertThat(this.sessionRegistry.getSessionInformation(sessionId)).isNull();
|
||||
assertThat(this.sessionRegistry.getAllSessions(principal, false)).isEmpty();
|
||||
@@ -151,21 +135,17 @@ public class SessionRegistryImplTests {
|
||||
Object principal = "Some principal object";
|
||||
String sessionId1 = "1234567890";
|
||||
String sessionId2 = "9876543210";
|
||||
|
||||
this.sessionRegistry.registerNewSession(sessionId1, principal);
|
||||
List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(principal, false);
|
||||
assertThat(sessions).hasSize(1);
|
||||
assertThat(contains(sessionId1, principal)).isTrue();
|
||||
|
||||
this.sessionRegistry.registerNewSession(sessionId2, principal);
|
||||
sessions = this.sessionRegistry.getAllSessions(principal, false);
|
||||
assertThat(sessions).hasSize(2);
|
||||
assertThat(contains(sessionId2, principal)).isTrue();
|
||||
|
||||
// Expire one session
|
||||
SessionInformation session = this.sessionRegistry.getSessionInformation(sessionId2);
|
||||
session.expireNow();
|
||||
|
||||
// Check retrieval still correct
|
||||
assertThat(this.sessionRegistry.getSessionInformation(sessionId2).isExpired()).isTrue();
|
||||
assertThat(this.sessionRegistry.getSessionInformation(sessionId1).isExpired()).isFalse();
|
||||
@@ -176,22 +156,18 @@ public class SessionRegistryImplTests {
|
||||
Object principal = "Some principal object";
|
||||
String sessionId1 = "1234567890";
|
||||
String sessionId2 = "9876543210";
|
||||
|
||||
this.sessionRegistry.registerNewSession(sessionId1, principal);
|
||||
List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(principal, false);
|
||||
assertThat(sessions).hasSize(1);
|
||||
assertThat(contains(sessionId1, principal)).isTrue();
|
||||
|
||||
this.sessionRegistry.registerNewSession(sessionId2, principal);
|
||||
sessions = this.sessionRegistry.getAllSessions(principal, false);
|
||||
assertThat(sessions).hasSize(2);
|
||||
assertThat(contains(sessionId2, principal)).isTrue();
|
||||
|
||||
this.sessionRegistry.removeSessionInformation(sessionId1);
|
||||
sessions = this.sessionRegistry.getAllSessions(principal, false);
|
||||
assertThat(sessions).hasSize(1);
|
||||
assertThat(contains(sessionId2, principal)).isTrue();
|
||||
|
||||
this.sessionRegistry.removeSessionInformation(sessionId2);
|
||||
assertThat(this.sessionRegistry.getSessionInformation(sessionId2)).isNull();
|
||||
assertThat(this.sessionRegistry.getAllSessions(principal, false)).isEmpty();
|
||||
@@ -199,13 +175,11 @@ public class SessionRegistryImplTests {
|
||||
|
||||
private boolean contains(String sessionId, Object principal) {
|
||||
List<SessionInformation> info = this.sessionRegistry.getAllSessions(principal, false);
|
||||
|
||||
for (SessionInformation sessionInformation : info) {
|
||||
if (sessionId.equals(sessionInformation.getSessionId())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,6 @@ public class DefaultTokenTests {
|
||||
String key = "key";
|
||||
long created = new Date().getTime();
|
||||
String extendedInformation = "extended";
|
||||
|
||||
DefaultToken t1 = new DefaultToken(key, created, extendedInformation);
|
||||
DefaultToken t2 = new DefaultToken(key, created, extendedInformation);
|
||||
assertThat(t2).isEqualTo(t1);
|
||||
@@ -52,7 +51,6 @@ public class DefaultTokenTests {
|
||||
public void testEqualityWithDifferentExtendedInformation3() {
|
||||
String key = "key";
|
||||
long created = new Date().getTime();
|
||||
|
||||
DefaultToken t1 = new DefaultToken(key, created, "length1");
|
||||
DefaultToken t2 = new DefaultToken(key, created, "longerLength2");
|
||||
assertThat(t1).isNotEqualTo(t2);
|
||||
|
||||
@@ -33,7 +33,6 @@ public class MapReactiveUserDetailsServiceTests {
|
||||
.roles("USER")
|
||||
.build();
|
||||
// @formatter:on
|
||||
|
||||
private MapReactiveUserDetailsService users = new MapReactiveUserDetailsService(Arrays.asList(USER_DETAILS));
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
@@ -71,7 +70,6 @@ public class MapReactiveUserDetailsServiceTests {
|
||||
assertThat(foundUser.getPassword()).isNotEmpty();
|
||||
foundUser.eraseCredentials();
|
||||
assertThat(foundUser.getPassword()).isNull();
|
||||
|
||||
foundUser = this.users.findByUsername(USER_DETAILS.getUsername()).cast(User.class).block();
|
||||
assertThat(foundUser.getPassword()).isNotEmpty();
|
||||
}
|
||||
|
||||
@@ -49,7 +49,6 @@ public class MockUserDetailsService implements UserDetailsService {
|
||||
if (this.users.get(username) == null) {
|
||||
throw new UsernameNotFoundException("User not found: " + username);
|
||||
}
|
||||
|
||||
return this.users.get(username);
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,6 @@ public class UserTests {
|
||||
@Test
|
||||
public void equalsReturnsTrueIfUsernamesAreTheSame() {
|
||||
User user1 = new User("rod", "koala", true, true, true, true, ROLE_12);
|
||||
|
||||
assertThat(user1).isNotNull();
|
||||
assertThat(user1).isNotEqualTo("A STRING");
|
||||
assertThat(user1).isEqualTo(user1);
|
||||
@@ -56,7 +55,6 @@ public class UserTests {
|
||||
User user1 = new User("rod", "koala", true, true, true, true, ROLE_12);
|
||||
Set<UserDetails> users = new HashSet<>();
|
||||
users.add(user1);
|
||||
|
||||
assertThat(users).contains(new User("rod", "koala", true, true, true, true, ROLE_12));
|
||||
assertThat(users).contains(new User("rod", "anotherpass", false, false, false, false,
|
||||
AuthorityUtils.createAuthorityList("ROLE_X")));
|
||||
@@ -66,7 +64,6 @@ public class UserTests {
|
||||
@Test
|
||||
public void testNoArgConstructorDoesntExist() {
|
||||
Class<User> clazz = User.class;
|
||||
|
||||
try {
|
||||
clazz.getDeclaredConstructor((Class[]) null);
|
||||
fail("Should have thrown NoSuchMethodException");
|
||||
@@ -83,14 +80,12 @@ public class UserTests {
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
new User("rod", null, true, true, true, true, ROLE_12);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_ONE");
|
||||
auths.add(null);
|
||||
@@ -145,9 +140,7 @@ public class UserTests {
|
||||
@Test
|
||||
public void withUserDetailsWhenAllEnabled() {
|
||||
User expected = new User("rob", "pass", true, true, true, true, ROLE_12);
|
||||
|
||||
UserDetails actual = User.withUserDetails(expected).build();
|
||||
|
||||
assertThat(actual.getUsername()).isEqualTo(expected.getUsername());
|
||||
assertThat(actual.getPassword()).isEqualTo(expected.getPassword());
|
||||
assertThat(actual.getAuthorities()).isEqualTo(expected.getAuthorities());
|
||||
@@ -160,9 +153,7 @@ public class UserTests {
|
||||
@Test
|
||||
public void withUserDetailsWhenAllDisabled() {
|
||||
User expected = new User("rob", "pass", false, false, false, false, ROLE_12);
|
||||
|
||||
UserDetails actual = User.withUserDetails(expected).build();
|
||||
|
||||
assertThat(actual.getUsername()).isEqualTo(expected.getUsername());
|
||||
assertThat(actual.getPassword()).isEqualTo(expected.getPassword());
|
||||
assertThat(actual.getAuthorities()).isEqualTo(expected.getAuthorities());
|
||||
@@ -175,10 +166,8 @@ public class UserTests {
|
||||
@Test
|
||||
public void withUserWhenDetailsPasswordEncoderThenEncodes() {
|
||||
UserDetails userDetails = User.withUsername("user").password("password").roles("USER").build();
|
||||
|
||||
UserDetails withEncodedPassword = User.withUserDetails(userDetails).passwordEncoder((p) -> p + "encoded")
|
||||
.build();
|
||||
|
||||
assertThat(withEncodedPassword.getPassword()).isEqualTo("passwordencoded");
|
||||
}
|
||||
|
||||
@@ -186,7 +175,6 @@ public class UserTests {
|
||||
public void withUsernameWhenPasswordEncoderAndPasswordThenEncodes() {
|
||||
UserDetails withEncodedPassword = User.withUsername("user").password("password")
|
||||
.passwordEncoder((p) -> p + "encoded").roles("USER").build();
|
||||
|
||||
assertThat(withEncodedPassword.getPassword()).isEqualTo("passwordencoded");
|
||||
}
|
||||
|
||||
@@ -199,7 +187,6 @@ public class UserTests {
|
||||
.roles("USER")
|
||||
.build();
|
||||
// @formatter:on
|
||||
|
||||
assertThat(withEncodedPassword.getPassword()).isEqualTo("passwordencoded");
|
||||
}
|
||||
|
||||
@@ -214,7 +201,6 @@ public class UserTests {
|
||||
.roles("USER")
|
||||
.build();
|
||||
// @formatter:on
|
||||
|
||||
assertThat(withEncodedPassword.getPassword()).isEqualTo("passwordencoded");
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,6 @@ public class EhCacheBasedUserCacheTests {
|
||||
private Ehcache getCache() {
|
||||
Ehcache cache = cacheManager.getCache("ehcacheusercachetests");
|
||||
cache.removeAll();
|
||||
|
||||
return cache;
|
||||
}
|
||||
|
||||
@@ -67,15 +66,12 @@ public class EhCacheBasedUserCacheTests {
|
||||
EhCacheBasedUserCache cache = new EhCacheBasedUserCache();
|
||||
cache.setCache(getCache());
|
||||
cache.afterPropertiesSet();
|
||||
|
||||
// Check it gets stored in the cache
|
||||
cache.putUserInCache(getUser());
|
||||
assertThat(getUser().getPassword()).isEqualTo(cache.getUserFromCache(getUser().getUsername()).getPassword());
|
||||
|
||||
// Check it gets removed from the cache
|
||||
cache.removeUserFromCache(getUser());
|
||||
assertThat(cache.getUserFromCache(getUser().getUsername())).isNull();
|
||||
|
||||
// Check it doesn't return values for null or unknown users
|
||||
assertThat(cache.getUserFromCache(null)).isNull();
|
||||
assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull();
|
||||
@@ -84,10 +80,8 @@ public class EhCacheBasedUserCacheTests {
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void startupDetectsMissingCache() throws Exception {
|
||||
EhCacheBasedUserCache cache = new EhCacheBasedUserCache();
|
||||
|
||||
cache.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
|
||||
Ehcache myCache = getCache();
|
||||
cache.setCache(myCache);
|
||||
assertThat(cache.getCache()).isEqualTo(myCache);
|
||||
|
||||
@@ -64,15 +64,12 @@ public class SpringCacheBasedUserCacheTests {
|
||||
@Test
|
||||
public void cacheOperationsAreSuccessful() throws Exception {
|
||||
SpringCacheBasedUserCache cache = new SpringCacheBasedUserCache(getCache());
|
||||
|
||||
// Check it gets stored in the cache
|
||||
cache.putUserInCache(getUser());
|
||||
assertThat(getUser().getPassword()).isEqualTo(cache.getUserFromCache(getUser().getUsername()).getPassword());
|
||||
|
||||
// Check it gets removed from the cache
|
||||
cache.removeUserFromCache(getUser());
|
||||
assertThat(cache.getUserFromCache(getUser().getUsername())).isNull();
|
||||
|
||||
// Check it doesn't return values for null or unknown users
|
||||
assertThat(cache.getUserFromCache(null)).isNull();
|
||||
assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull();
|
||||
|
||||
@@ -43,7 +43,6 @@ public class JdbcDaoImplTests {
|
||||
JdbcDaoImpl dao = new JdbcDaoImpl();
|
||||
dao.setDataSource(PopulatedDatabase.getDataSource());
|
||||
dao.afterPropertiesSet();
|
||||
|
||||
return dao;
|
||||
}
|
||||
|
||||
@@ -52,7 +51,6 @@ public class JdbcDaoImplTests {
|
||||
dao.setDataSource(PopulatedDatabase.getDataSource());
|
||||
dao.setRolePrefix("ARBITRARY_PREFIX_");
|
||||
dao.afterPropertiesSet();
|
||||
|
||||
return dao;
|
||||
}
|
||||
|
||||
@@ -63,7 +61,6 @@ public class JdbcDaoImplTests {
|
||||
assertThat(user.getUsername()).isEqualTo("rod");
|
||||
assertThat(user.getPassword()).isEqualTo("koala");
|
||||
assertThat(user.isEnabled()).isTrue();
|
||||
|
||||
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains("ROLE_TELLER");
|
||||
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains("ROLE_SUPERVISOR");
|
||||
}
|
||||
@@ -88,7 +85,6 @@ public class JdbcDaoImplTests {
|
||||
JdbcDaoImpl dao = new JdbcDaoImpl();
|
||||
dao.setAuthoritiesByUsernameQuery("SELECT * FROM FOO");
|
||||
assertThat(dao.getAuthoritiesByUsernameQuery()).isEqualTo("SELECT * FROM FOO");
|
||||
|
||||
dao.setUsersByUsernameQuery("SELECT USERS FROM FOO");
|
||||
assertThat(dao.getUsersByUsernameQuery()).isEqualTo("SELECT USERS FROM FOO");
|
||||
}
|
||||
@@ -96,7 +92,6 @@ public class JdbcDaoImplTests {
|
||||
@Test
|
||||
public void testLookupFailsIfUserHasNoGrantedAuthorities() throws Exception {
|
||||
JdbcDaoImpl dao = makePopulatedJdbcDao();
|
||||
|
||||
try {
|
||||
dao.loadUserByUsername("cooper");
|
||||
fail("Should have thrown UsernameNotFoundException");
|
||||
@@ -108,13 +103,11 @@ public class JdbcDaoImplTests {
|
||||
@Test
|
||||
public void testLookupFailsWithWrongUsername() throws Exception {
|
||||
JdbcDaoImpl dao = makePopulatedJdbcDao();
|
||||
|
||||
try {
|
||||
dao.loadUserByUsername("UNKNOWN_USER");
|
||||
fail("Should have thrown UsernameNotFoundException");
|
||||
}
|
||||
catch (UsernameNotFoundException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,11 +122,9 @@ public class JdbcDaoImplTests {
|
||||
public void testRolePrefixWorks() throws Exception {
|
||||
JdbcDaoImpl dao = makePopulatedJdbcDaoWithRolePrefix();
|
||||
assertThat(dao.getRolePrefix()).isEqualTo("ARBITRARY_PREFIX_");
|
||||
|
||||
UserDetails user = dao.loadUserByUsername("rod");
|
||||
assertThat(user.getUsername()).isEqualTo("rod");
|
||||
assertThat(user.getAuthorities()).hasSize(2);
|
||||
|
||||
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains("ARBITRARY_PREFIX_ROLE_TELLER");
|
||||
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()))
|
||||
.contains("ARBITRARY_PREFIX_ROLE_SUPERVISOR");
|
||||
@@ -144,7 +135,6 @@ public class JdbcDaoImplTests {
|
||||
JdbcDaoImpl dao = makePopulatedJdbcDao();
|
||||
dao.setEnableAuthorities(false);
|
||||
dao.setEnableGroups(true);
|
||||
|
||||
UserDetails jerry = dao.loadUserByUsername("jerry");
|
||||
assertThat(jerry.getAuthorities()).hasSize(3);
|
||||
}
|
||||
@@ -162,34 +152,29 @@ public class JdbcDaoImplTests {
|
||||
@Test
|
||||
public void testStartupFailsIfDataSourceNotSet() {
|
||||
JdbcDaoImpl dao = new JdbcDaoImpl();
|
||||
|
||||
try {
|
||||
dao.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartupFailsIfUserMapSetToNull() {
|
||||
JdbcDaoImpl dao = new JdbcDaoImpl();
|
||||
|
||||
try {
|
||||
dao.setDataSource(null);
|
||||
dao.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setMessageSourceWhenNullThenThrowsException() {
|
||||
JdbcDaoImpl dao = new JdbcDaoImpl();
|
||||
|
||||
dao.setMessageSource(null);
|
||||
}
|
||||
|
||||
@@ -199,9 +184,7 @@ public class JdbcDaoImplTests {
|
||||
JdbcDaoImpl dao = new JdbcDaoImpl();
|
||||
dao.setMessageSource(source);
|
||||
String code = "code";
|
||||
|
||||
dao.getMessages().getMessage(code);
|
||||
|
||||
verify(source).getMessage(eq(code), any(), any());
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,6 @@ public class UserAttributeEditorTests {
|
||||
public void testCorrectOperationWithTrailingSpaces() {
|
||||
UserAttributeEditor editor = new UserAttributeEditor();
|
||||
editor.setAsText("password ,ROLE_ONE,ROLE_TWO ");
|
||||
|
||||
UserAttribute user = (UserAttribute) editor.getValue();
|
||||
assertThat(user.getPassword()).isEqualTo("password");
|
||||
assertThat(user.getAuthorities()).hasSize(2);
|
||||
@@ -43,7 +42,6 @@ public class UserAttributeEditorTests {
|
||||
public void testCorrectOperationWithoutEnabledDisabledKeyword() {
|
||||
UserAttributeEditor editor = new UserAttributeEditor();
|
||||
editor.setAsText("password,ROLE_ONE,ROLE_TWO");
|
||||
|
||||
UserAttribute user = (UserAttribute) editor.getValue();
|
||||
assertThat(user.isValid()).isTrue();
|
||||
assertThat(user.isEnabled()).isTrue(); // default
|
||||
@@ -57,7 +55,6 @@ public class UserAttributeEditorTests {
|
||||
public void testDisabledKeyword() {
|
||||
UserAttributeEditor editor = new UserAttributeEditor();
|
||||
editor.setAsText("password,disabled,ROLE_ONE,ROLE_TWO");
|
||||
|
||||
UserAttribute user = (UserAttribute) editor.getValue();
|
||||
assertThat(user.isValid()).isTrue();
|
||||
assertThat(!user.isEnabled()).isTrue();
|
||||
@@ -71,7 +68,6 @@ public class UserAttributeEditorTests {
|
||||
public void testEmptyStringReturnsNull() {
|
||||
UserAttributeEditor editor = new UserAttributeEditor();
|
||||
editor.setAsText("");
|
||||
|
||||
UserAttribute user = (UserAttribute) editor.getValue();
|
||||
assertThat(user == null).isTrue();
|
||||
}
|
||||
@@ -80,7 +76,6 @@ public class UserAttributeEditorTests {
|
||||
public void testEnabledKeyword() {
|
||||
UserAttributeEditor editor = new UserAttributeEditor();
|
||||
editor.setAsText("password,ROLE_ONE,enabled,ROLE_TWO");
|
||||
|
||||
UserAttribute user = (UserAttribute) editor.getValue();
|
||||
assertThat(user.isValid()).isTrue();
|
||||
assertThat(user.isEnabled()).isTrue();
|
||||
@@ -94,7 +89,6 @@ public class UserAttributeEditorTests {
|
||||
public void testMalformedStringReturnsNull() {
|
||||
UserAttributeEditor editor = new UserAttributeEditor();
|
||||
editor.setAsText("MALFORMED_STRING");
|
||||
|
||||
UserAttribute user = (UserAttribute) editor.getValue();
|
||||
assertThat(user == null).isTrue();
|
||||
}
|
||||
@@ -103,7 +97,6 @@ public class UserAttributeEditorTests {
|
||||
public void testNoPasswordOrRolesReturnsNull() {
|
||||
UserAttributeEditor editor = new UserAttributeEditor();
|
||||
editor.setAsText("disabled");
|
||||
|
||||
UserAttribute user = (UserAttribute) editor.getValue();
|
||||
assertThat(user == null).isTrue();
|
||||
}
|
||||
@@ -112,7 +105,6 @@ public class UserAttributeEditorTests {
|
||||
public void testNoRolesReturnsNull() {
|
||||
UserAttributeEditor editor = new UserAttributeEditor();
|
||||
editor.setAsText("password,enabled");
|
||||
|
||||
UserAttribute user = (UserAttribute) editor.getValue();
|
||||
assertThat(user == null).isTrue();
|
||||
}
|
||||
@@ -121,7 +113,6 @@ public class UserAttributeEditorTests {
|
||||
public void testNullReturnsNull() {
|
||||
UserAttributeEditor editor = new UserAttributeEditor();
|
||||
editor.setAsText(null);
|
||||
|
||||
UserAttribute user = (UserAttribute) editor.getValue();
|
||||
assertThat(user == null).isTrue();
|
||||
}
|
||||
|
||||
@@ -48,7 +48,6 @@ public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
|
||||
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
|
||||
+ "}";
|
||||
// @formatter:on
|
||||
|
||||
@Test
|
||||
public void serializeAnonymousAuthenticationTokenTest() throws JsonProcessingException, JSONException {
|
||||
User user = createDefaultUser();
|
||||
|
||||
@@ -41,7 +41,6 @@ public class BadCredentialsExceptionMixinTests extends AbstractMixinTests {
|
||||
+ "\"suppressed\": [\"[Ljava.lang.Throwable;\",[]]"
|
||||
+ "}";
|
||||
// @formatter:on
|
||||
|
||||
@Test
|
||||
public void serializeBadCredentialsExceptionMixinTest() throws JsonProcessingException, JSONException {
|
||||
BadCredentialsException exception = new BadCredentialsException("message");
|
||||
|
||||
@@ -48,7 +48,6 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
|
||||
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
|
||||
+ "}";
|
||||
// @formatter:on
|
||||
|
||||
// @formatter:off
|
||||
private static final String REMEMBERME_AUTH_STRINGPRINCIPAL_JSON = "{"
|
||||
+ "\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\","
|
||||
@@ -59,7 +58,6 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
|
||||
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
|
||||
+ "}";
|
||||
// @formatter:on
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testWithNullPrincipal() {
|
||||
new RememberMeAuthenticationToken("key", null, Collections.<GrantedAuthority>emptyList());
|
||||
|
||||
@@ -44,7 +44,6 @@ public class SecurityContextMixinTests extends AbstractMixinTests {
|
||||
+ "\"authentication\": " + UsernamePasswordAuthenticationTokenMixinTests.AUTHENTICATED_STRINGPRINCIPAL_JSON
|
||||
+ "}";
|
||||
// @formatter:on
|
||||
|
||||
@Test
|
||||
public void securityContextSerializeTest() throws JsonProcessingException, JSONException {
|
||||
SecurityContext context = new SecurityContextImpl();
|
||||
|
||||
@@ -58,7 +58,6 @@ public class SecurityJackson2ModulesTests {
|
||||
public void readValueWhenExplicitDefaultTypingAfterSecuritySetupThenReadsAsSpecificType() throws Exception {
|
||||
this.mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
|
||||
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}";
|
||||
|
||||
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlisted.class);
|
||||
}
|
||||
|
||||
@@ -68,14 +67,12 @@ public class SecurityJackson2ModulesTests {
|
||||
this.mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
|
||||
SecurityJackson2Modules.enableDefaultTyping(this.mapper);
|
||||
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}";
|
||||
|
||||
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlisted.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readValueWhenAnnotatedThenReadsAsSpecificType() throws Exception {
|
||||
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlistedButAnnotated\",\"property\":\"bar\"}";
|
||||
|
||||
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlistedButAnnotated.class);
|
||||
}
|
||||
|
||||
@@ -83,7 +80,6 @@ public class SecurityJackson2ModulesTests {
|
||||
public void readValueWhenMixinProvidedThenReadsAsSpecificType() throws Exception {
|
||||
this.mapper.addMixIn(NotAllowlisted.class, NotAllowlistedMixin.class);
|
||||
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}";
|
||||
|
||||
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlisted.class);
|
||||
}
|
||||
|
||||
@@ -91,7 +87,6 @@ public class SecurityJackson2ModulesTests {
|
||||
public void readValueWhenHashMapThenReadsAsSpecificType() throws Exception {
|
||||
this.mapper.addMixIn(NotAllowlisted.class, NotAllowlistedMixin.class);
|
||||
String content = "{\"@class\":\"java.util.HashMap\"}";
|
||||
|
||||
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(HashMap.class);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,18 +36,12 @@ public class SimpleGrantedAuthorityMixinTests extends AbstractMixinTests {
|
||||
|
||||
// @formatter:off
|
||||
public static final String AUTHORITY_JSON = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"authority\": \"ROLE_USER\"}";
|
||||
|
||||
public static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", [" + AUTHORITY_JSON + "]]";
|
||||
|
||||
public static final String AUTHORITIES_SET_JSON = "[\"java.util.Collections$UnmodifiableSet\", [" + AUTHORITY_JSON + "]]";
|
||||
|
||||
public static final String NO_AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", []]";
|
||||
|
||||
public static final String EMPTY_AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$EmptyList\", []]";
|
||||
|
||||
public static final String NO_AUTHORITIES_SET_JSON = "[\"java.util.Collections$UnmodifiableSet\", []]";
|
||||
// @formatter:on
|
||||
|
||||
@Test
|
||||
public void serializeSimpleGrantedAuthorityTest() throws JsonProcessingException, JSONException {
|
||||
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
|
||||
|
||||
@@ -53,7 +53,6 @@ public class UserDeserializerTests extends AbstractMixinTests {
|
||||
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON
|
||||
+ "}";
|
||||
// @formatter:on
|
||||
|
||||
@Test
|
||||
public void serializeUserTest() throws JsonProcessingException, JSONException {
|
||||
User user = createDefaultUser();
|
||||
@@ -72,14 +71,12 @@ public class UserDeserializerTests extends AbstractMixinTests {
|
||||
public void deserializeUserWithNullPasswordEmptyAuthorityTest() throws IOException {
|
||||
String userJsonWithoutPasswordString = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON,
|
||||
"[]");
|
||||
|
||||
this.mapper.readValue(userJsonWithoutPasswordString, User.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeUserWithNullPasswordNoAuthorityTest() throws Exception {
|
||||
String userJsonWithoutPasswordString = removeNode(userWithNoAuthoritiesJson(), this.mapper, "password");
|
||||
|
||||
User user = this.mapper.readValue(userJsonWithoutPasswordString, User.class);
|
||||
assertThat(user).isNotNull();
|
||||
assertThat(user.getUsername()).isEqualTo("admin");
|
||||
@@ -107,7 +104,6 @@ public class UserDeserializerTests extends AbstractMixinTests {
|
||||
private String removeNode(String json, ObjectMapper mapper, String toRemove) throws Exception {
|
||||
ObjectNode node = mapper.getFactory().createParser(json).readValueAsTree();
|
||||
node.remove(toRemove);
|
||||
|
||||
String result = mapper.writeValueAsString(node);
|
||||
JSONAssert.assertNotEquals(json, result, false);
|
||||
return result;
|
||||
|
||||
@@ -44,7 +44,6 @@ public class InMemoryUserDetailsManagerTests {
|
||||
@Test
|
||||
public void changePasswordWhenUsernameIsNotInLowercase() {
|
||||
UserDetails userNotLowerCase = User.withUserDetails(PasswordEncodedUser.user()).username("User").build();
|
||||
|
||||
String newPassword = "newPassword";
|
||||
this.manager.updatePassword(userNotLowerCase, newPassword);
|
||||
assertThat(this.manager.loadUserByUsername(userNotLowerCase.getUsername()).getPassword())
|
||||
|
||||
@@ -97,7 +97,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
this.manager.setChangePasswordSql(JdbcUserDetailsManager.DEF_CHANGE_PASSWORD_SQL);
|
||||
this.manager.initDao();
|
||||
this.template = this.manager.getJdbcTemplate();
|
||||
|
||||
this.template.execute("create table users(username varchar(20) not null primary key,"
|
||||
+ "password varchar(20) not null, enabled boolean not null)");
|
||||
this.template
|
||||
@@ -121,7 +120,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
this.template.execute("alter table users add column acc_locked boolean default false not null");
|
||||
this.template.execute("alter table users add column acc_expired boolean default false not null");
|
||||
this.template.execute("alter table users add column creds_expired boolean default false not null");
|
||||
|
||||
this.manager.setUsersByUsernameQuery(
|
||||
"select username,password,enabled, acc_locked, acc_expired, creds_expired from users where username = ?");
|
||||
this.manager.setCreateUserSql(
|
||||
@@ -133,22 +131,17 @@ public class JdbcUserDetailsManagerTests {
|
||||
@Test
|
||||
public void createUserInsertsCorrectData() {
|
||||
this.manager.createUser(joe);
|
||||
|
||||
UserDetails joe2 = this.manager.loadUserByUsername("joe");
|
||||
|
||||
assertThat(joe2).isEqualTo(joe);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createUserInsertsCorrectDataWithLocking() {
|
||||
setUpAccLockingColumns();
|
||||
|
||||
UserDetails user = new User("joe", "pass", true, false, true, false,
|
||||
AuthorityUtils.createAuthorityList("A", "B"));
|
||||
this.manager.createUser(user);
|
||||
|
||||
UserDetails user2 = this.manager.loadUserByUsername(user.getUsername());
|
||||
|
||||
assertThat(user2).isEqualToComparingFieldByField(user);
|
||||
}
|
||||
|
||||
@@ -156,7 +149,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
public void deleteUserRemovesUserDataAndAuthoritiesAndClearsCache() {
|
||||
insertJoe();
|
||||
this.manager.deleteUser("joe");
|
||||
|
||||
assertThat(this.template.queryForList(SELECT_JOE_SQL)).isEmpty();
|
||||
assertThat(this.template.queryForList(SELECT_JOE_AUTHORITIES_SQL)).isEmpty();
|
||||
assertThat(this.cache.getUserMap().containsKey("joe")).isFalse();
|
||||
@@ -167,11 +159,8 @@ public class JdbcUserDetailsManagerTests {
|
||||
insertJoe();
|
||||
User newJoe = new User("joe", "newpassword", false, true, true, true,
|
||||
AuthorityUtils.createAuthorityList(new String[] { "D", "F", "E" }));
|
||||
|
||||
this.manager.updateUser(newJoe);
|
||||
|
||||
UserDetails joe = this.manager.loadUserByUsername("joe");
|
||||
|
||||
assertThat(joe).isEqualTo(newJoe);
|
||||
assertThat(this.cache.getUserMap().containsKey("joe")).isFalse();
|
||||
}
|
||||
@@ -179,16 +168,11 @@ public class JdbcUserDetailsManagerTests {
|
||||
@Test
|
||||
public void updateUserChangesDataCorrectlyAndClearsCacheWithLocking() {
|
||||
setUpAccLockingColumns();
|
||||
|
||||
insertJoe();
|
||||
|
||||
User newJoe = new User("joe", "newpassword", false, false, false, true,
|
||||
AuthorityUtils.createAuthorityList("D", "F", "E"));
|
||||
|
||||
this.manager.updateUser(newJoe);
|
||||
|
||||
UserDetails joe = this.manager.loadUserByUsername(newJoe.getUsername());
|
||||
|
||||
assertThat(joe).isEqualToComparingFieldByField(newJoe);
|
||||
assertThat(this.cache.getUserMap().containsKey(newJoe.getUsername())).isFalse();
|
||||
}
|
||||
@@ -216,7 +200,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
authenticateJoe();
|
||||
this.manager.changePassword("wrongpassword", "newPassword");
|
||||
UserDetails newJoe = this.manager.loadUserByUsername("joe");
|
||||
|
||||
assertThat(newJoe.getPassword()).isEqualTo("newPassword");
|
||||
assertThat(this.cache.getUserMap().containsKey("joe")).isFalse();
|
||||
}
|
||||
@@ -227,11 +210,9 @@ public class JdbcUserDetailsManagerTests {
|
||||
Authentication currentAuth = authenticateJoe();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
given(am.authenticate(currentAuth)).willReturn(currentAuth);
|
||||
|
||||
this.manager.setAuthenticationManager(am);
|
||||
this.manager.changePassword("password", "newPassword");
|
||||
UserDetails newJoe = this.manager.loadUserByUsername("joe");
|
||||
|
||||
assertThat(newJoe.getPassword()).isEqualTo("newPassword");
|
||||
// The password in the context should also be altered
|
||||
Authentication newAuth = SecurityContextHolder.getContext().getAuthentication();
|
||||
@@ -247,16 +228,13 @@ public class JdbcUserDetailsManagerTests {
|
||||
authenticateJoe();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
|
||||
|
||||
this.manager.setAuthenticationManager(am);
|
||||
|
||||
try {
|
||||
this.manager.changePassword("password", "newPassword");
|
||||
fail("Expected BadCredentialsException");
|
||||
}
|
||||
catch (BadCredentialsException expected) {
|
||||
}
|
||||
|
||||
// Check password hasn't changed.
|
||||
UserDetails newJoe = this.manager.loadUserByUsername("joe");
|
||||
assertThat(newJoe.getPassword()).isEqualTo("password");
|
||||
@@ -268,7 +246,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
public void findAllGroupsReturnsExpectedGroupNames() {
|
||||
List<String> groups = this.manager.findAllGroups();
|
||||
assertThat(groups).hasSize(4);
|
||||
|
||||
Collections.sort(groups);
|
||||
assertThat(groups.get(0)).isEqualTo("GROUP_0");
|
||||
assertThat(groups.get(1)).isEqualTo("GROUP_1");
|
||||
@@ -289,10 +266,8 @@ public class JdbcUserDetailsManagerTests {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void createGroupInsertsCorrectData() {
|
||||
this.manager.createGroup("TEST_GROUP", AuthorityUtils.createAuthorityList("ROLE_X", "ROLE_Y"));
|
||||
|
||||
List roles = this.template.queryForList("select ga.authority from groups g, group_authorities ga "
|
||||
+ "where ga.group_id = g.id " + "and g.group_name = 'TEST_GROUP'");
|
||||
|
||||
assertThat(roles).hasSize(2);
|
||||
}
|
||||
|
||||
@@ -302,7 +277,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
this.manager.deleteGroup("GROUP_1");
|
||||
this.manager.deleteGroup("GROUP_2");
|
||||
this.manager.deleteGroup("GROUP_3");
|
||||
|
||||
assertThat(this.template.queryForList("select * from group_authorities")).isEmpty();
|
||||
assertThat(this.template.queryForList("select * from group_members")).isEmpty();
|
||||
assertThat(this.template.queryForList("select id from groups")).isEmpty();
|
||||
@@ -311,7 +285,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
@Test
|
||||
public void renameGroupIsSuccessful() {
|
||||
this.manager.renameGroup("GROUP_0", "GROUP_X");
|
||||
|
||||
assertThat(this.template.queryForObject("select id from groups where group_name = 'GROUP_X'", Integer.class))
|
||||
.isZero();
|
||||
}
|
||||
@@ -319,14 +292,12 @@ public class JdbcUserDetailsManagerTests {
|
||||
@Test
|
||||
public void addingGroupUserSetsCorrectData() {
|
||||
this.manager.addUserToGroup("tom", "GROUP_0");
|
||||
|
||||
assertThat(this.template.queryForList("select username from group_members where group_id = 0")).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removeUserFromGroupDeletesGroupMemberRow() {
|
||||
this.manager.removeUserFromGroup("jerry", "GROUP_1");
|
||||
|
||||
assertThat(this.template.queryForList("select group_id from group_members where username = 'jerry'"))
|
||||
.hasSize(1);
|
||||
}
|
||||
@@ -341,7 +312,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
public void addGroupAuthorityInsertsCorrectGroupAuthorityRow() {
|
||||
GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_X");
|
||||
this.manager.addGroupAuthority("GROUP_0", auth);
|
||||
|
||||
this.template.queryForObject(
|
||||
"select authority from group_authorities where authority = 'ROLE_X' and group_id = 0", String.class);
|
||||
}
|
||||
@@ -351,7 +321,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_A");
|
||||
this.manager.removeGroupAuthority("GROUP_0", auth);
|
||||
assertThat(this.template.queryForList("select authority from group_authorities where group_id = 0")).isEmpty();
|
||||
|
||||
this.manager.removeGroupAuthority("GROUP_2", auth);
|
||||
assertThat(this.template.queryForList("select authority from group_authorities where group_id = 2")).hasSize(2);
|
||||
}
|
||||
@@ -388,7 +357,6 @@ public class JdbcUserDetailsManagerTests {
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("joe", "password",
|
||||
joe.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
return auth;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,12 +28,10 @@ public class FieldUtilsTests {
|
||||
@Test
|
||||
public void gettingAndSettingProtectedFieldIsSuccessful() throws Exception {
|
||||
Object tc = new TestClass();
|
||||
|
||||
assertThat(FieldUtils.getProtectedFieldValue("protectedField", tc)).isEqualTo("x");
|
||||
assertThat(FieldUtils.getFieldValue(tc, "nested.protectedField")).isEqualTo("z");
|
||||
FieldUtils.setProtectedFieldValue("protectedField", tc, "y");
|
||||
assertThat(FieldUtils.getProtectedFieldValue("protectedField", tc)).isEqualTo("y");
|
||||
|
||||
try {
|
||||
FieldUtils.getProtectedFieldValue("nonExistentField", tc);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user