Reformat code using spring-javaformat

Run `./gradlew format` to reformat all java files.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-08-10 16:39:17 -05:00
committed by Rob Winch
parent 81d9c6cac5
commit b7fc18262d
2487 changed files with 41506 additions and 46548 deletions

View File

@@ -22,6 +22,7 @@ package org.springframework.security;
* @author Ben Alex
*/
public interface ITargetObject {
// ~ Methods
// ========================================================================================================
@@ -34,4 +35,5 @@ public interface ITargetObject {
String makeUpperCase(String input);
String publicMakeLowerCase(String input);
}

View File

@@ -34,6 +34,7 @@ package org.springframework.security;
* @author Ben Alex
*/
public class OtherTargetObject extends TargetObject implements ITargetObject {
// ~ Methods
// ========================================================================================================
@@ -48,4 +49,5 @@ public class OtherTargetObject extends TargetObject implements ITargetObject {
public String publicMakeLowerCase(String input) {
return super.publicMakeLowerCase(input);
}
}

View File

@@ -27,6 +27,7 @@ import javax.sql.DataSource;
* @author Ben Alex
*/
public class PopulatedDatabase {
// ~ Static fields/initializers
// =====================================================================================
@@ -53,11 +54,15 @@ public class PopulatedDatabase {
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("CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME))");
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(
"CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME))");
template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY)");
template.execute("CREATE TABLE ACL_OBJECT_IDENTITY(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,OBJECT_IDENTITY VARCHAR_IGNORECASE(250) NOT NULL,PARENT_OBJECT BIGINT,ACL_CLASS VARCHAR_IGNORECASE(250) NOT NULL,CONSTRAINT UNIQUE_OBJECT_IDENTITY UNIQUE(OBJECT_IDENTITY),CONSTRAINT SYS_FK_3 FOREIGN KEY(PARENT_OBJECT) REFERENCES ACL_OBJECT_IDENTITY(ID))");
template.execute("CREATE TABLE ACL_PERMISSION(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,ACL_OBJECT_IDENTITY BIGINT NOT NULL,RECIPIENT VARCHAR_IGNORECASE(100) NOT NULL,MASK INTEGER NOT NULL,CONSTRAINT UNIQUE_RECIPIENT UNIQUE(ACL_OBJECT_IDENTITY,RECIPIENT),CONSTRAINT SYS_FK_7 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID))");
template.execute(
"CREATE TABLE ACL_OBJECT_IDENTITY(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,OBJECT_IDENTITY VARCHAR_IGNORECASE(250) NOT NULL,PARENT_OBJECT BIGINT,ACL_CLASS VARCHAR_IGNORECASE(250) NOT NULL,CONSTRAINT UNIQUE_OBJECT_IDENTITY UNIQUE(OBJECT_IDENTITY),CONSTRAINT SYS_FK_3 FOREIGN KEY(PARENT_OBJECT) REFERENCES ACL_OBJECT_IDENTITY(ID))");
template.execute(
"CREATE TABLE ACL_PERMISSION(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,ACL_OBJECT_IDENTITY BIGINT NOT NULL,RECIPIENT VARCHAR_IGNORECASE(100) NOT NULL,MASK INTEGER NOT NULL,CONSTRAINT UNIQUE_RECIPIENT UNIQUE(ACL_OBJECT_IDENTITY,RECIPIENT),CONSTRAINT SYS_FK_7 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID))");
template.execute("SET IGNORECASE TRUE");
template.execute("INSERT INTO USERS VALUES('dianne','emu',TRUE)");
template.execute("INSERT INTO USERS VALUES('rod','koala',TRUE)");
@@ -69,15 +74,22 @@ public class PopulatedDatabase {
template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_TELLER')");
template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_TELLER')");
template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_TELLER')");
template.execute("INSERT INTO acl_object_identity VALUES (1, 'org.springframework.security.acl.DomainObject:1', null, 'org.springframework.security.acl.basic.SimpleAclEntry');");
template.execute("INSERT INTO acl_object_identity VALUES (2, 'org.springframework.security.acl.DomainObject:2', 1, 'org.springframework.security.acl.basic.SimpleAclEntry');");
template.execute("INSERT INTO acl_object_identity VALUES (3, 'org.springframework.security.acl.DomainObject:3', 1, 'org.springframework.security.acl.basic.SimpleAclEntry');");
template.execute("INSERT INTO acl_object_identity VALUES (4, 'org.springframework.security.acl.DomainObject:4', 1, 'org.springframework.security.acl.basic.SimpleAclEntry');");
template.execute("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');");
template.execute(
"INSERT INTO acl_object_identity VALUES (1, 'org.springframework.security.acl.DomainObject:1', null, 'org.springframework.security.acl.basic.SimpleAclEntry');");
template.execute(
"INSERT INTO acl_object_identity VALUES (2, 'org.springframework.security.acl.DomainObject:2', 1, 'org.springframework.security.acl.basic.SimpleAclEntry');");
template.execute(
"INSERT INTO acl_object_identity VALUES (3, 'org.springframework.security.acl.DomainObject:3', 1, 'org.springframework.security.acl.basic.SimpleAclEntry');");
template.execute(
"INSERT INTO acl_object_identity VALUES (4, 'org.springframework.security.acl.DomainObject:4', 1, 'org.springframework.security.acl.basic.SimpleAclEntry');");
template.execute(
"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');");
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);");
@@ -92,9 +104,12 @@ public class PopulatedDatabase {
public static void createGroupTables(JdbcTemplate template) {
// Group tables and data
template.execute("CREATE TABLE GROUPS(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 0) PRIMARY KEY, GROUP_NAME VARCHAR_IGNORECASE(50) NOT NULL)");
template.execute("CREATE TABLE GROUP_AUTHORITIES(GROUP_ID BIGINT NOT NULL, AUTHORITY VARCHAR(50) NOT NULL, CONSTRAINT FK_GROUP_AUTHORITIES_GROUP FOREIGN KEY(GROUP_ID) REFERENCES GROUPS(ID))");
template.execute("CREATE TABLE GROUP_MEMBERS(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 0) PRIMARY KEY, USERNAME VARCHAR(50) NOT NULL, GROUP_ID BIGINT NOT NULL, CONSTRAINT FK_GROUP_MEMBERS_GROUP FOREIGN KEY(GROUP_ID) REFERENCES GROUPS(ID))");
template.execute(
"CREATE TABLE GROUPS(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 0) PRIMARY KEY, GROUP_NAME VARCHAR_IGNORECASE(50) NOT NULL)");
template.execute(
"CREATE TABLE GROUP_AUTHORITIES(GROUP_ID BIGINT NOT NULL, AUTHORITY VARCHAR(50) NOT NULL, CONSTRAINT FK_GROUP_AUTHORITIES_GROUP FOREIGN KEY(GROUP_ID) REFERENCES GROUPS(ID))");
template.execute(
"CREATE TABLE GROUP_MEMBERS(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 0) PRIMARY KEY, USERNAME VARCHAR(50) NOT NULL, GROUP_ID BIGINT NOT NULL, CONSTRAINT FK_GROUP_MEMBERS_GROUP FOREIGN KEY(GROUP_ID) REFERENCES GROUPS(ID))");
}
public static void insertGroupData(JdbcTemplate template) {
@@ -122,4 +137,5 @@ public class PopulatedDatabase {
template.execute("INSERT INTO GROUP_MEMBERS VALUES (2, 'tom', 1)");
template.execute("INSERT INTO GROUP_MEMBERS VALUES (3, 'tom', 2)");
}
}

View File

@@ -25,6 +25,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
* @author Ben Alex
*/
public class TargetObject implements ITargetObject {
// ~ Methods
// ========================================================================================================
@@ -38,9 +39,7 @@ public class TargetObject implements ITargetObject {
/**
* Returns the lowercase string, followed by security environment information.
*
* @param input the message to make lowercase
*
* @return the lowercase message, a space, the <code>Authentication</code> class that
* was on the <code>SecurityContext</code> at the time of method invocation, and a
* boolean indicating if the <code>Authentication</code> object is authenticated or
@@ -53,16 +52,13 @@ public class TargetObject implements ITargetObject {
return input.toLowerCase() + " Authentication empty";
}
else {
return input.toLowerCase() + " " + auth.getClass().getName() + " "
+ auth.isAuthenticated();
return input.toLowerCase() + " " + auth.getClass().getName() + " " + auth.isAuthenticated();
}
}
/**
* Returns the uppercase string, followed by security environment information.
*
* @param input the message to make uppercase
*
* @return the uppercase message, a space, the <code>Authentication</code> class that
* was on the <code>SecurityContext</code> at the time of method invocation, and a
* boolean indicating if the <code>Authentication</code> object is authenticated or
@@ -71,16 +67,15 @@ public class TargetObject implements ITargetObject {
public String makeUpperCase(String input) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return input.toUpperCase() + " " + auth.getClass().getName() + " "
+ auth.isAuthenticated();
return input.toUpperCase() + " " + auth.getClass().getName() + " " + auth.isAuthenticated();
}
/**
* Delegates through to the {@link #makeLowerCase(String)} method.
*
* @param input the message to be made lower-case
*/
public String publicMakeLowerCase(String input) {
return this.makeLowerCase(input);
}
}

View File

@@ -26,6 +26,7 @@ import org.springframework.beans.factory.DisposableBean;
* @author Luke Taylor
*/
public class TestDataSource extends DriverManagerDataSource implements DisposableBean {
String name;
public TestDataSource(String databaseName) {
@@ -41,4 +42,5 @@ public class TestDataSource extends DriverManagerDataSource implements Disposabl
System.out.println("Shutting down database: " + name);
new JdbcTemplate(this).execute("SHUTDOWN");
}
}

View File

@@ -31,8 +31,7 @@ public class AuthenticationCredentialsNotFoundEventTests {
@Test(expected = IllegalArgumentException.class)
public void testRejectsNulls() {
new AuthenticationCredentialsNotFoundEvent(null,
SecurityConfig.createList("TEST"),
new AuthenticationCredentialsNotFoundEvent(null, SecurityConfig.createList("TEST"),
new AuthenticationCredentialsNotFoundException("test"));
}
@@ -44,7 +43,8 @@ public class AuthenticationCredentialsNotFoundEventTests {
@Test(expected = IllegalArgumentException.class)
public void testRejectsNulls3() {
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(),
SecurityConfig.createList("TEST"), null);
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"),
null);
}
}

View File

@@ -31,11 +31,12 @@ import java.util.*;
* @author Ben Alex
*/
public class AuthorizationFailureEventTests {
private final UsernamePasswordAuthenticationToken foo = new UsernamePasswordAuthenticationToken(
"foo", "bar");
private final UsernamePasswordAuthenticationToken foo = new UsernamePasswordAuthenticationToken("foo", "bar");
private List<ConfigAttribute> attributes = SecurityConfig.createList("TEST");
private AccessDeniedException exception = new AuthorizationServiceException("error",
new Throwable());
private AccessDeniedException exception = new AuthorizationServiceException("error", new Throwable());
@Test(expected = IllegalArgumentException.class)
public void rejectsNullSecureObject() {
@@ -49,8 +50,7 @@ public class AuthorizationFailureEventTests {
@Test(expected = IllegalArgumentException.class)
public void rejectsNullAuthentication() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), attributes, null,
exception);
new AuthorizationFailureEvent(new SimpleMethodInvocation(), attributes, null, exception);
}
@Test(expected = IllegalArgumentException.class)
@@ -60,10 +60,10 @@ public class AuthorizationFailureEventTests {
@Test
public void gettersReturnCtorSuppliedData() {
AuthorizationFailureEvent event = new AuthorizationFailureEvent(new Object(),
attributes, foo, exception);
AuthorizationFailureEvent event = new AuthorizationFailureEvent(new Object(), attributes, foo, exception);
assertThat(event.getConfigAttributes()).isSameAs(attributes);
assertThat(event.getAccessDeniedException()).isSameAs(exception);
assertThat(event.getAuthentication()).isSameAs(foo);
}
}

View File

@@ -38,13 +38,12 @@ public class AuthorizedEventTests {
@Test(expected = IllegalArgumentException.class)
public void testRejectsNulls2() {
new AuthorizedEvent(new SimpleMethodInvocation(), null,
new UsernamePasswordAuthenticationToken("foo", "bar"));
new AuthorizedEvent(new SimpleMethodInvocation(), null, new UsernamePasswordAuthenticationToken("foo", "bar"));
}
@Test(expected = IllegalArgumentException.class)
public void testRejectsNulls3() {
new AuthorizedEvent(new SimpleMethodInvocation(),
SecurityConfig.createList("TEST"), null);
new AuthorizedEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"), null);
}
}

View File

@@ -16,7 +16,6 @@
package org.springframework.security.access;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
@@ -90,6 +89,7 @@ public class SecurityConfigTests {
// ==================================================================================================
private class MockConfigAttribute implements ConfigAttribute {
private String attribute;
MockConfigAttribute(String configuration) {
@@ -99,5 +99,7 @@ public class SecurityConfigTests {
public String getAttribute() {
return this.attribute;
}
}
}

View File

@@ -29,6 +29,7 @@ import org.springframework.security.access.prepost.PreAuthorize;
@Secured({ "ROLE_USER" })
@PermitAll
public interface BusinessService extends Serializable {
// ~ Methods
// ========================================================================================================

View File

@@ -19,7 +19,6 @@ import java.util.ArrayList;
import java.util.List;
/**
*
* @author Joe Scalise
*/
public class BusinessServiceImpl<E extends Entity> implements BusinessService {
@@ -67,4 +66,5 @@ public class BusinessServiceImpl<E extends Entity> implements BusinessService {
public void rolesAllowedUser() {
}
}

View File

@@ -22,6 +22,8 @@ package org.springframework.security.access.annotation;
*
*/
public class Entity {
public Entity(String someParameter) {
}
}

View File

@@ -67,4 +67,5 @@ public class ExpressionProtectedBusinessServiceImpl implements BusinessService {
public void rolesAllowedUser() {
}
}

View File

@@ -22,7 +22,6 @@ import javax.annotation.security.RolesAllowed;
import javax.annotation.security.PermitAll;
/**
*
* @author Luke Taylor
*/
@PermitAll
@@ -68,4 +67,5 @@ public class Jsr250BusinessServiceImpl implements BusinessService {
public void rolesAllowedUser() {
}
}

View File

@@ -49,8 +49,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
}
private ConfigAttribute[] findAttributes(String methodName) throws Exception {
return this.mds.findAttributes(this.a.getClass().getMethod(methodName), null)
.toArray(new ConfigAttribute[0]);
return this.mds.findAttributes(this.a.getClass().getMethod(methodName), null).toArray(new ConfigAttribute[0]);
}
@Test
@@ -64,8 +63,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
public void permitAllMethodHasPermitAllAttribute() throws Exception {
ConfigAttribute[] accessAttributes = findAttributes("permitAllMethod");
assertThat(accessAttributes).hasSize(1);
assertThat(accessAttributes[0].toString())
.isEqualTo("javax.annotation.security.PermitAll");
assertThat(accessAttributes[0].toString()).isEqualTo("javax.annotation.security.PermitAll");
}
@Test
@@ -77,15 +75,15 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@Test
public void classRoleIsAppliedToNoRoleMethod() throws Exception {
Collection<ConfigAttribute> accessAttributes = this.mds.findAttributes(
this.userAllowed.getClass().getMethod("noRoleMethod"), null);
Collection<ConfigAttribute> accessAttributes = this.mds
.findAttributes(this.userAllowed.getClass().getMethod("noRoleMethod"), null);
assertThat(accessAttributes).isNull();
}
@Test
public void methodRoleOverridesClassRole() throws Exception {
Collection<ConfigAttribute> accessAttributes = this.mds.findAttributes(
this.userAllowed.getClass().getMethod("adminMethod"), null);
Collection<ConfigAttribute> accessAttributes = this.mds
.findAttributes(this.userAllowed.getClass().getMethod("adminMethod"), null);
assertThat(accessAttributes).hasSize(1);
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_ADMIN");
}
@@ -130,26 +128,21 @@ public class Jsr250MethodSecurityMetadataSourceTests {
* 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,
* even if it is not hidden or overridden by the class in question.
*
* @throws Exception
*/
@Test
public void classLevelAnnotationsOnlyAffectTheClassTheyAnnotateAndTheirMembers()
throws Exception {
public void classLevelAnnotationsOnlyAffectTheClassTheyAnnotateAndTheirMembers() throws Exception {
Child target = new Child();
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(),
"notOverriden");
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "notOverriden");
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
assertThat(accessAttributes).isNull();
}
@Test
public void classLevelAnnotationsOnlyAffectTheClassTheyAnnotateAndTheirMembersOverriden()
throws Exception {
public void classLevelAnnotationsOnlyAffectTheClassTheyAnnotateAndTheirMembersOverriden() throws Exception {
Child target = new Child();
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(),
"overriden");
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "overriden");
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
assertThat(accessAttributes).hasSize(1);
@@ -159,8 +152,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@Test
public void classLevelAnnotationsImpactMemberLevel() throws Exception {
Child target = new Child();
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(),
"defaults");
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "defaults");
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
assertThat(accessAttributes).hasSize(1);
@@ -168,11 +160,9 @@ public class Jsr250MethodSecurityMetadataSourceTests {
}
@Test
public void classLevelAnnotationsIgnoredByExplicitMemberAnnotation()
throws Exception {
public void classLevelAnnotationsIgnoredByExplicitMemberAnnotation() throws Exception {
Child target = new Child();
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(),
"explicitMethod");
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "explicitMethod");
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
assertThat(accessAttributes).hasSize(1);
@@ -182,14 +172,12 @@ public class Jsr250MethodSecurityMetadataSourceTests {
/**
* The interfaces implemented by a class never contribute annotations to the class
* itself or any of its members.
*
* @throws Exception
*/
@Test
public void interfacesNeverContributeAnnotationsMethodLevel() throws Exception {
Parent target = new Parent();
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(),
"interfaceMethod");
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "interfaceMethod");
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
assertThat(accessAttributes).isEmpty();
@@ -198,8 +186,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@Test
public void interfacesNeverContributeAnnotationsClassLevel() throws Exception {
Parent target = new Parent();
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(),
"notOverriden");
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "notOverriden");
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
assertThat(accessAttributes).isEmpty();
@@ -208,8 +195,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@Test
public void annotationsOnOverriddenMemberIgnored() throws Exception {
Child target = new Child();
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(),
"overridenIgnored");
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "overridenIgnored");
Collection<ConfigAttribute> accessAttributes = this.mds.getAttributes(mi);
assertThat(accessAttributes).hasSize(1);
@@ -235,6 +221,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@PermitAll
public void permitAllMethod() {
}
}
@RolesAllowed("USER")
@@ -246,6 +233,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@RolesAllowed("ADMIN")
public void adminMethod() {
}
}
// JSR-250 Spec
@@ -255,6 +243,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@RolesAllowed("INTERFACEMETHOD")
void interfaceMethod();
}
static class Parent implements IParent {
@@ -271,6 +260,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@RolesAllowed("OVERRIDENIGNORED")
public void overridenIgnored() {
}
}
@RolesAllowed("DERIVED")
@@ -290,5 +280,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@RolesAllowed("EXPLICIT")
public void explicitMethod() {
}
}
}

View File

@@ -27,7 +27,6 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.TestingAuthenticationToken;
/**
*
* @author Luke Taylor
*/
public class Jsr250VoterTests {
@@ -42,19 +41,18 @@ public class Jsr250VoterTests {
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", "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", "NONE"), new Object(), attrs))
.isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
assertThat(voter.vote(
new TestingAuthenticationToken("user", "pwd", "A"), new Object(),
assertThat(voter.vote(new TestingAuthenticationToken("user", "pwd", "A"), new Object(),
SecurityConfig.createList("A", "B", "C"))).isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
}
}

View File

@@ -47,6 +47,7 @@ import org.springframework.security.core.GrantedAuthority;
* @author Luke Taylor
*/
public class SecuredAnnotationSecurityMetadataSourceTests {
// ~ Instance fields
// ================================================================================================
@@ -60,15 +61,13 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
Method method = null;
try {
method = DepartmentServiceImpl.class.getMethod("someUserMethod3",
new Class[] { Department.class });
method = DepartmentServiceImpl.class.getMethod("someUserMethod3", new Class[] { Department.class });
}
catch (NoSuchMethodException unexpected) {
fail("Should be a superMethod called 'someUserMethod3' on class!");
}
Collection<ConfigAttribute> attrs = mds.findAttributes(method,
DepartmentServiceImpl.class);
Collection<ConfigAttribute> attrs = mds.findAttributes(method, DepartmentServiceImpl.class);
assertThat(attrs).isNotNull();
@@ -77,22 +76,19 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
// should have 1 SecurityConfig
for (ConfigAttribute sc : attrs) {
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo(
"ROLE_ADMIN");
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo("ROLE_ADMIN");
}
Method superMethod = null;
try {
superMethod = DepartmentServiceImpl.class.getMethod("someUserMethod3",
new Class[] { Entity.class });
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);
Collection<ConfigAttribute> superAttrs = this.mds.findAttributes(superMethod, DepartmentServiceImpl.class);
assertThat(superAttrs).isNotNull();
@@ -101,15 +97,13 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
assertThat(superAttrs).as("Did not find 1 attribute").hasSize(1);
// should have 1 SecurityConfig
for (ConfigAttribute sc : superAttrs) {
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo(
"ROLE_ADMIN");
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo("ROLE_ADMIN");
}
}
@Test
public void classLevelAttributesAreFound() {
Collection<ConfigAttribute> attrs = this.mds.findAttributes(
BusinessService.class);
Collection<ConfigAttribute> attrs = this.mds.findAttributes(BusinessService.class);
assertThat(attrs).isNotNull();
@@ -127,15 +121,13 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
Method method = null;
try {
method = BusinessService.class.getMethod("someUserAndAdminMethod",
new Class[] {});
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);
Collection<ConfigAttribute> attrs = this.mds.findAttributes(method, BusinessService.class);
// expect 2 attributes
assertThat(attrs).hasSize(2);
@@ -164,19 +156,16 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
public void customAnnotationAttributesAreFound() {
SecuredAnnotationSecurityMetadataSource mds = new SecuredAnnotationSecurityMetadataSource(
new CustomSecurityAnnotationMetadataExtractor());
Collection<ConfigAttribute> attrs = mds.findAttributes(
CustomAnnotatedService.class);
Collection<ConfigAttribute> attrs = mds.findAttributes(CustomAnnotatedService.class);
assertThat(attrs).containsOnly(SecurityEnum.ADMIN);
}
@Test
public void annotatedAnnotationAtClassLevelIsDetected() throws Exception {
MockMethodInvocation annotatedAtClassLevel = new MockMethodInvocation(
new AnnotatedAnnotationAtClassLevel(), ReturnVoid.class, "doSomething",
List.class);
MockMethodInvocation annotatedAtClassLevel = new MockMethodInvocation(new AnnotatedAnnotationAtClassLevel(),
ReturnVoid.class, "doSomething", List.class);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs).extracting("attribute").containsOnly("CUSTOM");
@@ -185,11 +174,9 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
@Test
public void annotatedAnnotationAtInterfaceLevelIsDetected() throws Exception {
MockMethodInvocation annotatedAtInterfaceLevel = new MockMethodInvocation(
new AnnotatedAnnotationAtInterfaceLevel(), ReturnVoid2.class,
"doSomething", List.class);
new AnnotatedAnnotationAtInterfaceLevel(), ReturnVoid2.class, "doSomething", List.class);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs).extracting("attribute").containsOnly("CUSTOM");
@@ -197,11 +184,9 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
@Test
public void annotatedAnnotationAtMethodLevelIsDetected() throws Exception {
MockMethodInvocation annotatedAtMethodLevel = new MockMethodInvocation(
new AnnotatedAnnotationAtMethodLevel(), ReturnVoid.class, "doSomething",
List.class);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray(
new ConfigAttribute[0]);
MockMethodInvocation annotatedAtMethodLevel = new MockMethodInvocation(new AnnotatedAnnotationAtMethodLevel(),
ReturnVoid.class, "doSomething", List.class);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs).extracting("attribute").containsOnly("CUSTOM");
@@ -221,34 +206,39 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
Department(String name) {
super(name);
}
}
interface DepartmentService extends BusinessService {
@Secured({ "ROLE_USER" })
Department someUserMethod3(Department dept);
}
@SuppressWarnings("serial")
class DepartmentServiceImpl extends BusinessServiceImpl<Department>
implements DepartmentService {
class DepartmentServiceImpl extends BusinessServiceImpl<Department> implements DepartmentService {
@Secured({ "ROLE_ADMIN" })
public Department someUserMethod3(final Department dept) {
return super.someUserMethod3(dept);
}
}
// SEC-1491 Related classes. PoC for custom annotation with enum value.
@CustomSecurityAnnotation(SecurityEnum.ADMIN)
interface CustomAnnotatedService {
}
class CustomAnnotatedServiceImpl implements CustomAnnotatedService {
}
enum SecurityEnum implements ConfigAttribute, GrantedAuthority {
ADMIN, USER;
public String getAttribute() {
@@ -258,24 +248,25 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
public String getAuthority() {
return toString();
}
}
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface CustomSecurityAnnotation {
SecurityEnum[]value();
SecurityEnum[] value();
}
class CustomSecurityAnnotationMetadataExtractor
implements AnnotationMetadataExtractor<CustomSecurityAnnotation> {
class CustomSecurityAnnotationMetadataExtractor implements AnnotationMetadataExtractor<CustomSecurityAnnotation> {
public Collection<? extends ConfigAttribute> extractAttributes(
CustomSecurityAnnotation securityAnnotation) {
public Collection<? extends ConfigAttribute> extractAttributes(CustomSecurityAnnotation securityAnnotation) {
SecurityEnum[] values = securityAnnotation.value();
return EnumSet.copyOf(Arrays.asList(values));
}
}
@Target({ ElementType.METHOD, ElementType.TYPE })
@@ -283,17 +274,20 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
@Inherited
@Secured("CUSTOM")
public @interface AnnotatedAnnotation {
}
public interface ReturnVoid {
void doSomething(List<?> param);
}
@AnnotatedAnnotation
public interface ReturnVoid2 {
void doSomething(List<?> param);
}
@AnnotatedAnnotation
@@ -301,12 +295,14 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
public void doSomething(List<?> param) {
}
}
public static class AnnotatedAnnotationAtInterfaceLevel implements ReturnVoid2 {
public void doSomething(List<?> param) {
}
}
public static class AnnotatedAnnotationAtMethodLevel implements ReturnVoid {
@@ -314,5 +310,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
@AnnotatedAnnotation
public void doSomething(List<?> param) {
}
}
}

View File

@@ -18,4 +18,5 @@ package org.springframework.security.access.annotation.sec2150;
public interface CrudRepository {
Iterable<Object> findAll();
}

View File

@@ -23,15 +23,14 @@ public class MethodInvocationFactory {
/**
* In order to reproduce the bug for SEC-2150, we must have a proxy object that
* implements TargetSourceAware and implements our annotated interface.
*
* @return
* @throws NoSuchMethodException
*/
public static MockMethodInvocation createSec2150MethodInvocation()
throws NoSuchMethodException {
public static MockMethodInvocation createSec2150MethodInvocation() throws NoSuchMethodException {
ProxyFactory factory = new ProxyFactory(new Class[] { PersonRepository.class });
factory.setTargetClass(CrudRepository.class);
PersonRepository repository = (PersonRepository) factory.getProxy();
return new MockMethodInvocation(repository, PersonRepository.class, "findAll");
}
}

View File

@@ -28,4 +28,5 @@ import org.springframework.security.access.prepost.PreAuthorize;
@Secured("ROLE_PERSON")
@PreAuthorize("hasRole('ROLE_PERSON')")
public interface PersonRepository extends CrudRepository {
}

View File

@@ -32,14 +32,15 @@ import org.springframework.security.core.Authentication;
* @author Luke Taylor
*/
public class AbstractSecurityExpressionHandlerTests {
private AbstractSecurityExpressionHandler<Object> handler;
@Before
public void setUp() {
handler = new AbstractSecurityExpressionHandler<Object>() {
@Override
protected SecurityExpressionOperations createSecurityExpressionRoot(
Authentication authentication, Object o) {
protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication,
Object o) {
return new SecurityExpressionRoot(authentication) {
};
}
@@ -48,13 +49,11 @@ public class AbstractSecurityExpressionHandlerTests {
@Test
public void beanNamesAreCorrectlyResolved() {
handler.setApplicationContext(new AnnotationConfigApplicationContext(
TestConfiguration.class));
handler.setApplicationContext(new AnnotationConfigApplicationContext(TestConfiguration.class));
Expression expression = handler.getExpressionParser().parseExpression(
"@number10.compareTo(@number20) < 0");
assertThat(expression.getValue(handler.createEvaluationContext(
mock(Authentication.class), new Object()))).isEqualTo(true);
Expression expression = handler.getExpressionParser().parseExpression("@number10.compareTo(@number20) < 0");
assertThat(expression.getValue(handler.createEvaluationContext(mock(Authentication.class), new Object())))
.isEqualTo(true);
}
@Test(expected = IllegalArgumentException.class)
@@ -68,6 +67,7 @@ public class AbstractSecurityExpressionHandlerTests {
handler.setExpressionParser(parser);
assertThat(parser == handler.getExpressionParser()).isTrue();
}
}
@Configuration
@@ -82,4 +82,5 @@ class TestConfiguration {
Integer number20() {
return 20;
}
}

View File

@@ -19,7 +19,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.authentication.AuthenticationTrustResolver;
@@ -28,13 +27,12 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
/**
*
* @author Luke Taylor
* @since 3.0
*/
public class SecurityExpressionRootTests {
final static Authentication JOE = new TestingAuthenticationToken("joe", "pass",
"ROLE_A", "ROLE_B");
final static Authentication JOE = new TestingAuthenticationToken("joe", "pass", "ROLE_A", "ROLE_B");
SecurityExpressionRoot root;
@@ -135,4 +133,5 @@ public class SecurityExpressionRootTests {
assertThat(root.hasAnyAuthority("NO", "A")).isFalse();
assertThat(root.hasAnyAuthority("ROLE_A", "NOT")).isTrue();
}
}

View File

@@ -41,12 +41,15 @@ import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class DefaultMethodSecurityExpressionHandlerTests {
private DefaultMethodSecurityExpressionHandler handler;
@Mock
private Authentication authentication;
@Mock
private MethodInvocation methodInvocation;
@Mock
private AuthenticationTrustResolver trustResolver;
@@ -71,10 +74,8 @@ public class DefaultMethodSecurityExpressionHandlerTests {
public void createEvaluationContextCustomTrustResolver() {
handler.setTrustResolver(trustResolver);
Expression expression = handler.getExpressionParser()
.parseExpression("anonymous");
EvaluationContext context = handler.createEvaluationContext(authentication,
methodInvocation);
Expression expression = handler.getExpressionParser().parseExpression("anonymous");
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
expression.getValue(context, Boolean.class);
verify(trustResolver).isAnonymous(authentication);
@@ -90,8 +91,7 @@ public class DefaultMethodSecurityExpressionHandlerTests {
Expression expression = handler.getExpressionParser().parseExpression("filterObject.key eq 'key2'");
EvaluationContext context = handler.createEvaluationContext(authentication,
methodInvocation);
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
Object filtered = handler.filter(map, expression, context);
@@ -112,8 +112,7 @@ public class DefaultMethodSecurityExpressionHandlerTests {
Expression expression = handler.getExpressionParser().parseExpression("filterObject.value eq 'value3'");
EvaluationContext context = handler.createEvaluationContext(authentication,
methodInvocation);
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
Object filtered = handler.filter(map, expression, context);
@@ -132,10 +131,10 @@ public class DefaultMethodSecurityExpressionHandlerTests {
map.put("key2", "value2");
map.put("key3", "value3");
Expression expression = handler.getExpressionParser().parseExpression("(filterObject.key eq 'key1') or (filterObject.value eq 'value2')");
Expression expression = handler.getExpressionParser()
.parseExpression("(filterObject.key eq 'key1') or (filterObject.value eq 'value2')");
EvaluationContext context = handler.createEvaluationContext(authentication,
methodInvocation);
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
Object filtered = handler.filter(map, expression, context);
@@ -153,8 +152,7 @@ public class DefaultMethodSecurityExpressionHandlerTests {
Expression expression = handler.getExpressionParser().parseExpression("filterObject ne '2'");
EvaluationContext context = handler.createEvaluationContext(authentication,
methodInvocation);
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
Object filtered = handler.filter(stream, expression, context);
@@ -170,15 +168,17 @@ public class DefaultMethodSecurityExpressionHandlerTests {
Expression expression = handler.getExpressionParser().parseExpression("true");
EvaluationContext context = handler.createEvaluationContext(authentication,
methodInvocation);
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
((Stream) handler.filter(upstream, expression, context)).close();
verify(upstream).close();
}
private static class Foo {
public void bar(){
public void bar() {
}
}
}

View File

@@ -50,94 +50,78 @@ public class ExpressionBasedPreInvocationAdviceTests {
@Test(expected = IllegalArgumentException.class)
public void findFilterTargetNameProvidedButNotMatch() throws Exception {
//given
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true",
"filterTargetDoesNotMatch",
null);
// given
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "filterTargetDoesNotMatch",
null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingCollection",
new Class[]{List.class},
new Object[]{new ArrayList<>()});
//when - then
"doSomethingCollection", new Class[] { List.class }, new Object[] { new ArrayList<>() });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
}
@Test(expected = IllegalArgumentException.class)
public void findFilterTargetNameProvidedArrayUnsupported() throws Exception {
//given
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true",
"param", null);
// given
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "param", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingArray",
new Class[]{String[].class},
new Object[]{new String[0]});
//when - then
"doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
}
@Test
public void findFilterTargetNameProvided() throws Exception {
//given
// given
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "param", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingCollection",
new Class[]{List.class},
new Object[]{new ArrayList<>()});
"doSomethingCollection", new Class[] { List.class }, new Object[] { new ArrayList<>() });
//when
boolean result = expressionBasedPreInvocationAdvice
.before(authentication, methodInvocation, attribute);
//then
// when
boolean result = expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
// then
assertThat(result).isTrue();
}
@Test(expected = IllegalArgumentException.class)
public void findFilterTargetNameNotProvidedArrayUnsupported() throws Exception {
//given
// given
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingArray",
new Class[]{String[].class},
new Object[]{new String[0]});
//when - then
"doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
}
@Test
public void findFilterTargetNameNotProvided() throws Exception {
//given
// given
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingCollection",
new Class[]{List.class},
new Object[]{new ArrayList<>()});
//when
"doSomethingCollection", new Class[] { List.class }, new Object[] { new ArrayList<>() });
// when
boolean result = expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
//then
// then
assertThat(result).isTrue();
}
@Test(expected = IllegalArgumentException.class)
public void findFilterTargetNameNotProvidedTypeNotSupported() throws Exception {
//given
// given
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingString",
new Class[]{String.class},
new Object[]{"param"});
//when - then
"doSomethingString", new Class[] { String.class }, new Object[] { "param" });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
}
@Test(expected = IllegalArgumentException.class)
public void findFilterTargetNameNotProvidedMethodAcceptMoreThenOneArgument() throws Exception {
//given
// given
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingTwoArgs",
new Class[]{String.class, List.class},
new Object[]{"param", new ArrayList<>()});
//when - then
"doSomethingTwoArgs", new Class[] { String.class, List.class },
new Object[] { "param", new ArrayList<>() });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
}
@@ -158,5 +142,7 @@ public class ExpressionBasedPreInvocationAdviceTests {
public Boolean doSomethingTwoArgs(String param, List<?> list) {
return Boolean.TRUE;
}
}
}

View File

@@ -34,48 +34,44 @@ import org.springframework.security.util.SimpleMethodInvocation;
@SuppressWarnings("unchecked")
public class MethodExpressionVoterTests {
private TestingAuthenticationToken joe = new TestingAuthenticationToken("joe",
"joespass", "ROLE_blah");
private TestingAuthenticationToken joe = new TestingAuthenticationToken("joe", "joespass", "ROLE_blah");
private PreInvocationAuthorizationAdviceVoter am = new PreInvocationAuthorizationAdviceVoter(
new ExpressionBasedPreInvocationAdvice());
@Test
public void hasRoleExpressionAllowsUserWithRole() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingAnArray());
assertThat(am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute(null, null,
"hasRole('blah')")))).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray());
assertThat(
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(null, null, "hasRole('blah')"))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
@Test
public void hasRoleExpressionDeniesUserWithoutRole() throws Exception {
List<ConfigAttribute> cad = new ArrayList<>(1);
cad.add(new PreInvocationExpressionAttribute(null, null, "hasRole('joedoesnt')"));
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingAnArray());
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray());
assertThat(am.vote(joe, mi, cad)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
}
@Test
public void matchingArgAgainstAuthenticationNameIsSuccessful() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingAString(), "joe");
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAString(), "joe");
assertThat(am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute(null, null,
"(#argument == principal) and (principal == 'joe')"))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
@Test
public void accessIsGrantedIfNoPreAuthorizeAttributeIsUsed() throws Exception {
Collection arg = createCollectionArg("joe", "bob", "sam");
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingACollection(), arg);
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(), arg);
assertThat(am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute(
"(filterObject == 'jim')", "collection", null))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'jim')", "collection", null))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
// All objects should have been removed, because the expression is always false
assertThat(arg).isEmpty();
}
@@ -83,46 +79,42 @@ public class MethodExpressionVoterTests {
@Test
public void collectionPreFilteringIsSuccessful() throws Exception {
List arg = createCollectionArg("joe", "bob", "sam");
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingACollection(), arg);
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(), arg);
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(
"(filterObject == 'joe' or filterObject == 'sam')", "collection",
"permitAll")));
"(filterObject == 'joe' or filterObject == 'sam')", "collection", "permitAll")));
assertThat(arg).containsExactly("joe", "sam");
}
@Test(expected = IllegalArgumentException.class)
public void arraysCannotBePrefiltered() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingAnArray(), createArrayArg("sam", "joe"));
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(
"(filterObject == 'jim')", "someArray", null)));
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray(),
createArrayArg("sam", "joe"));
am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'jim')", "someArray", null)));
}
@Test(expected = IllegalArgumentException.class)
public void incorrectFilterTargetNameIsRejected() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingACollection(), createCollectionArg("joe", "bob"));
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(
"(filterObject == 'joe')", "collcetion", null)));
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(),
createCollectionArg("joe", "bob"));
am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collcetion", null)));
}
@Test(expected = IllegalArgumentException.class)
public void nullNamedFilterTargetIsRejected() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingACollection(), new Object[] { null });
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(
"(filterObject == 'joe')", "collection", null)));
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(),
new Object[] { null });
am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collection", null)));
}
@Test
public void ruleDefinedInAClassMethodIsApplied() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingAString(), "joe");
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAString(), "joe");
assertThat(
am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute(null, null,
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(null, null,
"T(org.springframework.security.access.expression.method.SecurityRules).isJoe(#argument)"))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
@@ -159,14 +151,17 @@ public class MethodExpressionVoterTests {
// ==================================================================================================
private interface Target {
void methodTakingAnArray(Object[] args);
void methodTakingAString(String argument);
Collection methodTakingACollection(Collection collection);
}
private static class TargetImpl implements Target {
public void methodTakingAnArray(Object[] args) {
}
@@ -176,5 +171,7 @@ public class MethodExpressionVoterTests {
public Collection methodTakingACollection(Collection collection) {
return collection;
}
}
}

View File

@@ -36,10 +36,13 @@ import static org.mockito.Mockito.doReturn;
*/
@RunWith(MockitoJUnitRunner.class)
public class MethodSecurityEvaluationContextTests {
@Mock
private ParameterNameDiscoverer paramNameDiscoverer;
@Mock
private Authentication authentication;
@Mock
private MethodInvocation methodInvocation;
@@ -47,16 +50,16 @@ public class MethodSecurityEvaluationContextTests {
public void lookupVariableWhenParameterNameNullThenNotSet() {
Class<String> type = String.class;
Method method = ReflectionUtils.findMethod(String.class, "contains", CharSequence.class);
doReturn(new String[] {null}).when(paramNameDiscoverer).getParameterNames(method);
doReturn(new Object[]{null}).when(methodInvocation).getArguments();
doReturn(new String[] { null }).when(paramNameDiscoverer).getParameterNames(method);
doReturn(new Object[] { null }).when(methodInvocation).getArguments();
doReturn(type).when(methodInvocation).getThis();
doReturn(method).when(methodInvocation).getMethod();
NotNullVariableMethodSecurityEvaluationContext context= new NotNullVariableMethodSecurityEvaluationContext(authentication, methodInvocation, paramNameDiscoverer);
NotNullVariableMethodSecurityEvaluationContext context = new NotNullVariableMethodSecurityEvaluationContext(
authentication, methodInvocation, paramNameDiscoverer);
context.lookupVariable("testVariable");
}
private static class NotNullVariableMethodSecurityEvaluationContext
extends MethodSecurityEvaluationContext {
private static class NotNullVariableMethodSecurityEvaluationContext extends MethodSecurityEvaluationContext {
NotNullVariableMethodSecurityEvaluationContext(Authentication auth, MethodInvocation mi,
ParameterNameDiscoverer parameterNameDiscoverer) {
@@ -65,12 +68,14 @@ public class MethodSecurityEvaluationContextTests {
@Override
public void setVariable(String name, @Nullable Object value) {
if ( name == null ) {
if (name == null) {
throw new IllegalArgumentException("name should not be null");
}
else {
super.setVariable(name, value);
}
}
}
}

View File

@@ -34,10 +34,15 @@ import org.springframework.security.core.Authentication;
* @author Luke Taylor
*/
public class MethodSecurityExpressionRootTests {
SpelExpressionParser parser = new SpelExpressionParser();
MethodSecurityExpressionRoot root;
StandardEvaluationContext ctx;
private AuthenticationTrustResolver trustResolver;
private Authentication user;
@Before
@@ -99,8 +104,8 @@ public class MethodSecurityExpressionRootTests {
ctx.setVariable("domainObject", dummyDomainObject);
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
root.setPermissionEvaluator(pe);
when(pe.hasPermission(eq(user), eq(dummyDomainObject), any(Integer.class)))
.thenReturn(true).thenReturn(true).thenReturn(false);
when(pe.hasPermission(eq(user), eq(dummyDomainObject), any(Integer.class))).thenReturn(true).thenReturn(true)
.thenReturn(false);
Expression e = parser.parseExpression("hasPermission(#domainObject, 0xA)");
// evaluator returns true
@@ -135,4 +140,5 @@ public class MethodSecurityExpressionRootTests {
e = parser.parseExpression("hasPermission(this.x, 2)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
}
}

View File

@@ -39,54 +39,53 @@ import org.springframework.security.access.prepost.PrePostAnnotationSecurityMeta
import org.springframework.test.util.ReflectionTestUtils;
/**
*
* @author Luke Taylor
* @since 3.0
*/
public class PrePostAnnotationSecurityMetadataSourceTests {
private PrePostAnnotationSecurityMetadataSource mds = new PrePostAnnotationSecurityMetadataSource(
new ExpressionBasedAnnotationAttributeFactory(
new DefaultMethodSecurityExpressionHandler()));
new ExpressionBasedAnnotationAttributeFactory(new DefaultMethodSecurityExpressionHandler()));
private MockMethodInvocation voidImpl1;
private MockMethodInvocation voidImpl2;
private MockMethodInvocation voidImpl3;
private MockMethodInvocation listImpl1;
private MockMethodInvocation notherListImpl1;
private MockMethodInvocation notherListImpl2;
private MockMethodInvocation annotatedAtClassLevel;
private MockMethodInvocation annotatedAtInterfaceLevel;
private MockMethodInvocation annotatedAtMethodLevel;
@Before
public void setUpData() throws Exception {
voidImpl1 = new MockMethodInvocation(new ReturnVoidImpl1(), ReturnVoid.class,
"doSomething", List.class);
voidImpl2 = new MockMethodInvocation(new ReturnVoidImpl2(), ReturnVoid.class,
"doSomething", List.class);
voidImpl3 = new MockMethodInvocation(new ReturnVoidImpl3(), ReturnVoid.class,
"doSomething", List.class);
listImpl1 = new MockMethodInvocation(new ReturnAListImpl1(), ReturnAList.class,
"doSomething", List.class);
notherListImpl1 = new MockMethodInvocation(new ReturnAnotherListImpl1(),
ReturnAnotherList.class, "doSomething", List.class);
notherListImpl2 = new MockMethodInvocation(new ReturnAnotherListImpl2(),
ReturnAnotherList.class, "doSomething", List.class);
annotatedAtClassLevel = new MockMethodInvocation(
new CustomAnnotationAtClassLevel(), ReturnVoid.class, "doSomething",
voidImpl1 = new MockMethodInvocation(new ReturnVoidImpl1(), ReturnVoid.class, "doSomething", List.class);
voidImpl2 = new MockMethodInvocation(new ReturnVoidImpl2(), ReturnVoid.class, "doSomething", List.class);
voidImpl3 = new MockMethodInvocation(new ReturnVoidImpl3(), ReturnVoid.class, "doSomething", List.class);
listImpl1 = new MockMethodInvocation(new ReturnAListImpl1(), ReturnAList.class, "doSomething", List.class);
notherListImpl1 = new MockMethodInvocation(new ReturnAnotherListImpl1(), ReturnAnotherList.class, "doSomething",
List.class);
annotatedAtInterfaceLevel = new MockMethodInvocation(
new CustomAnnotationAtInterfaceLevel(), ReturnVoid2.class, "doSomething",
List.class);
annotatedAtMethodLevel = new MockMethodInvocation(
new CustomAnnotationAtMethodLevel(), ReturnVoid.class, "doSomething",
notherListImpl2 = new MockMethodInvocation(new ReturnAnotherListImpl2(), ReturnAnotherList.class, "doSomething",
List.class);
annotatedAtClassLevel = new MockMethodInvocation(new CustomAnnotationAtClassLevel(), ReturnVoid.class,
"doSomething", List.class);
annotatedAtInterfaceLevel = new MockMethodInvocation(new CustomAnnotationAtInterfaceLevel(), ReturnVoid2.class,
"doSomething", List.class);
annotatedAtMethodLevel = new MockMethodInvocation(new CustomAnnotationAtMethodLevel(), ReturnVoid.class,
"doSomething", List.class);
}
@Test
public void classLevelPreAnnotationIsPickedUpWhenNoMethodLevelExists() {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl1).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(voidImpl1).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -98,8 +97,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void mixedClassAndMethodPreAnnotationsAreBothIncluded() {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl2).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(voidImpl2).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -111,8 +109,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void methodWithPreFilterOnlyIsAllowed() {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl3).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(voidImpl3).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -124,8 +121,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void methodWithPostFilterOnlyIsAllowed() {
ConfigAttribute[] attrs = mds.getAttributes(listImpl1).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(listImpl1).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(2);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -139,8 +135,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void interfaceAttributesAreIncluded() {
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl1).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl1).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -153,8 +148,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void classAttributesTakesPrecedeceOverInterfaceAttributes() {
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl2).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl2).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -167,24 +161,21 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void customAnnotationAtClassLevelIsDetected() {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
}
@Test
public void customAnnotationAtInterfaceLevelIsDetected() {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
}
@Test
public void customAnnotationAtMethodLevelIsDetected() {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray(
new ConfigAttribute[0]);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
}
@@ -194,8 +185,8 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
MockMethodInvocation mi = MethodInvocationFactory.createSec2150MethodInvocation();
Collection<ConfigAttribute> attributes = mds.getAttributes(mi);
assertThat(attributes).hasSize(1);
Expression expression = (Expression) ReflectionTestUtils.getField(attributes
.iterator().next(), "authorizeExpression");
Expression expression = (Expression) ReflectionTestUtils.getField(attributes.iterator().next(),
"authorizeExpression");
assertThat(expression.getExpressionString()).isEqualTo("hasRole('ROLE_PERSON')");
}
@@ -203,47 +194,62 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
// ==================================================================================================
public interface ReturnVoid {
void doSomething(List<?> param);
}
public interface ReturnAList {
List<?> doSomething(List<?> param);
}
@PreAuthorize("interfaceAuthzExpression")
public interface ReturnAnotherList {
@PreAuthorize("interfaceMethodAuthzExpression")
@PreFilter(filterTarget = "param", value = "interfacePreFilterExpression")
List<?> doSomething(List<?> param);
}
@PreAuthorize("someExpression")
public static class ReturnVoidImpl1 implements ReturnVoid {
public void doSomething(List<?> param) {
}
}
@PreAuthorize("someExpression")
public static class ReturnVoidImpl2 implements ReturnVoid {
@PreFilter(filterTarget = "param", value = "somePreFilterExpression")
public void doSomething(List<?> param) {
}
}
public static class ReturnVoidImpl3 implements ReturnVoid {
@PreFilter(filterTarget = "param", value = "somePreFilterExpression")
public void doSomething(List<?> param) {
}
}
public static class ReturnAListImpl1 implements ReturnAList {
@PostFilter("somePostFilterExpression")
public List<?> doSomething(List<?> param) {
return param;
}
}
public static class ReturnAListImpl2 implements ReturnAList {
@PreAuthorize("someExpression")
@PreFilter(filterTarget = "param", value = "somePreFilterExpression")
@PostFilter("somePostFilterExpression")
@@ -251,19 +257,24 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
public List<?> doSomething(List<?> param) {
return param;
}
}
public static class ReturnAnotherListImpl1 implements ReturnAnotherList {
public List<?> doSomething(List<?> param) {
return param;
}
}
public static class ReturnAnotherListImpl2 implements ReturnAnotherList {
@PreFilter(filterTarget = "param", value = "classMethodPreFilterExpression")
public List<?> doSomething(List<?> param) {
return param;
}
}
@Target({ ElementType.METHOD, ElementType.TYPE })
@@ -271,27 +282,37 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Inherited
@PreAuthorize("customAnnotationExpression")
public @interface CustomAnnotation {
}
@CustomAnnotation
public interface ReturnVoid2 {
void doSomething(List<?> param);
}
@CustomAnnotation
public static class CustomAnnotationAtClassLevel implements ReturnVoid {
public void doSomething(List<?> param) {
}
}
public static class CustomAnnotationAtInterfaceLevel implements ReturnVoid2 {
public void doSomething(List<?> param) {
}
}
public static class CustomAnnotationAtMethodLevel implements ReturnVoid {
@CustomAnnotation
public void doSomething(List<?> param) {
}
}
}

View File

@@ -16,6 +16,7 @@
package org.springframework.security.access.expression.method;
public class SecurityRules {
public static boolean disallow() {
return false;
}
@@ -27,4 +28,5 @@ public class SecurityRules {
public static boolean isJoe(String s) {
return "joe".equals(s);
}
}

View File

@@ -29,8 +29,7 @@ import org.apache.commons.collections.CollectionUtils;
*/
public abstract class HierarchicalRolesTestHelper {
public static boolean containTheSameGrantedAuthorities(
Collection<? extends GrantedAuthority> authorities1,
public static boolean containTheSameGrantedAuthorities(Collection<? extends GrantedAuthority> authorities1,
Collection<? extends GrantedAuthority> authorities2) {
if (authorities1 == null && authorities2 == null) {
return true;
@@ -43,8 +42,7 @@ public abstract class HierarchicalRolesTestHelper {
}
public static boolean containTheSameGrantedAuthoritiesCompareByAuthorityString(
Collection<? extends GrantedAuthority> authorities1,
Collection<? extends GrantedAuthority> authorities2) {
Collection<? extends GrantedAuthority> authorities1, Collection<? extends GrantedAuthority> authorities2) {
if (authorities1 == null && authorities2 == null) {
return true;
}
@@ -52,13 +50,11 @@ public abstract class HierarchicalRolesTestHelper {
if (authorities1 == null || authorities2 == null) {
return false;
}
return CollectionUtils.isEqualCollection(
toCollectionOfAuthorityStrings(authorities1),
return CollectionUtils.isEqualCollection(toCollectionOfAuthorityStrings(authorities1),
toCollectionOfAuthorityStrings(authorities2));
}
public static List<String> toCollectionOfAuthorityStrings(
Collection<? extends GrantedAuthority> authorities) {
public static List<String> toCollectionOfAuthorityStrings(Collection<? extends GrantedAuthority> authorities) {
if (authorities == null) {
return null;
}

View File

@@ -41,9 +41,9 @@ public class RoleHierarchyAuthoritiesMapperTests {
mapper = new RoleHierarchyAuthoritiesMapper(new NullRoleHierarchy());
authorities = mapper.mapAuthorities(AuthorityUtils.createAuthorityList("ROLE_A",
"ROLE_D"));
authorities = mapper.mapAuthorities(AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_D"));
assertThat(authorities).hasSize(2);
}
}

View File

@@ -40,99 +40,72 @@ public class RoleHierarchyImplTests {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(
authorities0)).isNotNull();
assertThat(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isEmpty();
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isNotNull();
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isEmpty();
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(
authorities1)).isNotNull();
assertThat(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).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");
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();
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), authorities0)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities2)).isTrue();
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2),
authorities2)).isTrue();
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2), authorities2)).isTrue();
}
@Test
public void testTransitiveRoleHierarchies() {
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A",
"ROLE_B", "ROLE_C");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A",
"ROLE_B", "ROLE_C", "ROLE_D");
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B", "ROLE_C");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B", "ROLE_C",
"ROLE_D");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C");
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities2)).isTrue();
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_D");
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_D");
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities3)).isTrue();
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities3)).isTrue();
}
@Test
public void testComplexRoleHierarchy() {
List<GrantedAuthority> authoritiesInput1 = AuthorityUtils.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> authoritiesOutput1 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B", "ROLE_C", "ROLE_D");
List<GrantedAuthority> authoritiesInput2 = AuthorityUtils.createAuthorityList(
"ROLE_B");
List<GrantedAuthority> authoritiesOutput2 = AuthorityUtils.createAuthorityList(
"ROLE_B", "ROLE_D");
List<GrantedAuthority> authoritiesInput3 = AuthorityUtils.createAuthorityList(
"ROLE_C");
List<GrantedAuthority> authoritiesOutput3 = AuthorityUtils.createAuthorityList(
"ROLE_C", "ROLE_D");
List<GrantedAuthority> authoritiesInput4 = AuthorityUtils.createAuthorityList(
"ROLE_D");
List<GrantedAuthority> authoritiesOutput4 = AuthorityUtils.createAuthorityList(
List<GrantedAuthority> authoritiesInput1 = AuthorityUtils.createAuthorityList("ROLE_A");
List<GrantedAuthority> authoritiesOutput1 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B", "ROLE_C",
"ROLE_D");
List<GrantedAuthority> authoritiesInput2 = AuthorityUtils.createAuthorityList("ROLE_B");
List<GrantedAuthority> authoritiesOutput2 = AuthorityUtils.createAuthorityList("ROLE_B", "ROLE_D");
List<GrantedAuthority> authoritiesInput3 = AuthorityUtils.createAuthorityList("ROLE_C");
List<GrantedAuthority> authoritiesOutput3 = AuthorityUtils.createAuthorityList("ROLE_C", "ROLE_D");
List<GrantedAuthority> authoritiesInput4 = AuthorityUtils.createAuthorityList("ROLE_D");
List<GrantedAuthority> authoritiesOutput4 = AuthorityUtils.createAuthorityList("ROLE_D");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
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();
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput1), authoritiesOutput1)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput2),
authoritiesOutput2)).isTrue();
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput2), authoritiesOutput2)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput3),
authoritiesOutput3)).isTrue();
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput3), authoritiesOutput3)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput4),
authoritiesOutput4)).isTrue();
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput4), authoritiesOutput4)).isTrue();
}
@Test
@@ -154,8 +127,7 @@ public class RoleHierarchyImplTests {
}
try {
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A");
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException e) {
@@ -172,7 +144,8 @@ public class RoleHierarchyImplTests {
try {
roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B");
fail("Cycle in role hierarchy was not detected!");
} catch (CycleInRoleHierarchyException e) {
}
catch (CycleInRoleHierarchyException e) {
}
}
@@ -181,8 +154,7 @@ public class RoleHierarchyImplTests {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
try {
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
}
catch (CycleInRoleHierarchyException e) {
fail("A cycle in role hierarchy was incorrectly detected!");
@@ -193,93 +165,78 @@ public class RoleHierarchyImplTests {
@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");
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(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities2)).isTrue();
assertThat(
HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2),
authorities2)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), authorities0)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2), authorities2)).isTrue();
}
@Test
public void testWhitespaceRoleHierarchies() {
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList(
"ROLE A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE A",
"ROLE B", "ROLE>C");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE A",
"ROLE B", "ROLE>C", "ROLE D");
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE A", "ROLE B", "ROLE>C");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE A", "ROLE B", "ROLE>C",
"ROLE D");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE A > ROLE B\nROLE B > ROLE>C");
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities2)).isTrue();
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities2)).isTrue();
roleHierarchyImpl.setHierarchy(
"ROLE A > ROLE B\nROLE B > ROLE>C\nROLE>C > ROLE D");
roleHierarchyImpl.setHierarchy("ROLE A > ROLE B\nROLE B > ROLE>C\nROLE>C > ROLE D");
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities3)).isTrue();
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), authorities3)).isTrue();
}
// gh-6954
@Test
public void testJavadoc() {
List<GrantedAuthority> flatAuthorities = AuthorityUtils.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> allAuthorities = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B", "ROLE_AUTHENTICATED", "ROLE_UNAUTHENTICATED");
List<GrantedAuthority> flatAuthorities = AuthorityUtils.createAuthorityList("ROLE_A");
List<GrantedAuthority> allAuthorities = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B",
"ROLE_AUTHENTICATED", "ROLE_UNAUTHENTICATED");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\n"
+ "ROLE_B > ROLE_AUTHENTICATED\n"
+ "ROLE_AUTHENTICATED > ROLE_UNAUTHENTICATED");
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\n" + "ROLE_B > ROLE_AUTHENTICATED\n" + "ROLE_AUTHENTICATED > ROLE_UNAUTHENTICATED");
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities)).containsExactlyInAnyOrderElementsOf(allAuthorities);
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
.containsExactlyInAnyOrderElementsOf(allAuthorities);
}
// gh-6954
@Test
public void testInterfaceJavadoc() {
List<GrantedAuthority> flatAuthorities = AuthorityUtils.createAuthorityList(
"ROLE_HIGHEST");
List<GrantedAuthority> allAuthorities = AuthorityUtils.createAuthorityList(
"ROLE_HIGHEST", "ROLE_HIGHER", "ROLE_LOW", "ROLE_LOWER");
List<GrantedAuthority> flatAuthorities = AuthorityUtils.createAuthorityList("ROLE_HIGHEST");
List<GrantedAuthority> allAuthorities = AuthorityUtils.createAuthorityList("ROLE_HIGHEST", "ROLE_HIGHER",
"ROLE_LOW", "ROLE_LOWER");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_HIGHEST > ROLE_HIGHER\n"
+ "ROLE_HIGHER > ROLE_LOW\n"
+ "ROLE_LOW > ROLE_LOWER");
roleHierarchyImpl
.setHierarchy("ROLE_HIGHEST > ROLE_HIGHER\n" + "ROLE_HIGHER > ROLE_LOW\n" + "ROLE_LOW > ROLE_LOWER");
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities)).containsExactlyInAnyOrderElementsOf(allAuthorities);
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
.containsExactlyInAnyOrderElementsOf(allAuthorities);
}
// gh-6954
@Test
public void singleLineLargeHierarchy() {
List<GrantedAuthority> flatAuthorities = AuthorityUtils.createAuthorityList(
"ROLE_HIGHEST");
List<GrantedAuthority> allAuthorities = AuthorityUtils.createAuthorityList(
"ROLE_HIGHEST", "ROLE_HIGHER", "ROLE_LOW", "ROLE_LOWER");
List<GrantedAuthority> flatAuthorities = AuthorityUtils.createAuthorityList("ROLE_HIGHEST");
List<GrantedAuthority> allAuthorities = AuthorityUtils.createAuthorityList("ROLE_HIGHEST", "ROLE_HIGHER",
"ROLE_LOW", "ROLE_LOWER");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_HIGHEST > ROLE_HIGHER > ROLE_LOW > ROLE_LOWER");
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities)).containsExactlyInAnyOrderElementsOf(allAuthorities);
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
.containsExactlyInAnyOrderElementsOf(allAuthorities);
}
}

View File

@@ -28,6 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Joe Grandja
*/
public class RoleHierarchyUtilsTests {
private static final String EOL = System.lineSeparator();
@Test
@@ -90,4 +91,5 @@ public class RoleHierarchyUtilsTests {
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
}
}

View File

@@ -35,55 +35,34 @@ public class TestHelperTests {
@Test
public void testContainTheSameGrantedAuthorities() {
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList(
"ROLE_B", "ROLE_A");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_C");
List<GrantedAuthority> authorities4 = AuthorityUtils
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_A");
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_B", "ROLE_A");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_C");
List<GrantedAuthority> authorities4 = AuthorityUtils.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_A");
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, 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();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities3, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities4)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities5)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, null)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities3)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities3, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities4)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities4, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities4, authorities5)).isFalse();
}
// SEC-863
@Test
public void testToListOfAuthorityStrings() {
Collection<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B");
Collection<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList(
"ROLE_B", "ROLE_A");
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");
Collection<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B");
Collection<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_B", "ROLE_A");
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");
@@ -105,89 +84,69 @@ public class TestHelperTests {
authoritiesStrings5.add("ROLE_A");
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities1),
authoritiesStrings1)).isTrue();
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities1), authoritiesStrings1))
.isTrue();
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities2),
authoritiesStrings2)).isTrue();
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities2), authoritiesStrings2))
.isTrue();
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities3),
authoritiesStrings3)).isTrue();
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities3), authoritiesStrings3))
.isTrue();
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities4),
authoritiesStrings4)).isTrue();
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities4), authoritiesStrings4))
.isTrue();
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities5),
authoritiesStrings5)).isTrue();
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities5), authoritiesStrings5))
.isTrue();
}
// SEC-863
@Test
public void testContainTheSameGrantedAuthoritiesCompareByAuthorityString() {
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList(
"ROLE_B", "ROLE_A");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_C");
List<GrantedAuthority> authorities4 = AuthorityUtils
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_A");
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_B", "ROLE_A");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_C");
List<GrantedAuthority> authorities4 = AuthorityUtils.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_A");
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, 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();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities3, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities4)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities5)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, null)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities3)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities3, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities4)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities4, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities4, authorities5)).isFalse();
}
// SEC-863
@Test
public void testContainTheSameGrantedAuthoritiesCompareByAuthorityStringWithAuthorityLists() {
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B");
assertThat(HierarchicalRolesTestHelper
.containTheSameGrantedAuthoritiesCompareByAuthorityString(authorities1,
authorities2)).isTrue();
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B");
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(authorities1,
authorities2)).isTrue();
}
// SEC-863
@Test
public void testCreateAuthorityList() {
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_A");
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");
List<GrantedAuthority> authorities2 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A", "ROLE_C");
assertThat(authorities2).hasSize(2);
assertThat(authorities2.get(0).getAuthority()).isEqualTo("ROLE_A");
assertThat(authorities2.get(1).getAuthority()).isEqualTo("ROLE_C");
}
}

View File

@@ -31,6 +31,7 @@ import org.springframework.security.util.SimpleMethodInvocation;
* @author Ben Alex
*/
public class AbstractSecurityInterceptorTests {
// ~ Methods
// ========================================================================================================
@@ -61,6 +62,7 @@ public class AbstractSecurityInterceptorTests {
// ==================================================================================================
private class MockSecurityInterceptorReturnsNull extends AbstractSecurityInterceptor {
private SecurityMetadataSource securityMetadataSource;
public Class<?> getSecureObjectClass() {
@@ -71,14 +73,14 @@ public class AbstractSecurityInterceptorTests {
return securityMetadataSource;
}
public void setSecurityMetadataSource(
SecurityMetadataSource securityMetadataSource) {
public void setSecurityMetadataSource(SecurityMetadataSource securityMetadataSource) {
this.securityMetadataSource = securityMetadataSource;
}
}
private class MockSecurityInterceptorWhichOnlySupportsStrings extends
AbstractSecurityInterceptor {
private class MockSecurityInterceptorWhichOnlySupportsStrings extends AbstractSecurityInterceptor {
private SecurityMetadataSource securityMetadataSource;
public Class<?> getSecureObjectClass() {
@@ -89,9 +91,10 @@ public class AbstractSecurityInterceptorTests {
return securityMetadataSource;
}
public void setSecurityMetadataSource(
SecurityMetadataSource securityMetadataSource) {
public void setSecurityMetadataSource(SecurityMetadataSource securityMetadataSource) {
this.securityMetadataSource = securityMetadataSource;
}
}
}

View File

@@ -46,41 +46,33 @@ public class AfterInvocationProviderManagerTests {
public void testCorrectOperation() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP3")));
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
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" });
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(), attr1, "content-before-swapping"))
.isEqualTo("swap1");
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2,
"content-before-swapping")).isEqualTo("swap2");
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(), 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(), attr4, "content-before-swapping"))
.isEqualTo("content-before-swapping");
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2and3,
"content-before-swapping")).isEqualTo("swap3");
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2and3, "content-before-swapping"))
.isEqualTo("swap3");
}
@Test
@@ -101,11 +93,9 @@ public class AfterInvocationProviderManagerTests {
public void testRejectsNonAfterInvocationProviders() {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP1")));
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")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
try {
manager.setProviders(list);
@@ -133,12 +123,9 @@ public class AfterInvocationProviderManagerTests {
public void testSupportsConfigAttributeIteration() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP3")));
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
manager.setProviders(list);
manager.afterPropertiesSet();
@@ -150,12 +137,9 @@ public class AfterInvocationProviderManagerTests {
public void testSupportsSecureObjectIteration() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP3")));
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(new MockAfterInvocationProvider("swap2", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP2")));
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
manager.setProviders(list);
manager.afterPropertiesSet();
@@ -185,9 +169,8 @@ public class AfterInvocationProviderManagerTests {
this.configAttribute = configAttribute;
}
public Object decide(Authentication authentication, Object object,
Collection<ConfigAttribute> config, Object returnedObject)
throws AccessDeniedException {
public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config,
Object returnedObject) throws AccessDeniedException {
if (config.contains(configAttribute)) {
return forceReturnObject;
}
@@ -202,5 +185,7 @@ public class AfterInvocationProviderManagerTests {
public boolean supports(ConfigAttribute attribute) {
return attribute.equals(configAttribute);
}
}
}

View File

@@ -47,4 +47,5 @@ public class InterceptorStatusTokenTests {
assertThat(token.getSecureObject()).isEqualTo(mi);
assertThat(token.getSecurityContext()).isSameAs(ctx);
}
}

View File

@@ -27,6 +27,7 @@ import org.springframework.security.access.SecurityConfig;
* @author Ben Alex
*/
public class NullRunAsManagerTests {
// ~ Methods
// ========================================================================================================
@@ -47,4 +48,5 @@ public class NullRunAsManagerTests {
NullRunAsManager runAs = new NullRunAsManager();
assertThat(runAs.supports(new SecurityConfig("X"))).isFalse();
}
}

View File

@@ -33,8 +33,7 @@ public class RunAsImplAuthenticationProviderTests {
@Test(expected = BadCredentialsException.class)
public void testAuthenticationFailDueToWrongKey() {
RunAsUserToken token = new RunAsUserToken("wrong_key", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"),
UsernamePasswordAuthenticationToken.class);
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class);
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.setKey("hello_world");
@@ -44,15 +43,13 @@ public class RunAsImplAuthenticationProviderTests {
@Test
public void testAuthenticationSuccess() {
RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"),
UsernamePasswordAuthenticationToken.class);
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);
Assert.assertTrue("Should have returned RunAsUserToken", result instanceof RunAsUserToken);
RunAsUserToken resultCast = (RunAsUserToken) result;
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
@@ -79,4 +76,5 @@ public class RunAsImplAuthenticationProviderTests {
assertThat(provider.supports(RunAsUserToken.class)).isTrue();
assertThat(!provider.supports(TestingAuthenticationToken.class)).isTrue();
}
}

View File

@@ -42,8 +42,7 @@ public class RunAsManagerImplTests {
@Test
public void testDoesNotReturnAdditionalAuthoritiesIfCalledWithoutARunAsSetting() {
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken(
"Test", "Password",
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
RunAsManagerImpl runAs = new RunAsManagerImpl();
@@ -56,8 +55,8 @@ public class RunAsManagerImplTests {
@Test
public void testRespectsRolePrefix() {
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken(
"Test", "Password", AuthorityUtils.createAuthorityList("ONE", "TWO"));
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ONE", "TWO"));
RunAsManagerImpl runAs = new RunAsManagerImpl();
runAs.setKey("my_password");
@@ -66,12 +65,10 @@ public class RunAsManagerImplTests {
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 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());
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
assertThat(authorities.contains("FOOBAR_RUN_AS_SOMETHING")).isTrue();
assertThat(authorities.contains("ONE")).isTrue();
@@ -83,8 +80,7 @@ public class RunAsManagerImplTests {
@Test
public void testReturnsAdditionalGrantedAuthorities() {
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken(
"Test", "Password",
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
RunAsManagerImpl runAs = new RunAsManagerImpl();
@@ -100,8 +96,7 @@ public class RunAsManagerImplTests {
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
Set<String> authorities = AuthorityUtils.authorityListToSet(
result.getAuthorities());
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();
@@ -138,4 +133,5 @@ public class RunAsManagerImplTests {
assertThat(!runAs.supports(new SecurityConfig("ROLE_WHICH_IS_IGNORED"))).isTrue();
assertThat(!runAs.supports(new SecurityConfig("role_LOWER_CASE_FAILS"))).isTrue();
}
}

View File

@@ -33,8 +33,7 @@ public class RunAsUserTokenTests {
@Test
public void testAuthenticationSetting() {
RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"),
UsernamePasswordAuthenticationToken.class);
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class);
assertThat(token.isAuthenticated()).isTrue();
token.setAuthenticated(false);
assertThat(!token.isAuthenticated()).isTrue();
@@ -43,13 +42,11 @@ public class RunAsUserTokenTests {
@Test
public void testGetters() {
RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"),
UsernamePasswordAuthenticationToken.class);
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class);
assertThat("Test").isEqualTo(token.getPrincipal());
assertThat("Password").isEqualTo(token.getCredentials());
assertThat("my_password".hashCode()).isEqualTo(token.getKeyHash());
assertThat(UsernamePasswordAuthenticationToken.class).isEqualTo(
token.getOriginalAuthentication());
assertThat(UsernamePasswordAuthenticationToken.class).isEqualTo(token.getOriginalAuthentication());
}
@Test
@@ -68,10 +65,10 @@ public class RunAsUserTokenTests {
@Test
public void testToString() {
RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"),
UsernamePasswordAuthenticationToken.class);
assertThat(token.toString().lastIndexOf("Original Class: "
+ UsernamePasswordAuthenticationToken.class.getName().toString()) != -1).isTrue();
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class);
assertThat(token.toString()
.lastIndexOf("Original Class: " + UsernamePasswordAuthenticationToken.class.getName().toString()) != -1)
.isTrue();
}
// SEC-1792
@@ -81,4 +78,5 @@ public class RunAsUserTokenTests {
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), null);
assertThat(token.toString().lastIndexOf("Original Class: null") != -1).isTrue();
}
}

View File

@@ -54,13 +54,21 @@ import java.util.*;
*/
@SuppressWarnings("unchecked")
public class MethodSecurityInterceptorTests {
private TestingAuthenticationToken token;
private MethodSecurityInterceptor interceptor;
private ITargetObject realTarget;
private ITargetObject advisedTarget;
private AccessDecisionManager adm;
private MethodSecurityMetadataSource mds;
private AuthenticationManager authman;
private ApplicationEventPublisher eventPublisher;
// ~ Methods
@@ -132,23 +140,20 @@ public class MethodSecurityInterceptorTests {
}
@Test(expected = IllegalArgumentException.class)
public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation()
throws Throwable {
public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable {
when(mds.supports(MethodInvocation.class)).thenReturn(false);
interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation()
throws Exception {
public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception {
when(mds.supports(MethodInvocation.class)).thenReturn(true);
when(adm.supports(MethodInvocation.class)).thenReturn(false);
interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation()
throws Exception {
public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception {
final RunAsManager ram = mock(RunAsManager.class);
when(ram.supports(MethodInvocation.class)).thenReturn(false);
interceptor.setRunAsManager(ram);
@@ -156,8 +161,7 @@ public class MethodSecurityInterceptorTests {
}
@Test(expected = IllegalArgumentException.class)
public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation()
throws Exception {
public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception {
final AfterInvocationManager aim = mock(AfterInvocationManager.class);
when(aim.supports(MethodInvocation.class)).thenReturn(false);
interceptor.setAfterInvocationManager(aim);
@@ -165,15 +169,13 @@ public class MethodSecurityInterceptorTests {
}
@Test(expected = IllegalArgumentException.class)
public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes()
throws Exception {
public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception {
when(adm.supports(any(ConfigAttribute.class))).thenReturn(false);
interceptor.afterPropertiesSet();
}
@Test
public void validationNotAttemptedIfIsValidateConfigAttributesSetToFalse()
throws Exception {
public void validationNotAttemptedIfIsValidateConfigAttributesSetToFalse() throws Exception {
when(adm.supports(MethodInvocation.class)).thenReturn(true);
when(mds.supports(MethodInvocation.class)).thenReturn(true);
interceptor.setValidateConfigAttributes(false);
@@ -183,8 +185,7 @@ public class MethodSecurityInterceptorTests {
}
@Test
public void validationNotAttemptedIfMethodSecurityMetadataSourceReturnsNullForAttributes()
throws Exception {
public void validationNotAttemptedIfMethodSecurityMetadataSourceReturnsNullForAttributes() throws Exception {
when(adm.supports(MethodInvocation.class)).thenReturn(true);
when(mds.supports(MethodInvocation.class)).thenReturn(true);
when(mds.getAllConfigAttributes()).thenReturn(null);
@@ -205,19 +206,18 @@ public class MethodSecurityInterceptorTests {
public void callingAPublicMethodWhenPresentingAnAuthenticationObjectDoesntChangeItsAuthenticatedProperty() {
mdsReturnsNull();
SecurityContextHolder.getContext().setAuthentication(token);
assertThat(advisedTarget.publicMakeLowerCase("HELLO")).isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken false");
assertThat(advisedTarget.publicMakeLowerCase("HELLO"))
.isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken false");
assertThat(!token.isAuthenticated()).isTrue();
}
@Test(expected = AuthenticationException.class)
public void callIsntMadeWhenAuthenticationManagerRejectsAuthentication() {
final TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
"Password");
final TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password");
SecurityContextHolder.getContext().setAuthentication(token);
mdsReturnsUserRole();
when(authman.authenticate(token)).thenThrow(
new BadCredentialsException("rejected"));
when(authman.authenticate(token)).thenThrow(new BadCredentialsException("rejected"));
advisedTarget.makeLowerCase("HELLO");
}
@@ -232,7 +232,8 @@ public class MethodSecurityInterceptorTests {
String result = advisedTarget.makeLowerCase("HELLO");
// Note we check the isAuthenticated remained true in following line
assertThat(result).isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken true");
assertThat(result)
.isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken true");
verify(eventPublisher).publishEvent(any(AuthorizedEvent.class));
}
@@ -244,8 +245,8 @@ public class MethodSecurityInterceptorTests {
createTarget(true);
mdsReturnsUserRole();
when(authman.authenticate(token)).thenReturn(token);
doThrow(new AccessDeniedException("rejected")).when(adm).decide(
any(Authentication.class), any(MethodInvocation.class), any(List.class));
doThrow(new AccessDeniedException("rejected")).when(adm).decide(any(Authentication.class),
any(MethodInvocation.class), any(List.class));
try {
advisedTarget.makeUpperCase("HELLO");
@@ -267,12 +268,11 @@ public class MethodSecurityInterceptorTests {
ctx.setAuthentication(token);
token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds",
token.getAuthorities(), TestingAuthenticationToken.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", token.getAuthorities(),
TestingAuthenticationToken.class);
interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class)))
.thenReturn(runAsToken);
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
String result = advisedTarget.makeUpperCase("hello");
assertThat(result).isEqualTo("HELLO org.springframework.security.access.intercept.RunAsUserToken true");
@@ -290,12 +290,11 @@ public class MethodSecurityInterceptorTests {
ctx.setAuthentication(token);
token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds",
token.getAuthorities(), TestingAuthenticationToken.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", token.getAuthorities(),
TestingAuthenticationToken.class);
interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class)))
.thenReturn(runAsToken);
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
try {
advisedTarget.makeUpperCase("hello");
@@ -342,7 +341,7 @@ public class MethodSecurityInterceptorTests {
}
void mdsReturnsUserRole() {
when(mds.getAttributes(any(MethodInvocation.class))).thenReturn(
SecurityConfig.createList("ROLE_USER"));
when(mds.getAttributes(any(MethodInvocation.class))).thenReturn(SecurityConfig.createList("ROLE_USER"));
}
}

View File

@@ -43,10 +43,8 @@ public class MethodSecurityMetadataSourceAdvisorTests {
MethodSecurityMetadataSource mds = mock(MethodSecurityMetadataSource.class);
when(mds.getAttributes(method, clazz)).thenReturn(null);
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"", mds, "");
assertThat(advisor.getPointcut().getMethodMatcher().matches(method,
clazz)).isFalse();
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor("", mds, "");
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isFalse();
}
@Test
@@ -55,11 +53,9 @@ public class MethodSecurityMetadataSourceAdvisorTests {
Method method = clazz.getMethod("countLength", new Class[] { String.class });
MethodSecurityMetadataSource mds = mock(MethodSecurityMetadataSource.class);
when(mds.getAttributes(method, clazz)).thenReturn(
SecurityConfig.createList("ROLE_A"));
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"", mds, "");
assertThat(
advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isTrue();
when(mds.getAttributes(method, clazz)).thenReturn(SecurityConfig.createList("ROLE_A"));
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor("", mds, "");
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isTrue();
}
}

View File

@@ -54,12 +54,19 @@ import java.util.List;
* @author Rob Winch
*/
public class AspectJMethodSecurityInterceptorTests {
private TestingAuthenticationToken token;
private AspectJMethodSecurityInterceptor interceptor;
private @Mock AccessDecisionManager adm;
private @Mock MethodSecurityMetadataSource mds;
private @Mock AuthenticationManager authman;
private @Mock AspectJCallback aspectJCallback;
private ProceedingJoinPoint joinPoint;
// ~ Methods
@@ -87,8 +94,7 @@ public class AspectJMethodSecurityInterceptorTests {
when(codeSig.getDeclaringType()).thenReturn(TargetObject.class);
when(codeSig.getParameterTypes()).thenReturn(new Class[] { String.class });
when(staticPart.getSignature()).thenReturn(codeSig);
when(mds.getAttributes(any())).thenReturn(
SecurityConfig.createList("ROLE_USER"));
when(mds.getAttributes(any())).thenReturn(SecurityConfig.createList("ROLE_USER"));
when(authman.authenticate(token)).thenReturn(token);
}
@@ -110,8 +116,7 @@ public class AspectJMethodSecurityInterceptorTests {
@SuppressWarnings("unchecked")
@Test
public void callbackIsNotInvokedWhenPermissionDenied() {
doThrow(new AccessDeniedException("denied")).when(adm).decide(
any(), any(), any());
doThrow(new AccessDeniedException("denied")).when(adm).decide(any(), any(), any());
SecurityContextHolder.getContext().setAuthentication(token);
try {
@@ -126,8 +131,7 @@ public class AspectJMethodSecurityInterceptorTests {
@Test
public void adapterHoldsCorrectData() {
TargetObject to = new TargetObject();
Method m = ClassUtils.getMethodIfAvailable(TargetObject.class, "countLength",
new Class[] { String.class });
Method m = ClassUtils.getMethodIfAvailable(TargetObject.class, "countLength", new Class[] { String.class });
when(joinPoint.getTarget()).thenReturn(to);
when(joinPoint.getArgs()).thenReturn(new Object[] { "Hi" });
@@ -166,11 +170,10 @@ public class AspectJMethodSecurityInterceptorTests {
ctx.setAuthentication(token);
token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds",
token.getAuthorities(), TestingAuthenticationToken.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", token.getAuthorities(),
TestingAuthenticationToken.class);
interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class)))
.thenReturn(runAsToken);
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(aspectJCallback.proceedWithObject()).thenThrow(new RuntimeException());
try {
@@ -193,11 +196,10 @@ public class AspectJMethodSecurityInterceptorTests {
ctx.setAuthentication(token);
token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds",
token.getAuthorities(), TestingAuthenticationToken.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", token.getAuthorities(),
TestingAuthenticationToken.class);
interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class)))
.thenReturn(runAsToken);
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(joinPoint.proceed()).thenThrow(new RuntimeException());
try {
@@ -211,4 +213,5 @@ public class AspectJMethodSecurityInterceptorTests {
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
}
}

View File

@@ -33,10 +33,15 @@ import org.springframework.security.access.method.MapBasedMethodSecurityMetadata
* @since 2.0.4
*/
public class MapBasedMethodSecurityMetadataSourceTests {
private final List<ConfigAttribute> ROLE_A = SecurityConfig.createList("ROLE_A");
private final List<ConfigAttribute> ROLE_B = SecurityConfig.createList("ROLE_B");
private MapBasedMethodSecurityMetadataSource mds;
private Method someMethodString;
private Method someMethodInteger;
@Before
@@ -64,10 +69,13 @@ public class MapBasedMethodSecurityMetadataSourceTests {
@SuppressWarnings("unused")
private class MockService {
public void someMethod(String s) {
}
public void someMethod(Integer i) {
}
}
}

View File

@@ -47,10 +47,15 @@ import org.springframework.security.util.MethodInvocationUtils;
* @author Ben Alex
*/
public class MethodInvocationPrivilegeEvaluatorTests {
private TestingAuthenticationToken token;
private MethodSecurityInterceptor interceptor;
private AccessDecisionManager adm;
private MethodSecurityMetadataSource mds;
private final List<ConfigAttribute> role = SecurityConfig.createList("ROLE_IGNORED");
// ~ Methods
@@ -72,8 +77,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
@Test
public void allowsAccessUsingCreate() throws Exception {
Object object = new TargetObject();
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase",
"foobar");
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
when(mds.getAttributes(mi)).thenReturn(role);
@@ -86,9 +90,8 @@ public class MethodInvocationPrivilegeEvaluatorTests {
@Test
public void allowsAccessUsingCreateFromClass() {
final MethodInvocation mi = MethodInvocationUtils.createFromClass(
new OtherTargetObject(), ITargetObject.class, "makeLowerCase",
new Class[] { String.class }, new Object[] { "Hello world" });
final MethodInvocation mi = MethodInvocationUtils.createFromClass(new OtherTargetObject(), ITargetObject.class,
"makeLowerCase", new Class[] { String.class }, new Object[] { "Hello world" });
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(interceptor);
when(mds.getAttributes(mi)).thenReturn(role);
@@ -99,8 +102,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
@Test
public void declinesAccessUsingCreate() {
Object object = new TargetObject();
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase",
"foobar");
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(interceptor);
when(mds.getAttributes(mi)).thenReturn(role);
@@ -111,9 +113,8 @@ public class MethodInvocationPrivilegeEvaluatorTests {
@Test
public void declinesAccessUsingCreateFromClass() {
final MethodInvocation mi = MethodInvocationUtils.createFromClass(
new OtherTargetObject(), ITargetObject.class, "makeLowerCase",
new Class[] { String.class }, new Object[] { "helloWorld" });
final MethodInvocation mi = MethodInvocationUtils.createFromClass(new OtherTargetObject(), ITargetObject.class,
"makeLowerCase", new Class[] { String.class }, new Object[] { "helloWorld" });
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(interceptor);
@@ -122,4 +123,5 @@ public class MethodInvocationPrivilegeEvaluatorTests {
assertThat(mipe.isAllowed(mi, token)).isFalse();
}
}

View File

@@ -22,18 +22,21 @@ import java.lang.reflect.Method;
@SuppressWarnings("unchecked")
public class MockMethodInvocation implements MethodInvocation {
private Method method;
private Object targetObject;
private Object[] arguments = new Object[0];
public MockMethodInvocation(Object targetObject, Class clazz, String methodName, Class[] parameterTypes,
Object[] arguments) throws NoSuchMethodException {
Object[] arguments) throws NoSuchMethodException {
this(targetObject, clazz, methodName, parameterTypes);
this.arguments = arguments;
}
public MockMethodInvocation(Object targetObject, Class clazz, String methodName,
Class... parameterTypes) throws NoSuchMethodException {
public MockMethodInvocation(Object targetObject, Class clazz, String methodName, Class... parameterTypes)
throws NoSuchMethodException {
this.method = clazz.getMethod(methodName, parameterTypes);
this.targetObject = targetObject;
}
@@ -57,4 +60,5 @@ public class MockMethodInvocation implements MethodInvocation {
public Object proceed() {
return null;
}
}

View File

@@ -32,20 +32,20 @@ import java.util.*;
*/
@SuppressWarnings({ "unchecked" })
public class DelegatingMethodSecurityMetadataSourceTests {
DelegatingMethodSecurityMetadataSource mds;
@Test
public void returnsEmptyListIfDelegateReturnsNull() throws Exception {
List sources = new ArrayList();
MethodSecurityMetadataSource delegate = mock(MethodSecurityMetadataSource.class);
when(delegate.getAttributes(ArgumentMatchers.<Method> any(), ArgumentMatchers.any(Class.class)))
when(delegate.getAttributes(ArgumentMatchers.<Method>any(), ArgumentMatchers.any(Class.class)))
.thenReturn(null);
sources.add(delegate);
mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(mds.getAllConfigAttributes().isEmpty()).isTrue();
MethodInvocation mi = new SimpleMethodInvocation(null,
String.class.getMethod("toString"));
MethodInvocation mi = new SimpleMethodInvocation(null, String.class.getMethod("toString"));
assertThat(mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
// Exercise the cached case
assertThat(mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
@@ -67,8 +67,7 @@ public class DelegatingMethodSecurityMetadataSourceTests {
assertThat(mds.getAttributes(mi)).isSameAs(attributes);
// Exercise the cached case
assertThat(mds.getAttributes(mi)).isSameAs(attributes);
assertThat(mds.getAttributes(
new SimpleMethodInvocation(null, String.class.getMethod("length")))).isEmpty();
assertThat(mds.getAttributes(new SimpleMethodInvocation(null, String.class.getMethod("length")))).isEmpty();
}
}

View File

@@ -28,8 +28,10 @@ import org.springframework.security.access.intercept.aspectj.MethodInvocationAda
@RunWith(MockitoJUnitRunner.class)
public class PreInvocationAuthorizationAdviceVoterTests {
@Mock
private PreInvocationAuthorizationAdvice authorizationAdvice;
private PreInvocationAuthorizationAdviceVoter voter;
@Before
@@ -52,4 +54,5 @@ public class PreInvocationAuthorizationAdviceVoterTests {
public void supportsMethodInvocationAdapter() {
assertThat(voter.supports(MethodInvocationAdapter.class)).isTrue();
}
}

View File

@@ -136,14 +136,13 @@ public class AbstractAccessDecisionManagerTests {
private class MockDecisionManagerImpl extends AbstractAccessDecisionManager {
protected MockDecisionManagerImpl(
List<AccessDecisionVoter<? extends Object>> decisionVoters) {
protected MockDecisionManagerImpl(List<AccessDecisionVoter<? extends Object>> decisionVoters) {
super(decisionVoters);
}
public void decide(Authentication authentication, Object object,
Collection<ConfigAttribute> configAttributes) {
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {
}
}
private class MockStringOnlyVoter implements AccessDecisionVoter<Object> {
@@ -156,9 +155,10 @@ public class AbstractAccessDecisionManagerTests {
throw new UnsupportedOperationException("mock method not implemented");
}
public int vote(Authentication authentication, Object object,
Collection<ConfigAttribute> attributes) {
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
throw new UnsupportedOperationException("mock method not implemented");
}
}
}

View File

@@ -26,10 +26,10 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.util.MethodInvocationUtils;
/**
*
* @author Luke Taylor
*/
public class AbstractAclVoterTests {
private AbstractAclVoter voter = new AbstractAclVoter() {
public boolean supports(ConfigAttribute attribute) {
return false;
@@ -50,21 +50,21 @@ public class AbstractAclVoterTests {
@Test
public void expectedDomainObjectArgumentIsReturnedFromMethodInvocation() {
voter.setProcessDomainObjectClass(String.class);
MethodInvocation mi = MethodInvocationUtils.create(new TestClass(),
"methodTakingAString", "The Argument");
MethodInvocation mi = MethodInvocationUtils.create(new TestClass(), "methodTakingAString", "The Argument");
assertThat(voter.getDomainObjectInstance(mi)).isEqualTo("The Argument");
}
@Test
public void correctArgumentIsSelectedFromMultipleArgs() {
voter.setProcessDomainObjectClass(String.class);
MethodInvocation mi = MethodInvocationUtils.create(new TestClass(),
"methodTakingAListAndAString", new ArrayList<>(), "The Argument");
MethodInvocation mi = MethodInvocationUtils.create(new TestClass(), "methodTakingAListAndAString",
new ArrayList<>(), "The Argument");
assertThat(voter.getDomainObjectInstance(mi)).isEqualTo("The Argument");
}
@SuppressWarnings("unused")
private static class TestClass {
public void methodTakingAString(String arg) {
}
@@ -73,6 +73,7 @@ public class AbstractAclVoterTests {
public void methodTakingAListAndAString(ArrayList<Object> arg1, String arg2) {
}
}
}

View File

@@ -38,12 +38,17 @@ import org.springframework.security.core.Authentication;
* @author Ben Alex
*/
public class AffirmativeBasedTests {
private final List<ConfigAttribute> attrs = new ArrayList<>();
private final Authentication user = new TestingAuthenticationToken("somebody",
"password", "ROLE_1", "ROLE_2");
private final Authentication user = new TestingAuthenticationToken("somebody", "password", "ROLE_1", "ROLE_2");
private AffirmativeBased mgr;
private AccessDecisionVoter grant;
private AccessDecisionVoter abstain;
private AccessDecisionVoter deny;
@Before
@@ -63,40 +68,34 @@ public class AffirmativeBasedTests {
}
@Test
public void oneAffirmativeVoteOneDenyVoteOneAbstainVoteGrantsAccess()
throws Exception {
public void oneAffirmativeVoteOneDenyVoteOneAbstainVoteGrantsAccess() throws Exception {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>> asList(
grant, deny, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(grant, deny, abstain));
mgr.afterPropertiesSet();
mgr.decide(user, new Object(), attrs);
}
@Test
public void oneDenyVoteOneAbstainVoteOneAffirmativeVoteGrantsAccess() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>> asList(
deny, abstain, grant));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(deny, abstain, grant));
mgr.decide(user, new Object(), attrs);
}
@Test
public void oneAffirmativeVoteTwoAbstainVotesGrantsAccess() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>> asList(
grant, abstain, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(grant, abstain, abstain));
mgr.decide(user, new Object(), attrs);
}
@Test(expected = AccessDeniedException.class)
public void oneDenyVoteTwoAbstainVotesDeniesAccess() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>> asList(
deny, abstain, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(deny, abstain, abstain));
mgr.decide(user, new Object(), attrs);
}
@Test(expected = AccessDeniedException.class)
public void onlyAbstainVotesDeniesAccessWithDefault() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>> asList(
abstain, abstain, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(abstain, abstain, abstain));
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
mgr.decide(user, new Object(), attrs);
@@ -104,11 +103,11 @@ public class AffirmativeBasedTests {
@Test
public void testThreeAbstainVotesGrantsAccessIfAllowIfAllAbstainDecisionsIsSet() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>> asList(
abstain, abstain, abstain));
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(abstain, abstain, abstain));
mgr.setAllowIfAllAbstainDecisions(true);
assertThat(mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
mgr.decide(user, new Object(), attrs);
}
}

View File

@@ -39,8 +39,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
public class AuthenticatedVoterTests {
private Authentication createAnonymous() {
return new AnonymousAuthenticationToken("ignored", "ignored",
AuthorityUtils.createAuthorityList("ignored"));
return new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"));
}
private Authentication createFullyAuthenticated() {
@@ -49,47 +48,34 @@ public class AuthenticatedVoterTests {
}
private Authentication createRememberMe() {
return new RememberMeAuthenticationToken("ignored", "ignored",
AuthorityUtils.createAuthorityList("ignored"));
return new RememberMeAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"));
}
@Test
public void testAnonymousWorks() {
AuthenticatedVoter voter = new AuthenticatedVoter();
List<ConfigAttribute> def = SecurityConfig.createList(
AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY);
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createAnonymous(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createRememberMe(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createFullyAuthenticated(), null, def));
List<ConfigAttribute> def = SecurityConfig.createList(AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY);
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(voter.vote(createAnonymous(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(voter.vote(createRememberMe(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(voter.vote(createFullyAuthenticated(), null, def));
}
@Test
public void testFullyWorks() {
AuthenticatedVoter voter = new AuthenticatedVoter();
List<ConfigAttribute> def = SecurityConfig.createList(
AuthenticatedVoter.IS_AUTHENTICATED_FULLY);
assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo(
voter.vote(createAnonymous(), null, def));
assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo(
voter.vote(createRememberMe(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createFullyAuthenticated(), null, def));
List<ConfigAttribute> def = SecurityConfig.createList(AuthenticatedVoter.IS_AUTHENTICATED_FULLY);
assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo(voter.vote(createAnonymous(), null, def));
assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo(voter.vote(createRememberMe(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(voter.vote(createFullyAuthenticated(), null, def));
}
@Test
public void testRememberMeWorks() {
AuthenticatedVoter voter = new AuthenticatedVoter();
List<ConfigAttribute> def = SecurityConfig.createList(
AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED);
assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo(
voter.vote(createAnonymous(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createRememberMe(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createFullyAuthenticated(), null, def));
List<ConfigAttribute> def = SecurityConfig.createList(AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED);
assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo(voter.vote(createAnonymous(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(voter.vote(createRememberMe(), null, def));
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(voter.vote(createFullyAuthenticated(), null, def));
}
@Test
@@ -109,12 +95,10 @@ public class AuthenticatedVoterTests {
public void testSupports() {
AuthenticatedVoter voter = new AuthenticatedVoter();
assertThat(voter.supports(String.class)).isTrue();
assertThat(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY))).isTrue();
assertThat(voter.supports(
new SecurityConfig(AuthenticatedVoter.IS_AUTHENTICATED_FULLY))).isTrue();
assertThat(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED))).isTrue();
assertThat(voter.supports(new SecurityConfig(AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY))).isTrue();
assertThat(voter.supports(new SecurityConfig(AuthenticatedVoter.IS_AUTHENTICATED_FULLY))).isTrue();
assertThat(voter.supports(new SecurityConfig(AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED))).isTrue();
assertThat(voter.supports(new SecurityConfig("FOO"))).isFalse();
}
}

View File

@@ -41,8 +41,7 @@ public class ConsensusBasedTests {
mgr.setAllowIfEqualGrantedDeniedDecisions(false);
assertThat(!mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check changed
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1",
"DENY_FOR_SURE");
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1", "DENY_FOR_SURE");
mgr.decide(auth, new Object(), config);
}
@@ -54,8 +53,7 @@ public class ConsensusBasedTests {
assertThat(mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check default
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1",
"DENY_FOR_SURE");
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1", "DENY_FOR_SURE");
mgr.decide(auth, new Object(), config);
@@ -122,4 +120,5 @@ public class ConsensusBasedTests {
private TestingAuthenticationToken makeTestToken() {
return new TestingAuthenticationToken("somebody", "password", "ROLE_1", "ROLE_2");
}
}

View File

@@ -34,6 +34,7 @@ import java.util.Iterator;
* @author Ben Alex
*/
public class DenyAgainVoter implements AccessDecisionVoter<Object> {
// ~ Methods
// ========================================================================================================
@@ -50,8 +51,7 @@ public class DenyAgainVoter implements AccessDecisionVoter<Object> {
return true;
}
public int vote(Authentication authentication, Object object,
Collection<ConfigAttribute> attributes) {
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
Iterator<ConfigAttribute> iter = attributes.iterator();
while (iter.hasNext()) {

View File

@@ -36,6 +36,7 @@ import java.util.Iterator;
* @author Ben Alex
*/
public class DenyVoter implements AccessDecisionVoter<Object> {
// ~ Methods
// ========================================================================================================
@@ -52,8 +53,7 @@ public class DenyVoter implements AccessDecisionVoter<Object> {
return true;
}
public int vote(Authentication authentication, Object object,
Collection<ConfigAttribute> attributes) {
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
Iterator<ConfigAttribute> iter = attributes.iterator();
while (iter.hasNext()) {
@@ -66,4 +66,5 @@ public class DenyVoter implements AccessDecisionVoter<Object> {
return ACCESS_ABSTAIN;
}
}

View File

@@ -31,10 +31,11 @@ public class RoleHierarchyVoterTests {
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
// User has role A, role B is required
TestingAuthenticationToken auth = new TestingAuthenticationToken("user",
"password", "ROLE_A");
TestingAuthenticationToken auth = new TestingAuthenticationToken("user", "password", "ROLE_A");
RoleHierarchyVoter voter = new RoleHierarchyVoter(roleHierarchyImpl);
assertThat(voter.vote(auth, new Object(), SecurityConfig.createList("ROLE_B"))).isEqualTo(RoleHierarchyVoter.ACCESS_GRANTED);
assertThat(voter.vote(auth, new Object(), SecurityConfig.createList("ROLE_B")))
.isEqualTo(RoleHierarchyVoter.ACCESS_GRANTED);
}
}

View File

@@ -24,17 +24,18 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
/**
*
* @author Luke Taylor
*/
public class RoleVoterTests {
@Test
public void oneMatchingAttributeGrantsAccess() {
RoleVoter voter = new RoleVoter();
voter.setRolePrefix("");
Authentication userAB = new TestingAuthenticationToken("user", "pass", "A", "B");
// Vote on attribute list that has two attributes A and C (i.e. only one matching)
assertThat(voter.vote(userAB, this, SecurityConfig.createList("A", "C"))).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
assertThat(voter.vote(userAB, this, SecurityConfig.createList("A", "C")))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
// SEC-3128
@@ -43,6 +44,8 @@ public class RoleVoterTests {
RoleVoter voter = new RoleVoter();
voter.setRolePrefix("");
Authentication notAuthenitcated = null;
assertThat(voter.vote(notAuthenitcated, this, SecurityConfig.createList("A"))).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
assertThat(voter.vote(notAuthenitcated, this, SecurityConfig.createList("A")))
.isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
}
}

View File

@@ -22,6 +22,7 @@ package org.springframework.security.access.vote;
* @author Ben Alex
*/
public class SomeDomainObject {
// ~ Instance fields
// ================================================================================================
@@ -40,4 +41,5 @@ public class SomeDomainObject {
public String getParent() {
return "parentOf" + identity;
}
}

View File

@@ -23,9 +23,11 @@ package org.springframework.security.access.vote;
* @author Ben Alex
*/
public class SomeDomainObjectManager {
// ~ Methods
// ========================================================================================================
public void someServiceMethod(SomeDomainObject someDomainObject) {
}
}

View File

@@ -68,8 +68,7 @@ public class UnanimousBasedTests {
}
private TestingAuthenticationToken makeTestTokenWithFooBarPrefix() {
return new TestingAuthenticationToken("somebody", "password", "FOOBAR_1",
"FOOBAR_2");
return new TestingAuthenticationToken("somebody", "password", "FOOBAR_1", "FOOBAR_2");
}
@Test
@@ -77,8 +76,7 @@ public class UnanimousBasedTests {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
List<ConfigAttribute> config = SecurityConfig.createList(
new String[] { "ROLE_1", "DENY_FOR_SURE" });
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1", "DENY_FOR_SURE" });
try {
mgr.decide(auth, new Object(), config);
@@ -118,8 +116,7 @@ public class UnanimousBasedTests {
TestingAuthenticationToken auth = makeTestTokenWithFooBarPrefix();
UnanimousBased mgr = makeDecisionManagerWithFooBarPrefix();
List<ConfigAttribute> config = SecurityConfig.createList(
new String[] { "FOOBAR_1", "FOOBAR_2" });
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "FOOBAR_1", "FOOBAR_2" });
mgr.decide(auth, new Object(), config);
}
@@ -158,9 +155,9 @@ public class UnanimousBasedTests {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
List<ConfigAttribute> config = SecurityConfig.createList(
new String[] { "ROLE_1", "ROLE_2" });
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1", "ROLE_2" });
mgr.decide(auth, new Object(), config);
}
}

View File

@@ -33,6 +33,7 @@ import java.util.*;
* @author Ben Alex
*/
public class AbstractAuthenticationTokenTests {
// ~ Instance fields
// ================================================================================================
@@ -48,10 +49,8 @@ public class AbstractAuthenticationTokenTests {
@Test(expected = UnsupportedOperationException.class)
public void testAuthoritiesAreImmutable() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password",
authorities);
List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token
.getAuthorities();
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token.getAuthorities();
assertThat(gotAuthorities).isNotSameAs(authorities);
gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER"));
@@ -59,8 +58,7 @@ public class AbstractAuthenticationTokenTests {
@Test
public void testGetters() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password",
authorities);
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("Password");
assertThat(token.getName()).isEqualTo("Test");
@@ -68,12 +66,9 @@ public class AbstractAuthenticationTokenTests {
@Test
public void testHashCode() {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password",
authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password",
authorities);
MockAuthenticationImpl token3 = new MockAuthenticationImpl(null, null,
AuthorityUtils.NO_AUTHORITIES);
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token3 = new MockAuthenticationImpl(null, null, AuthorityUtils.NO_AUTHORITIES);
assertThat(token2.hashCode()).isEqualTo(token1.hashCode());
assertThat(token1.hashCode() != token3.hashCode()).isTrue();
@@ -84,18 +79,14 @@ public class AbstractAuthenticationTokenTests {
@Test
public void testObjectsEquals() {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password",
authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password",
authorities);
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities);
assertThat(token2).isEqualTo(token1);
MockAuthenticationImpl token3 = new MockAuthenticationImpl("Test",
"Password_Changed", authorities);
MockAuthenticationImpl token3 = new MockAuthenticationImpl("Test", "Password_Changed", authorities);
assertThat(!token1.equals(token3)).isTrue();
MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed",
"Password", authorities);
MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed", "Password", authorities);
assertThat(!token1.equals(token4)).isTrue();
MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test", "Password",
@@ -106,8 +97,7 @@ public class AbstractAuthenticationTokenTests {
AuthorityUtils.createAuthorityList("ROLE_ONE"));
assertThat(!token1.equals(token6)).isTrue();
MockAuthenticationImpl token7 = new MockAuthenticationImpl("Test", "Password",
null);
MockAuthenticationImpl token7 = new MockAuthenticationImpl("Test", "Password", null);
assertThat(!token1.equals(token7)).isTrue();
assertThat(!token7.equals(token1)).isTrue();
@@ -116,8 +106,7 @@ public class AbstractAuthenticationTokenTests {
@Test
public void testSetAuthenticated() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password",
authorities);
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertThat(!token.isAuthenticated()).isTrue();
token.setAuthenticated(true);
assertThat(token.isAuthenticated()).isTrue();
@@ -125,15 +114,13 @@ public class AbstractAuthenticationTokenTests {
@Test
public void testToStringWithAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password",
authorities);
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
assertThat(token.toString().lastIndexOf("ROLE_TWO") != -1).isTrue();
}
@Test
public void testToStringWithNullAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password",
null);
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", null);
assertThat(token.toString().lastIndexOf("Not granted any authorities") != -1).isTrue();
}
@@ -153,7 +140,9 @@ public class AbstractAuthenticationTokenTests {
// ==================================================================================================
private class MockAuthenticationImpl extends AbstractAuthenticationToken {
private Object credentials;
private Object principal;
MockAuthenticationImpl(Object principal, Object credentials, List<GrantedAuthority> authorities) {
@@ -169,5 +158,7 @@ public class AbstractAuthenticationTokenTests {
public Object getPrincipal() {
return this.principal;
}
}
}

View File

@@ -34,35 +34,36 @@ public class AuthenticationTrustResolverImplTests {
@Test
public void testCorrectOperationIsAnonymous() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertThat(trustResolver.isAnonymous(new AnonymousAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored")))).isTrue();
assertThat(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored")))).isFalse();
assertThat(trustResolver.isAnonymous(
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))))
.isTrue();
assertThat(trustResolver.isAnonymous(
new TestingAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))))
.isFalse();
}
@Test
public void testCorrectOperationIsRememberMe() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertThat(trustResolver.isRememberMe(new RememberMeAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored")))).isTrue();
assertThat(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored")))).isFalse();
assertThat(trustResolver.isRememberMe(
new RememberMeAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))))
.isTrue();
assertThat(trustResolver.isAnonymous(
new TestingAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))))
.isFalse();
}
@Test
public void testGettersSetters() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertThat(AnonymousAuthenticationToken.class).isEqualTo(
trustResolver.getAnonymousClass());
assertThat(AnonymousAuthenticationToken.class).isEqualTo(trustResolver.getAnonymousClass());
trustResolver.setAnonymousClass(TestingAuthenticationToken.class);
assertThat(trustResolver.getAnonymousClass()).isEqualTo(
TestingAuthenticationToken.class);
assertThat(trustResolver.getAnonymousClass()).isEqualTo(TestingAuthenticationToken.class);
assertThat(RememberMeAuthenticationToken.class).isEqualTo(
trustResolver.getRememberMeClass());
assertThat(RememberMeAuthenticationToken.class).isEqualTo(trustResolver.getRememberMeClass());
trustResolver.setRememberMeClass(TestingAuthenticationToken.class);
assertThat(trustResolver.getRememberMeClass()).isEqualTo(
TestingAuthenticationToken.class);
assertThat(trustResolver.getRememberMeClass()).isEqualTo(TestingAuthenticationToken.class);
}
}

View File

@@ -39,6 +39,7 @@ import java.util.*;
* @author Luke Taylor
*/
public class DefaultAuthenticationEventPublisherTests {
DefaultAuthenticationEventPublisher publisher;
@Test
@@ -52,12 +53,10 @@ public class DefaultAuthenticationEventPublisherTests {
Object extraInfo = new Object();
publisher.publishAuthenticationFailure(new BadCredentialsException(""), a);
publisher.publishAuthenticationFailure(new BadCredentialsException("", cause), a);
verify(appPublisher, times(2)).publishEvent(
isA(AuthenticationFailureBadCredentialsEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
reset(appPublisher);
publisher.publishAuthenticationFailure(new UsernameNotFoundException(""), a);
publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause),
a);
publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause), a);
publisher.publishAuthenticationFailure(new AccountExpiredException(""), a);
publisher.publishAuthenticationFailure(new AccountExpiredException("", cause), a);
publisher.publishAuthenticationFailure(new ProviderNotFoundException(""), a);
@@ -66,25 +65,16 @@ public class DefaultAuthenticationEventPublisherTests {
publisher.publishAuthenticationFailure(new LockedException(""), a);
publisher.publishAuthenticationFailure(new LockedException("", cause), a);
publisher.publishAuthenticationFailure(new AuthenticationServiceException(""), a);
publisher.publishAuthenticationFailure(new AuthenticationServiceException("",
cause), a);
publisher.publishAuthenticationFailure(new AuthenticationServiceException("", cause), a);
publisher.publishAuthenticationFailure(new CredentialsExpiredException(""), a);
publisher.publishAuthenticationFailure(
new CredentialsExpiredException("", cause), a);
verify(appPublisher, times(2)).publishEvent(
isA(AuthenticationFailureBadCredentialsEvent.class));
verify(appPublisher, times(2)).publishEvent(
isA(AuthenticationFailureExpiredEvent.class));
verify(appPublisher).publishEvent(
isA(AuthenticationFailureProviderNotFoundEvent.class));
verify(appPublisher, times(2)).publishEvent(
isA(AuthenticationFailureDisabledEvent.class));
verify(appPublisher, times(2)).publishEvent(
isA(AuthenticationFailureLockedEvent.class));
verify(appPublisher, times(2)).publishEvent(
isA(AuthenticationFailureServiceExceptionEvent.class));
verify(appPublisher, times(2)).publishEvent(
isA(AuthenticationFailureCredentialsExpiredEvent.class));
publisher.publishAuthenticationFailure(new CredentialsExpiredException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureExpiredEvent.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureProviderNotFoundEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureLockedEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureServiceExceptionEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureCredentialsExpiredEvent.class));
verifyNoMoreInteractions(appPublisher);
}
@@ -105,14 +95,12 @@ public class DefaultAuthenticationEventPublisherTests {
public void additionalExceptionMappingsAreSupported() {
publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(),
AuthenticationFailureDisabledEvent.class.getName());
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
publisher.setAdditionalExceptionMappings(p);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
publisher.setApplicationEventPublisher(appPublisher);
publisher.publishAuthenticationFailure(new MockAuthenticationException("test"),
mock(Authentication.class));
publisher.publishAuthenticationFailure(new MockAuthenticationException("test"), mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
@@ -128,8 +116,7 @@ public class DefaultAuthenticationEventPublisherTests {
public void unknownFailureExceptionIsIgnored() {
publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(),
AuthenticationFailureDisabledEvent.class.getName());
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
publisher.setAdditionalExceptionMappings(p);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
@@ -141,16 +128,14 @@ public class DefaultAuthenticationEventPublisherTests {
@Test(expected = IllegalArgumentException.class)
public void emptyMapCausesException() {
Map<Class<? extends AuthenticationException>,
Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
publisher = new DefaultAuthenticationEventPublisher();
publisher.setAdditionalExceptionMappings(mappings);
}
@Test(expected = IllegalArgumentException.class)
public void missingExceptionClassCausesException() {
Map<Class<? extends AuthenticationException>,
Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(null, AuthenticationFailureLockedEvent.class);
publisher = new DefaultAuthenticationEventPublisher();
publisher.setAdditionalExceptionMappings(mappings);
@@ -158,8 +143,7 @@ public class DefaultAuthenticationEventPublisherTests {
@Test(expected = IllegalArgumentException.class)
public void missingEventClassAsMapValueCausesException() {
Map<Class<? extends AuthenticationException>,
Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(LockedException.class, null);
publisher = new DefaultAuthenticationEventPublisher();
publisher.setAdditionalExceptionMappings(mappings);
@@ -168,15 +152,13 @@ public class DefaultAuthenticationEventPublisherTests {
@Test
public void additionalExceptionMappingsUsingMapAreSupported() {
publisher = new DefaultAuthenticationEventPublisher();
Map<Class<? extends AuthenticationException>,
Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(MockAuthenticationException.class, AuthenticationFailureDisabledEvent.class);
publisher.setAdditionalExceptionMappings(mappings);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
publisher.setApplicationEventPublisher(appPublisher);
publisher.publishAuthenticationFailure(new MockAuthenticationException("test"),
mock(Authentication.class));
publisher.publishAuthenticationFailure(new MockAuthenticationException("test"), mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
@@ -204,18 +186,22 @@ public class DefaultAuthenticationEventPublisherTests {
publisher.setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class);
}
private static final class AuthenticationFailureEventWithoutAppropriateConstructor extends
AbstractAuthenticationFailureEvent {
private static final class AuthenticationFailureEventWithoutAppropriateConstructor
extends AbstractAuthenticationFailureEvent {
AuthenticationFailureEventWithoutAppropriateConstructor(Authentication auth) {
super(auth, new AuthenticationException("") {});
super(auth, new AuthenticationException("") {
});
}
}
private static final class MockAuthenticationException extends
AuthenticationException {
private static final class MockAuthenticationException extends AuthenticationException {
MockAuthenticationException(String msg) {
super(msg);
}
}
}

View File

@@ -36,6 +36,7 @@ import static org.mockito.Mockito.when;
*/
@RunWith(MockitoJUnitRunner.class)
public class DelegatingReactiveAuthenticationManagerTests {
@Mock
ReactiveAuthenticationManager delegate1;
@@ -50,31 +51,34 @@ public class DelegatingReactiveAuthenticationManagerTests {
when(this.delegate1.authenticate(any())).thenReturn(Mono.empty());
when(this.delegate2.authenticate(any())).thenReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
this.delegate2);
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
@Test
public void authenticateWhenNotEmptyThenOtherDelegatesNotSubscribed() {
// delay to try and force delegate2 to finish (i.e. make sure we didn't use flatMap)
when(this.delegate1.authenticate(any())).thenReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
// delay to try and force delegate2 to finish (i.e. make sure we didn't use
// flatMap)
when(this.delegate1.authenticate(any()))
.thenReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
this.delegate2);
StepVerifier.create(manager.authenticate(this.authentication))
.expectNext(this.authentication)
.verifyComplete();
StepVerifier.create(manager.authenticate(this.authentication)).expectNext(this.authentication).verifyComplete();
}
@Test
public void authenticateWhenBadCredentialsThenDelegate2NotInvokedAndError() {
when(this.delegate1.authenticate(any())).thenReturn(Mono.error(new BadCredentialsException("Test")));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
this.delegate2);
StepVerifier.create(manager.authenticate(this.authentication))
.expectError(BadCredentialsException.class)
.verify();
StepVerifier.create(manager.authenticate(this.authentication)).expectError(BadCredentialsException.class)
.verify();
}
}

View File

@@ -63,8 +63,7 @@ public class ProviderManagerTests {
@Test
public void credentialsAreClearedByDefault() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"Test", "Password");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password");
ProviderManager mgr = makeProviderManager();
Authentication result = mgr.authenticate(token);
assertThat(result.getCredentials()).isNull();
@@ -90,8 +89,8 @@ public class ProviderManagerTests {
@Test
public void authenticationSucceedsWhenFirstProviderReturnsNullButSecondAuthenticates() {
final Authentication a = mock(Authentication.class);
ProviderManager mgr = new ProviderManager(Arrays.asList(
createProviderWhichReturns(null), createProviderWhichReturns(a)));
ProviderManager mgr = new ProviderManager(
Arrays.asList(createProviderWhichReturns(null), createProviderWhichReturns(a)));
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
@@ -132,8 +131,7 @@ public class ProviderManagerTests {
// A provider which sets the details object
AuthenticationProvider provider = new AuthenticationProvider() {
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
((TestingAuthenticationToken) authentication).setDetails(resultDetails);
return authentication;
}
@@ -169,17 +167,16 @@ public class ProviderManagerTests {
public void authenticationExceptionIsIgnoredIfLaterProviderAuthenticates() {
final Authentication authReq = mock(Authentication.class);
ProviderManager mgr = new ProviderManager(
createProviderWhichThrows(new BadCredentialsException("",
new Throwable())), createProviderWhichReturns(authReq));
createProviderWhichThrows(new BadCredentialsException("", new Throwable())),
createProviderWhichReturns(authReq));
assertThat(mgr.authenticate(mock(Authentication.class))).isSameAs(authReq);
}
@Test
public void authenticationExceptionIsRethrownIfNoLaterProviderAuthenticates() {
ProviderManager mgr = new ProviderManager(Arrays.asList(
createProviderWhichThrows(new BadCredentialsException("")),
createProviderWhichReturns(null)));
ProviderManager mgr = new ProviderManager(Arrays
.asList(createProviderWhichThrows(new BadCredentialsException("")), createProviderWhichReturns(null)));
try {
mgr.authenticate(mock(Authentication.class));
fail("Expected BadCredentialsException");
@@ -191,13 +188,11 @@ public class ProviderManagerTests {
// SEC-546
@Test
public void accountStatusExceptionPreventsCallsToSubsequentProviders() {
AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException(
"") {
AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException("") {
});
AuthenticationProvider otherProvider = mock(AuthenticationProvider.class);
ProviderManager authMgr = new ProviderManager(Arrays.asList(
iThrowAccountStatusException, otherProvider));
ProviderManager authMgr = new ProviderManager(Arrays.asList(iThrowAccountStatusException, otherProvider));
try {
authMgr.authenticate(mock(Authentication.class));
@@ -213,19 +208,18 @@ public class ProviderManagerTests {
AuthenticationManager parent = mock(AuthenticationManager.class);
Authentication authReq = mock(Authentication.class);
when(parent.authenticate(authReq)).thenReturn(authReq);
ProviderManager mgr = new ProviderManager(
Collections.singletonList(mock(AuthenticationProvider.class)), parent);
ProviderManager mgr = new ProviderManager(Collections.singletonList(mock(AuthenticationProvider.class)),
parent);
assertThat(mgr.authenticate(authReq)).isSameAs(authReq);
}
@Test
public void parentIsNotCalledIfAccountStatusExceptionIsThrown() {
AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException(
"", new Throwable()) {
});
AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(
new AccountStatusException("", new Throwable()) {
});
AuthenticationManager parent = mock(AuthenticationManager.class);
ProviderManager mgr = new ProviderManager(
Collections.singletonList(iThrowAccountStatusException), parent);
ProviderManager mgr = new ProviderManager(Collections.singletonList(iThrowAccountStatusException), parent);
try {
mgr.authenticate(mock(Authentication.class));
fail("Expected exception");
@@ -245,8 +239,7 @@ public class ProviderManagerTests {
// 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);
Collections.singletonList(createProviderWhichThrows(new BadCredentialsException(""))), parent);
mgr.setAuthenticationEventPublisher(publisher);
try {
@@ -262,15 +255,13 @@ public class ProviderManagerTests {
public void authenticationExceptionFromParentOverridesPreviousOnes() {
AuthenticationManager parent = mock(AuthenticationManager.class);
ProviderManager mgr = new ProviderManager(
Collections.singletonList(createProviderWhichThrows(new BadCredentialsException(""))),
parent);
Collections.singletonList(createProviderWhichThrows(new BadCredentialsException(""))), parent);
final Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
final BadCredentialsException expected = new BadCredentialsException(
"I'm the one from the parent");
final BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
when(parent.authenticate(authReq)).thenThrow(expected);
try {
mgr.authenticate(authReq);
@@ -285,8 +276,8 @@ public class ProviderManagerTests {
public void statusExceptionIsPublished() {
AuthenticationManager parent = mock(AuthenticationManager.class);
final LockedException expected = new LockedException("");
ProviderManager mgr = new ProviderManager(
Collections.singletonList(createProviderWhichThrows(expected)), parent);
ProviderManager mgr = new ProviderManager(Collections.singletonList(createProviderWhichThrows(expected)),
parent);
final Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
@@ -303,10 +294,8 @@ public class ProviderManagerTests {
// SEC-2367
@Test
public void providerThrowsInternalAuthenticationServiceException() {
InternalAuthenticationServiceException expected = new InternalAuthenticationServiceException(
"Expected");
ProviderManager mgr = new ProviderManager(Arrays.asList(
createProviderWhichThrows(expected),
InternalAuthenticationServiceException expected = new InternalAuthenticationServiceException("Expected");
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(expected),
createProviderWhichThrows(new BadCredentialsException("Oops"))), null);
final Authentication authReq = mock(Authentication.class);
@@ -323,8 +312,8 @@ public class ProviderManagerTests {
public void authenticateWhenFailsInParentAndPublishesThenChildDoesNotPublish() {
BadCredentialsException badCredentialsExParent = new BadCredentialsException("Bad Credentials in parent");
ProviderManager parentMgr = new ProviderManager(createProviderWhichThrows(badCredentialsExParent));
ProviderManager childMgr = new ProviderManager(Collections.singletonList(createProviderWhichThrows(
new BadCredentialsException("Bad Credentials in child"))), parentMgr);
ProviderManager childMgr = new ProviderManager(Collections.singletonList(
createProviderWhichThrows(new BadCredentialsException("Bad Credentials in child"))), parentMgr);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
parentMgr.setAuthenticationEventPublisher(publisher);
@@ -339,12 +328,12 @@ public class ProviderManagerTests {
catch (BadCredentialsException e) {
assertThat(e).isSameAs(badCredentialsExParent);
}
verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq); // Parent publishes
verifyNoMoreInteractions(publisher); // Child should not publish (duplicate event)
verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq); // Parent
// publishes
verifyNoMoreInteractions(publisher); // Child should not publish (duplicate event)
}
private AuthenticationProvider createProviderWhichThrows(
final AuthenticationException e) {
private AuthenticationProvider createProviderWhichThrows(final AuthenticationException e) {
AuthenticationProvider provider = mock(AuthenticationProvider.class);
when(provider.supports(any(Class.class))).thenReturn(true);
when(provider.authenticate(any(Authentication.class))).thenThrow(e);
@@ -361,8 +350,7 @@ public class ProviderManagerTests {
}
private TestingAuthenticationToken createAuthenticationToken() {
return new TestingAuthenticationToken("name", "password",
new ArrayList<>(0));
return new TestingAuthenticationToken("name", "password", new ArrayList<>(0));
}
private ProviderManager makeProviderManager() {
@@ -374,8 +362,8 @@ public class ProviderManagerTests {
// ==================================================================================================
private static class MockProvider implements AuthenticationProvider {
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (supports(authentication.getClass())) {
return authentication;
}
@@ -386,8 +374,9 @@ public class ProviderManagerTests {
public boolean supports(Class<?> authentication) {
return TestingAuthenticationToken.class.isAssignableFrom(authentication)
|| UsernamePasswordAuthenticationToken.class
.isAssignableFrom(authentication);
|| UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
}

View File

@@ -35,8 +35,10 @@ import static org.mockito.Mockito.when;
*/
@RunWith(MockitoJUnitRunner.class)
public class ReactiveAuthenticationManagerAdapterTests {
@Mock
AuthenticationManager delegate;
@Mock
Authentication authentication;
@@ -82,8 +84,7 @@ public class ReactiveAuthenticationManagerAdapterTests {
Mono<Authentication> result = manager.authenticate(authentication);
StepVerifier.create(result)
.expectError(BadCredentialsException.class)
.verify();
StepVerifier.create(result).expectError(BadCredentialsException.class).verify();
}
}

View File

@@ -41,11 +41,17 @@ import reactor.test.StepVerifier;
*/
@RunWith(MockitoJUnitRunner.class)
public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Mock ReactiveUserDetailsService repository;
@Mock
ReactiveUserDetailsService repository;
@Mock
PasswordEncoder passwordEncoder;
UserDetailsRepositoryReactiveAuthenticationManager manager;
String username;
String password;
@Before
@@ -68,10 +74,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
Mono<Authentication> authentication = manager.authenticate(token);
StepVerifier
.create(authentication)
.expectError(BadCredentialsException.class)
.verify();
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
}
@Test
@@ -84,13 +87,11 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
// @formatter:on
when(repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, this.password + "INVALID");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,
this.password + "INVALID");
Mono<Authentication> authentication = manager.authenticate(token);
StepVerifier
.create(authentication)
.expectError(BadCredentialsException.class)
.verify();
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
}
@Test
@@ -116,8 +117,8 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
this.username, this.password);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
Authentication authentication = this.manager.authenticate(token).block();
assertThat(authentication).isEqualTo(authentication);
@@ -130,14 +131,12 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
this.username, this.password);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
Mono<Authentication> authentication = this.manager.authenticate(token);
StepVerifier
.create(authentication)
.expectError(BadCredentialsException.class)
.verify();
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
}
}

View File

@@ -37,4 +37,5 @@ public class TestAuthentication extends PasswordEncodedUser {
public static Authentication autheticated(UserDetails user) {
return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
}
}

View File

@@ -32,8 +32,7 @@ public class TestingAuthenticationProviderTests {
@Test
public void testAuthenticates() {
TestingAuthenticationProvider provider = new TestingAuthenticationProvider();
TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
"Password", "ROLE_ONE", "ROLE_TWO");
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", "ROLE_ONE", "ROLE_TWO");
Authentication result = provider.authenticate(token);
assertThat(result instanceof TestingAuthenticationToken).isTrue();
@@ -41,9 +40,7 @@ public class TestingAuthenticationProviderTests {
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
assertThat(castResult.getPrincipal()).isEqualTo("Test");
assertThat(castResult.getCredentials()).isEqualTo("Password");
assertThat(
AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains(
"ROLE_ONE", "ROLE_TWO");
assertThat(AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains("ROLE_ONE", "ROLE_TWO");
}
@Test
@@ -52,4 +49,5 @@ public class TestingAuthenticationProviderTests {
assertThat(provider.supports(TestingAuthenticationToken.class)).isTrue();
assertThat(!provider.supports(String.class)).isTrue();
}
}

View File

@@ -26,28 +26,28 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Josh Cummings
*/
public class TestingAuthenticationTokenTests {
@Test
public void constructorWhenNoAuthoritiesThenUnauthenticated() {
TestingAuthenticationToken unauthenticated =
new TestingAuthenticationToken("principal", "credentials");
TestingAuthenticationToken unauthenticated = new TestingAuthenticationToken("principal", "credentials");
assertThat(unauthenticated.isAuthenticated()).isFalse();
}
@Test
public void constructorWhenArityAuthoritiesThenAuthenticated() {
TestingAuthenticationToken authenticated =
new TestingAuthenticationToken("principal", "credentials", "authority");
TestingAuthenticationToken authenticated = new TestingAuthenticationToken("principal", "credentials",
"authority");
assertThat(authenticated.isAuthenticated()).isTrue();
}
@Test
public void constructorWhenCollectionAuthoritiesThenAuthenticated() {
TestingAuthenticationToken authenticated =
new TestingAuthenticationToken("principal", "credentials",
TestingAuthenticationToken authenticated = new TestingAuthenticationToken("principal", "credentials",
Arrays.asList(new SimpleGrantedAuthority("authority")));
assertThat(authenticated.isAuthenticated()).isTrue();
}
}

View File

@@ -44,6 +44,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
*/
@RunWith(MockitoJUnitRunner.class)
public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Mock
private ReactiveUserDetailsService userDetailsService;
@@ -79,8 +80,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void setSchedulerWhenNullThenIllegalArgumentException() {
assertThatCode(() -> this.manager.setScheduler(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatCode(() -> this.manager.setScheduler(null)).isInstanceOf(IllegalArgumentException.class);
}
@Test
@@ -89,8 +89,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
when(this.encoder.matches(any(), any())).thenReturn(true);
this.manager.setScheduler(this.scheduler);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
this.user, this.user.getPassword());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
@@ -107,8 +107,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
when(this.userDetailsPasswordService.updatePassword(any(), any())).thenReturn(Mono.just(this.user));
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
this.user, this.user.getPassword());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
@@ -122,11 +122,10 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
when(this.encoder.matches(any(), any())).thenReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
this.user, this.user.getPassword());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
this.user.getPassword());
assertThatThrownBy(() -> this.manager.authenticate(token).block())
.isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> this.manager.authenticate(token).block()).isInstanceOf(BadCredentialsException.class);
verifyZeroInteractions(this.userDetailsPasswordService);
}
@@ -138,8 +137,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
when(this.encoder.upgradeEncoding(any())).thenReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
this.user, this.user.getPassword());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
@@ -154,8 +153,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
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())
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));
@@ -167,8 +166,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
when(this.encoder.matches(any(), any())).thenReturn(true);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
this.user, this.user.getPassword());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
this.user.getPassword());
this.manager.authenticate(token).block();
@@ -187,8 +186,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
// @formatter:on
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(expiredUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
expiredUser, expiredUser.getPassword());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(expiredUser,
expiredUser.getPassword());
this.manager.authenticate(token).block();
}
@@ -205,8 +204,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
// @formatter:on
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(lockedUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
lockedUser, lockedUser.getPassword());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(lockedUser,
lockedUser.getPassword());
this.manager.authenticate(token).block();
}
@@ -224,8 +223,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
// @formatter:on
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(disabledUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
disabledUser, disabledUser.getPassword());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(disabledUser,
disabledUser.getPassword());
this.manager.authenticate(token).block();
}

View File

@@ -34,8 +34,8 @@ public class UsernamePasswordAuthenticationTokenTests {
@Test
public void authenticatedPropertyContractIsSatisfied() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"Test", "Password", AuthorityUtils.NO_AUTHORITIES);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.NO_AUTHORITIES);
// check default given we passed some GrantedAuthorty[]s (well, we passed empty
// list)
@@ -67,8 +67,7 @@ public class UsernamePasswordAuthenticationTokenTests {
@Test
public void gettersReturnCorrectData() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"Test", "Password",
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("Password");
@@ -81,4 +80,5 @@ public class UsernamePasswordAuthenticationTokenTests {
Class<?> clazz = UsernamePasswordAuthenticationToken.class;
clazz.getDeclaredConstructor((Class[]) null);
}
}

View File

@@ -38,12 +38,10 @@ public class AnonymousAuthenticationProviderTests {
@Test
public void testDetectsAnInvalidKey() {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(
"qwerty");
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(
"WRONG_KEY", "Test", AuthorityUtils.createAuthorityList("ROLE_ONE",
"ROLE_TWO"));
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY", "Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
try {
aap.authenticate(token);
@@ -66,18 +64,15 @@ public class AnonymousAuthenticationProviderTests {
@Test
public void testGettersSetters() {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(
"qwerty");
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
assertThat(aap.getKey()).isEqualTo("qwerty");
}
@Test
public void testIgnoresClassesItDoesNotSupport() {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(
"qwerty");
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
TestingAuthenticationToken token = new TestingAuthenticationToken("user",
"password", "ROLE_A");
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password", "ROLE_A");
assertThat(aap.supports(TestingAuthenticationToken.class)).isFalse();
// Try it anyway
@@ -86,11 +81,10 @@ public class AnonymousAuthenticationProviderTests {
@Test
public void testNormalOperation() {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(
"qwerty");
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("qwerty",
"Test", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("qwerty", "Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
Authentication result = aap.authenticate(token);
@@ -99,9 +93,9 @@ public class AnonymousAuthenticationProviderTests {
@Test
public void testSupports() {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(
"qwerty");
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
assertThat(aap.supports(AnonymousAuthenticationToken.class)).isTrue();
assertThat(aap.supports(TestingAuthenticationToken.class)).isFalse();
}
}

View File

@@ -35,8 +35,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
*/
public class AnonymousAuthenticationTokenTests {
private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList(
"ROLE_ONE", "ROLE_TWO");
private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
// ~ Methods
// ========================================================================================================
@@ -57,16 +56,14 @@ public class AnonymousAuthenticationTokenTests {
}
try {
new AnonymousAuthenticationToken("key", "Test",
null);
new AnonymousAuthenticationToken("key", "Test", null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new AnonymousAuthenticationToken("key", "Test",
AuthorityUtils.NO_AUTHORITIES);
new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -75,24 +72,20 @@ public class AnonymousAuthenticationTokenTests {
@Test
public void testEqualsWhenEqual() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
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);
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains(
"ROLE_ONE", "ROLE_TWO");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_ONE", "ROLE_TWO");
assertThat(token.isAuthenticated()).isTrue();
}
@@ -110,39 +103,33 @@ public class AnonymousAuthenticationTokenTests {
@Test
public void testNotEqualsDueToAbstractParentEqualsCheck() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key",
"DIFFERENT_PRINCIPAL", ROLES_12);
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key", "DIFFERENT_PRINCIPAL", ROLES_12);
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testNotEqualsDueToDifferentAuthenticationClass() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken(
"Test", "Password", ROLES_12);
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 token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken(
"DIFFERENT_KEY", "Test", ROLES_12);
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("DIFFERENT_KEY", "Test", ROLES_12);
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testSetAuthenticatedIgnored() {
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test", ROLES_12);
assertThat(token.isAuthenticated()).isTrue();
token.setAuthenticated(false);
assertThat(!token.isAuthenticated()).isTrue();
@@ -162,4 +149,5 @@ public class AnonymousAuthenticationTokenTests {
public void constructorWhenPrincipalIsEmptyStringThenThrowIllegalArgumentException() {
new AnonymousAuthenticationToken("key", "", ROLES_12);
}
}

View File

@@ -68,15 +68,13 @@ import org.springframework.security.core.userdetails.UserDetailsPasswordService;
*/
public class DaoAuthenticationProviderTests {
private static final List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList(
"ROLE_ONE", "ROLE_TWO");
private static final List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
// ~ Methods
// ========================================================================================================
@Test
public void testAuthenticateFailsForIncorrectPasswordCase() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "KOala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "KOala");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@@ -98,8 +96,7 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache());
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
"rod", null);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null);
try {
provider.authenticate(authenticationToken);
fail("Expected BadCredenialsException");
@@ -111,12 +108,10 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsIfAccountExpired() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"peter", "opal");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(
new MockUserDetailsServiceUserPeterAccountExpired());
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountExpired());
provider.setUserCache(new MockUserCache());
try {
@@ -130,8 +125,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsIfAccountLocked() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"peter", "opal");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountLocked());
@@ -148,12 +142,10 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsIfCredentialsExpired() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"peter", "opal");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(
new MockUserDetailsServiceUserPeterCredentialsExpired());
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterCredentialsExpired());
provider.setUserCache(new MockUserCache());
try {
@@ -179,8 +171,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsIfUserDisabled() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"peter", "opal");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeter());
@@ -197,8 +188,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsWhenAuthenticationDaoHasBackendFailure() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceSimulateBackendError());
@@ -214,8 +204,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsWithEmptyUsername() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
null, "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(null, "koala");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@@ -232,8 +221,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsWithInvalidPassword() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "INVALID_PASSWORD");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "INVALID_PASSWORD");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@@ -250,8 +238,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionFalse() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"INVALID_USER", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER", "koala");
DaoAuthenticationProvider provider = createProvider();
provider.setHideUserNotFoundExceptions(false); // we want
@@ -270,8 +257,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionsWithDefaultOfTrue() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"INVALID_USER", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER", "koala");
DaoAuthenticationProvider provider = createProvider();
assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
@@ -289,8 +275,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsWithInvalidUsernameAndChangePasswordEncoder() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"INVALID_USER", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER", "koala");
DaoAuthenticationProvider provider = createProvider();
assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
@@ -318,8 +303,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticateFailsWithMixedCaseUsernameIfDefaultChanged() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"RoD", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("RoD", "koala");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@@ -336,8 +320,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticates() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
token.setDetails("192.168.0.1");
DaoAuthenticationProvider provider = createProvider();
@@ -353,16 +336,13 @@ public class DaoAuthenticationProviderTests {
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertThat(castResult.getPrincipal().getClass()).isEqualTo(User.class);
assertThat(castResult.getCredentials()).isEqualTo("koala");
assertThat(
AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains(
"ROLE_ONE", "ROLE_TWO");
assertThat(AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains("ROLE_ONE", "ROLE_TWO");
assertThat(castResult.getDetails()).isEqualTo("192.168.0.1");
}
@Test
public void testAuthenticatesASecondTime() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@@ -386,8 +366,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testAuthenticatesWithForcePrincipalAsString() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@@ -409,8 +388,7 @@ public class DaoAuthenticationProviderTests {
public void authenticateWhenSuccessAndPasswordManagerThenUpdates() {
String password = "password";
String encodedPassword = "encoded";
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"user", password);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", password);
PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
@@ -435,8 +413,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void authenticateWhenBadCredentialsAndPasswordManagerThenNoUpdate() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"user", "password");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
@@ -450,16 +427,14 @@ public class DaoAuthenticationProviderTests {
when(encoder.matches(any(), any())).thenReturn(false);
when(userDetailsService.loadUserByUsername(any())).thenReturn(user);
assertThatThrownBy(() -> provider.authenticate(token))
.isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> provider.authenticate(token)).isInstanceOf(BadCredentialsException.class);
verifyZeroInteractions(passwordManager);
}
@Test
public void authenticateWhenNotUpgradeAndPasswordManagerThenNoUpdate() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"user", "password");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
@@ -481,8 +456,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testDetectsNullBeingReturnedFromAuthenticationDao() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceReturnsNull());
@@ -492,9 +466,8 @@ public class DaoAuthenticationProviderTests {
fail("Should have thrown AuthenticationServiceException");
}
catch (AuthenticationServiceException expected) {
assertThat(
"UserDetailsService returned null, which is an interface contract violation").isEqualTo(
expected.getMessage());
assertThat("UserDetailsService returned null, which is an interface contract violation")
.isEqualTo(expected.getMessage());
}
}
@@ -502,12 +475,10 @@ public class DaoAuthenticationProviderTests {
public void testGettersSetters() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(new BCryptPasswordEncoder());
assertThat(provider.getPasswordEncoder().getClass()).isEqualTo(
BCryptPasswordEncoder.class);
assertThat(provider.getPasswordEncoder().getClass()).isEqualTo(BCryptPasswordEncoder.class);
provider.setUserCache(new EhCacheBasedUserCache());
assertThat(provider.getUserCache().getClass()).isEqualTo(
EhCacheBasedUserCache.class);
assertThat(provider.getUserCache().getClass()).isEqualTo(EhCacheBasedUserCache.class);
assertThat(provider.isForcePrincipalAsString()).isFalse();
provider.setForcePrincipalAsString(true);
@@ -516,8 +487,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testGoesBackToAuthenticationDaoToObtainLatestPasswordIfCachedPasswordSeemsIncorrect() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
MockUserDetailsServiceUserRod authenticationDao = new MockUserDetailsServiceUserRod();
MockUserCache cache = new MockUserCache();
@@ -540,8 +510,7 @@ public class DaoAuthenticationProviderTests {
// To get this far, the new password was accepted
// Check the cache was updated
assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo(
"easternLongNeckTurtle");
assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo("easternLongNeckTurtle");
}
@Test
@@ -594,8 +563,7 @@ public class DaoAuthenticationProviderTests {
// SEC-2056
@Test
public void testUserNotFoundEncodesPassword() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"missing", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", "koala");
PasswordEncoder encoder = mock(PasswordEncoder.class);
when(encoder.encode(anyString())).thenReturn("koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
@@ -617,15 +585,13 @@ public class DaoAuthenticationProviderTests {
@Test
public void testUserNotFoundBCryptPasswordEncoder() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"missing", "koala");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", "koala");
PasswordEncoder encoder = new BCryptPasswordEncoder();
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false);
provider.setPasswordEncoder(encoder);
MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod();
userDetailsService.password = encoder.encode(
(CharSequence) token.getCredentials());
userDetailsService.password = encoder.encode((CharSequence) token.getCredentials());
provider.setUserDetailsService(userDetailsService);
try {
provider.authenticate(token);
@@ -637,8 +603,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testUserNotFoundDefaultEncoder() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"missing", null);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", null);
DaoAuthenticationProvider provider = createProvider();
provider.setHideUserNotFoundExceptions(false);
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
@@ -656,17 +621,14 @@ public class DaoAuthenticationProviderTests {
* SEC-2056 is fixed.
*/
public void IGNOREtestSec2056() {
UsernamePasswordAuthenticationToken foundUser = new UsernamePasswordAuthenticationToken(
"rod", "koala");
UsernamePasswordAuthenticationToken notFoundUser = new UsernamePasswordAuthenticationToken(
"notFound", "koala");
UsernamePasswordAuthenticationToken foundUser = new UsernamePasswordAuthenticationToken("rod", "koala");
UsernamePasswordAuthenticationToken notFoundUser = new UsernamePasswordAuthenticationToken("notFound", "koala");
PasswordEncoder encoder = new BCryptPasswordEncoder(10, new SecureRandom());
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false);
provider.setPasswordEncoder(encoder);
MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod();
userDetailsService.password = encoder.encode(
(CharSequence) foundUser.getCredentials());
userDetailsService.password = encoder.encode((CharSequence) foundUser.getCredentials());
provider.setUserDetailsService(userDetailsService);
int sampleSize = 100;
@@ -692,10 +654,8 @@ public class DaoAuthenticationProviderTests {
double userFoundAvg = avg(userFoundTimes);
double userNotFoundAvg = avg(userNotFoundTimes);
assertThat(Math.abs(userNotFoundAvg - userFoundAvg) <= 3).withFailMessage(
"User not found average " + userNotFoundAvg
+ " should be within 3ms of user found average "
+ userFoundAvg).isTrue();
assertThat(Math.abs(userNotFoundAvg - userFoundAvg) <= 3).withFailMessage("User not found average "
+ userNotFoundAvg + " should be within 3ms of user found average " + userFoundAvg).isTrue();
}
private double avg(List<Long> counts) {
@@ -708,8 +668,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testUserNotFoundNullCredentials() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"missing", null);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", null);
PasswordEncoder encoder = mock(PasswordEncoder.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false);
@@ -733,15 +692,15 @@ public class DaoAuthenticationProviderTests {
public UserDetails loadUserByUsername(String username) {
return null;
}
}
private class MockUserDetailsServiceSimulateBackendError
implements UserDetailsService {
private class MockUserDetailsServiceSimulateBackendError implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
throw new DataRetrievalFailureException(
"This mock simulator is designed to fail");
throw new DataRetrievalFailureException("This mock simulator is designed to fail");
}
}
private class MockUserDetailsServiceUserRod implements UserDetailsService {
@@ -758,6 +717,7 @@ public class DaoAuthenticationProviderTests {
public void setPassword(String password) {
this.password = password;
}
}
private class MockUserDetailsServiceUserPeter implements UserDetailsService {
@@ -768,10 +728,10 @@ public class DaoAuthenticationProviderTests {
}
throw new UsernameNotFoundException("Could not find: " + username);
}
}
private class MockUserDetailsServiceUserPeterAccountExpired
implements UserDetailsService {
private class MockUserDetailsServiceUserPeterAccountExpired implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
if ("peter".equals(username)) {
@@ -779,10 +739,10 @@ public class DaoAuthenticationProviderTests {
}
throw new UsernameNotFoundException("Could not find: " + username);
}
}
private class MockUserDetailsServiceUserPeterAccountLocked
implements UserDetailsService {
private class MockUserDetailsServiceUserPeterAccountLocked implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
if ("peter".equals(username)) {
@@ -790,10 +750,10 @@ public class DaoAuthenticationProviderTests {
}
throw new UsernameNotFoundException("Could not find: " + username);
}
}
private class MockUserDetailsServiceUserPeterCredentialsExpired
implements UserDetailsService {
private class MockUserDetailsServiceUserPeterCredentialsExpired implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
if ("peter".equals(username)) {
@@ -801,6 +761,7 @@ public class DaoAuthenticationProviderTests {
}
throw new UsernameNotFoundException("Could not find: " + username);
}
}
private DaoAuthenticationProvider createProvider() {
@@ -808,4 +769,5 @@ public class DaoAuthenticationProviderTests {
provider.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
return provider;
}
}

View File

@@ -25,6 +25,7 @@ import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
public class MockUserCache implements UserCache {
private Map<String, UserDetails> cache = new HashMap<>();
public UserDetails getUserFromCache(String username) {
@@ -38,4 +39,5 @@ public class MockUserCache implements UserCache {
public void removeUserFromCache(String username) {
cache.remove(username);
}
}

View File

@@ -31,12 +31,13 @@ import org.springframework.security.core.AuthenticationException;
* @author Ben Alex
*/
public class AuthenticationEventTests {
// ~ Methods
// ========================================================================================================
private Authentication getAuthentication() {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"Principal", "Credentials");
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal",
"Credentials");
authentication.setDetails("127.0.0.1");
return authentication;
@@ -53,8 +54,7 @@ public class AuthenticationEventTests {
public void testAbstractAuthenticationFailureEvent() {
Authentication auth = getAuthentication();
AuthenticationException exception = new DisabledException("TEST");
AbstractAuthenticationFailureEvent event = new AuthenticationFailureDisabledEvent(
auth, exception);
AbstractAuthenticationFailureEvent event = new AuthenticationFailureDisabledEvent(auth, exception);
assertThat(event.getAuthentication()).isEqualTo(auth);
assertThat(event.getException()).isEqualTo(exception);
}
@@ -82,4 +82,5 @@ public class AuthenticationEventTests {
}
}
}

View File

@@ -27,12 +27,13 @@ import org.springframework.security.core.Authentication;
* @author Ben Alex
*/
public class LoggerListenerTests {
// ~ Methods
// ========================================================================================================
private Authentication getAuthentication() {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"Principal", "Credentials");
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("Principal",
"Credentials");
authentication.setDetails("127.0.0.1");
return authentication;
@@ -40,10 +41,11 @@ public class LoggerListenerTests {
@Test
public void testLogsEvents() {
AuthenticationFailureDisabledEvent event = new AuthenticationFailureDisabledEvent(
getAuthentication(), new LockedException("TEST"));
AuthenticationFailureDisabledEvent event = new AuthenticationFailureDisabledEvent(getAuthentication(),
new LockedException("TEST"));
LoggerListener listener = new LoggerListener();
listener.onApplicationEvent(event);
}
}

View File

@@ -53,9 +53,13 @@ import org.springframework.security.core.session.SessionDestroyedEvent;
import org.springframework.test.util.ReflectionTestUtils;
public class DefaultJaasAuthenticationProviderTests {
private DefaultJaasAuthenticationProvider provider;
private UsernamePasswordAuthenticationToken token;
private ApplicationEventPublisher publisher;
private Log log;
@Before
@@ -68,11 +72,10 @@ public class DefaultJaasAuthenticationProviderTests {
provider.setApplicationEventPublisher(publisher);
provider.setAuthorityGranters(new AuthorityGranter[] { new TestAuthorityGranter() });
provider.afterPropertiesSet();
AppConfigurationEntry[] aces = new AppConfigurationEntry[] { new AppConfigurationEntry(
TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED,
Collections.<String, Object> emptyMap()) };
when(configuration.getAppConfigurationEntry(provider.getLoginContextName()))
.thenReturn(aces);
AppConfigurationEntry[] aces = new AppConfigurationEntry[] {
new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED,
Collections.<String, Object>emptyMap()) };
when(configuration.getAppConfigurationEntry(provider.getLoginContextName())).thenReturn(aces);
token = new UsernamePasswordAuthenticationToken("user", "password");
ReflectionTestUtils.setField(provider, "log", log);
@@ -121,8 +124,7 @@ public class DefaultJaasAuthenticationProviderTests {
@Test
public void authenticateBadUser() {
try {
provider.authenticate(new UsernamePasswordAuthenticationToken("asdf",
"password"));
provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"));
fail("LoginException should have been thrown for the bad user");
}
catch (AuthenticationException success) {
@@ -245,8 +247,7 @@ public class DefaultJaasAuthenticationProviderTests {
@Test
public void javadocExample() {
String resName = "/" + getClass().getName().replace('.', '/') + ".xml";
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
resName);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(resName);
context.registerShutdownHook();
try {
provider = context.getBean(DefaultJaasAuthenticationProvider.class);
@@ -260,10 +261,12 @@ public class DefaultJaasAuthenticationProviderTests {
}
private void verifyFailedLogin() {
ArgumentCaptor<JaasAuthenticationFailedEvent> event = ArgumentCaptor.forClass(JaasAuthenticationFailedEvent.class);
ArgumentCaptor<JaasAuthenticationFailedEvent> event = ArgumentCaptor
.forClass(JaasAuthenticationFailedEvent.class);
verify(publisher).publishEvent(event.capture());
assertThat(event.getValue()).isInstanceOf(JaasAuthenticationFailedEvent.class);
assertThat(event.getValue().getException()).isNotNull();
verifyNoMoreInteractions(publisher);
}
}

View File

@@ -51,11 +51,14 @@ import org.springframework.security.core.session.SessionDestroyedEvent;
* @author Ray Krueger
*/
public class JaasAuthenticationProviderTests {
// ~ Instance fields
// ================================================================================================
private ApplicationContext context;
private JaasAuthenticationProvider jaasProvider;
private JaasEventCheck eventCheck;
// ~ Methods
@@ -66,37 +69,36 @@ public class JaasAuthenticationProviderTests {
String resName = "/" + getClass().getName().replace('.', '/') + ".xml";
context = new ClassPathXmlApplicationContext(resName);
eventCheck = (JaasEventCheck) context.getBean("eventCheck");
jaasProvider = (JaasAuthenticationProvider) context
.getBean("jaasAuthenticationProvider");
jaasProvider = (JaasAuthenticationProvider) context.getBean("jaasAuthenticationProvider");
}
@Test
public void testBadPassword() {
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user",
"asdf"));
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"));
fail("LoginException should have been thrown for the bad password");
}
catch (AuthenticationException e) {
}
assertThat(eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null").isNotNull();
assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull();
assertThat(eventCheck.successEvent).as("Success event was fired").isNull();
}
@Test
public void testBadUser() {
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf",
"password"));
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"));
fail("LoginException should have been thrown for the bad user");
}
catch (AuthenticationException e) {
}
assertThat(eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null").isNotNull();
assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull();
assertThat(eventCheck.successEvent).as("Success event was fired").isNull();
}
@@ -133,8 +135,7 @@ public class JaasAuthenticationProviderTests {
public void spacesInLoginConfigPathAreAccepted() throws Exception {
File configFile;
// Create temp directory with a space in the name
File configDir = new File(System.getProperty("java.io.tmpdir") + File.separator
+ "jaas test");
File configDir = new File(System.getProperty("java.io.tmpdir") + File.separator + "jaas test");
configDir.deleteOnExit();
if (configDir.exists()) {
@@ -145,9 +146,8 @@ public class JaasAuthenticationProviderTests {
configFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(configFile);
PrintWriter pw = new PrintWriter(fos);
pw.append("JAASTestBlah {"
+ "org.springframework.security.authentication.jaas.TestLoginModule required;"
+ "};");
pw.append(
"JAASTestBlah {" + "org.springframework.security.authentication.jaas.TestLoginModule required;" + "};");
pw.flush();
pw.close();
@@ -191,8 +191,8 @@ public class JaasAuthenticationProviderTests {
@Test
public void testFull() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"user", "password", AuthorityUtils.createAuthorityList("ROLE_ONE"));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password",
AuthorityUtils.createAuthorityList("ROLE_ONE"));
assertThat(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
@@ -206,7 +206,8 @@ public class JaasAuthenticationProviderTests {
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_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;
@@ -214,7 +215,8 @@ public class JaasAuthenticationProviderTests {
for (GrantedAuthority a : list) {
if (a instanceof JaasGrantedAuthority) {
JaasGrantedAuthority grant = (JaasGrantedAuthority) a;
assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority").isNotNull();
assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority")
.isNotNull();
foundit = true;
}
}
@@ -222,7 +224,8 @@ public class JaasAuthenticationProviderTests {
assertThat(foundit).as("Could not find a JaasGrantedAuthority").isTrue();
assertThat(eventCheck.successEvent).as("Success event should be fired").isNotNull();
assertThat(eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal").isEqualTo(auth);
assertThat(eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal")
.isEqualTo(auth);
assertThat(eventCheck.failedEvent).as("Failure event should not be fired").isNull();
}
@@ -237,8 +240,7 @@ public class JaasAuthenticationProviderTests {
jaasProvider.setLoginExceptionResolver(e -> new LockedException("This is just a test!"));
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user",
"password"));
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
catch (LockedException e) {
}
@@ -249,11 +251,9 @@ public class JaasAuthenticationProviderTests {
@Test
public void testLogout() throws Exception {
MockLoginContext loginContext = new MockLoginContext(
jaasProvider.getLoginContextName());
MockLoginContext loginContext = new MockLoginContext(jaasProvider.getLoginContextName());
JaasAuthenticationToken token = new JaasAuthenticationToken(null, null,
loginContext);
JaasAuthenticationToken token = new JaasAuthenticationToken(null, null, loginContext);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(token);
@@ -268,26 +268,27 @@ public class JaasAuthenticationProviderTests {
@Test
public void testNullDefaultAuthorities() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"user", "password");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
assertThat(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
Authentication auth = jaasProvider.authenticate(token);
assertThat(auth
.getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned").hasSize(2);
assertThat(auth.getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned")
.hasSize(2);
}
@Test
public void testUnsupportedAuthenticationObjectReturnsNull() {
assertThat(jaasProvider.authenticate(new TestingAuthenticationToken("foo", "bar",
AuthorityUtils.NO_AUTHORITIES))).isNull();
assertThat(
jaasProvider.authenticate(new TestingAuthenticationToken("foo", "bar", AuthorityUtils.NO_AUTHORITIES)))
.isNull();
}
// ~ Inner Classes
// ==================================================================================================
private static class MockLoginContext extends LoginContext {
boolean loggedOut = false;
MockLoginContext(String loginModule) throws LoginException {
@@ -297,5 +298,7 @@ public class JaasAuthenticationProviderTests {
public void logout() {
this.loggedOut = true;
}
}
}

View File

@@ -25,10 +25,12 @@ import org.springframework.security.authentication.jaas.event.JaasAuthentication
* @author Ray Krueger
*/
public class JaasEventCheck implements ApplicationListener<JaasAuthenticationEvent> {
// ~ Instance fields
// ================================================================================================
JaasAuthenticationFailedEvent failedEvent;
JaasAuthenticationSuccessEvent successEvent;
// ~ Methods
@@ -43,4 +45,5 @@ public class JaasEventCheck implements ApplicationListener<JaasAuthenticationEve
successEvent = (JaasAuthenticationSuccessEvent) event;
}
}
}

View File

@@ -22,7 +22,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.springframework.security.authentication.jaas.JaasGrantedAuthority;
/**
*
* @author Clement Ng
*
*/
@@ -32,8 +31,7 @@ public class JaasGrantedAuthorityTests {
*/
@Test
public void authorityWithNullRoleFailsAssertion() {
assertThatThrownBy(() -> new JaasGrantedAuthority(null, null))
.isInstanceOf(IllegalArgumentException.class)
assertThatThrownBy(() -> new JaasGrantedAuthority(null, null)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("role cannot be null");
}
@@ -41,8 +39,8 @@ public class JaasGrantedAuthorityTests {
*/
@Test
public void authorityWithNullPrincipleFailsAssertion() {
assertThatThrownBy(() -> new JaasGrantedAuthority("role", null))
.isInstanceOf(IllegalArgumentException.class)
assertThatThrownBy(() -> new JaasGrantedAuthority("role", null)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("principal cannot be null");
}
}

View File

@@ -37,36 +37,31 @@ import org.springframework.security.core.authority.AuthorityUtils;
public class Sec760Tests {
public String resolveConfigFile(String filename) {
String resName = "/" + getClass().getPackage().getName().replace('.', '/')
+ filename;
String resName = "/" + getClass().getPackage().getName().replace('.', '/') + filename;
return resName;
}
private void testConfigureJaasCase(JaasAuthenticationProvider p1,
JaasAuthenticationProvider p2) throws Exception {
private void testConfigureJaasCase(JaasAuthenticationProvider p1, JaasAuthenticationProvider p2) throws Exception {
p1.setLoginConfig(new ClassPathResource(resolveConfigFile("/test1.conf")));
p1.setLoginContextName("test1");
p1.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] {
new TestCallbackHandler(), new JaasNameCallbackHandler(),
new JaasPasswordCallbackHandler() });
p1.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] { new TestCallbackHandler(),
new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler() });
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(), new JaasNameCallbackHandler(),
new JaasPasswordCallbackHandler() });
p2.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] { new TestCallbackHandler(),
new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler() });
p2.setAuthorityGranters(new AuthorityGranter[] { new TestAuthorityGranter() });
p2.afterPropertiesSet();
testAuthenticate(p2);
}
private void testAuthenticate(JaasAuthenticationProvider p1) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"user", "password", AuthorityUtils.createAuthorityList("ROLE_ONE",
"ROLE_TWO"));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
Authentication auth = p1.authenticate(token);
assertThat(auth).isNotNull();
@@ -74,8 +69,7 @@ public class Sec760Tests {
@Test
public void testConfigureJaas() throws Exception {
testConfigureJaasCase(new JaasAuthenticationProvider(),
new JaasAuthenticationProvider());
testConfigureJaasCase(new JaasAuthenticationProvider(), new JaasAuthenticationProvider());
}
}

View File

@@ -39,14 +39,16 @@ import static org.assertj.core.api.Assertions.fail;
* @author Ray Krueger
*/
public class SecurityContextLoginModuleTests {
// ~ Instance fields
// ================================================================================================
private SecurityContextLoginModule module = null;
private Subject subject = new Subject(false, new HashSet<>(),
new HashSet<>(), new HashSet<>());
private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
"principal", "credentials");
private Subject subject = new Subject(false, new HashSet<>(), new HashSet<>(), new HashSet<>());
private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("principal",
"credentials");
// ~ Methods
// ========================================================================================================
@@ -66,8 +68,7 @@ public class SecurityContextLoginModuleTests {
@Test
public void testAbort() throws Exception {
assertThat(this.module.abort()).as("Should return false, no auth is set")
.isFalse();
assertThat(this.module.abort()).as("Should return false, no auth is set").isFalse();
SecurityContextHolder.getContext().setAuthentication(this.auth);
this.module.login();
this.module.commit();
@@ -87,11 +88,8 @@ public class SecurityContextLoginModuleTests {
@Test
public void testLoginSuccess() throws Exception {
SecurityContextHolder.getContext().setAuthentication(this.auth);
assertThat(this.module.login())
.as("Login should succeed, there is an authentication set").isTrue();
assertThat(this.module.commit())
.withFailMessage(
"The authentication is not null, this should return true")
assertThat(this.module.login()).as("Login should succeed, there is an authentication set").isTrue();
assertThat(this.module.commit()).withFailMessage("The authentication is not null, this should return true")
.isTrue();
assertThat(this.subject.getPrincipals().contains(this.auth))
.withFailMessage("Principals should contain the authentication").isTrue();
@@ -102,13 +100,10 @@ public class SecurityContextLoginModuleTests {
SecurityContextHolder.getContext().setAuthentication(this.auth);
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.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();
.withFailMessage("Principals should not contain the authentication after logout").isFalse();
}
@Test
@@ -131,12 +126,12 @@ public class SecurityContextLoginModuleTests {
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();
assertThat(this.module.login()).as("Should return false and ask to be ignored").isFalse();
}
@Test
public void testNullLogout() throws Exception {
assertThat(this.module.logout()).isFalse();
}
}

View File

@@ -24,10 +24,10 @@ import java.util.Set;
import org.springframework.security.authentication.jaas.AuthorityGranter;
/**
*
* @author Ray Krueger
*/
public class TestAuthorityGranter implements AuthorityGranter {
// ~ Methods
// ========================================================================================================
@@ -41,4 +41,5 @@ public class TestAuthorityGranter implements AuthorityGranter {
return rtnSet;
}
}

View File

@@ -28,6 +28,7 @@ import javax.security.auth.callback.TextInputCallback;
* @author Ray Krueger
*/
public class TestCallbackHandler implements JaasAuthenticationCallbackHandler {
// ~ Methods
// ========================================================================================================
@@ -37,4 +38,5 @@ public class TestCallbackHandler implements JaasAuthenticationCallbackHandler {
tic.setText(auth.getPrincipal().toString());
}
}
}

View File

@@ -27,11 +27,14 @@ import javax.security.auth.spi.LoginModule;
* @author Ray Krueger
*/
public class TestLoginModule implements LoginModule {
// ~ Instance fields
// ================================================================================================
private String password;
private String user;
private Subject subject;
// ~ Methods
@@ -46,8 +49,7 @@ public class TestLoginModule implements LoginModule {
}
@SuppressWarnings("unchecked")
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map sharedState, Map options) {
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
this.subject = subject;
try {
@@ -55,8 +57,7 @@ public class TestLoginModule implements LoginModule {
NameCallback nameCallback = new NameCallback("prompt");
PasswordCallback passwordCallback = new PasswordCallback("prompt", false);
callbackHandler.handle(new Callback[] { textCallback, nameCallback,
passwordCallback });
callbackHandler.handle(new Callback[] { textCallback, nameCallback, passwordCallback });
password = new String(passwordCallback.getPassword());
user = nameCallback.getName();
@@ -85,4 +86,5 @@ public class TestLoginModule implements LoginModule {
public boolean logout() {
return true;
}
}

View File

@@ -37,25 +37,22 @@ import static org.assertj.core.api.Assertions.assertThat;
public class InMemoryConfigurationTests {
private AppConfigurationEntry[] defaultEntries;
private Map<String, AppConfigurationEntry[]> mappedEntries;
@Before
public void setUp() {
this.defaultEntries = new AppConfigurationEntry[] { new AppConfigurationEntry(
TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED,
Collections.<String, Object>emptyMap()) };
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()) });
this.mappedEntries = Collections.<String, AppConfigurationEntry[]>singletonMap("name",
new AppConfigurationEntry[] { new AppConfigurationEntry(TestLoginModule.class.getName(),
LoginModuleControlFlag.OPTIONAL, Collections.<String, Object>emptyMap()) });
}
@Test
public void constructorNullDefault() {
assertThat(new InMemoryConfiguration((AppConfigurationEntry[]) null)
.getAppConfigurationEntry("name")).isNull();
assertThat(new InMemoryConfiguration((AppConfigurationEntry[]) null).getAppConfigurationEntry("name")).isNull();
}
@Test(expected = IllegalArgumentException.class)
@@ -65,16 +62,14 @@ public class InMemoryConfigurationTests {
@Test
public void constructorEmptyMap() {
assertThat(new InMemoryConfiguration(
Collections.<String, AppConfigurationEntry[]>emptyMap())
.getAppConfigurationEntry("name")).isNull();
assertThat(new InMemoryConfiguration(Collections.<String, AppConfigurationEntry[]>emptyMap())
.getAppConfigurationEntry("name")).isNull();
}
@Test
public void constructorEmptyMapNullDefault() {
assertThat(new InMemoryConfiguration(
Collections.<String, AppConfigurationEntry[]>emptyMap(), null)
.getAppConfigurationEntry("name")).isNull();
assertThat(new InMemoryConfiguration(Collections.<String, AppConfigurationEntry[]>emptyMap(), null)
.getAppConfigurationEntry("name")).isNull();
}
@Test(expected = IllegalArgumentException.class)
@@ -84,20 +79,15 @@ public class InMemoryConfigurationTests {
@Test
public void nonnullDefault() {
InMemoryConfiguration configuration = new InMemoryConfiguration(
this.defaultEntries);
assertThat(configuration.getAppConfigurationEntry("name"))
.isEqualTo(this.defaultEntries);
InMemoryConfiguration configuration = new InMemoryConfiguration(this.defaultEntries);
assertThat(configuration.getAppConfigurationEntry("name")).isEqualTo(this.defaultEntries);
}
@Test
public void mappedNonnullDefault() {
InMemoryConfiguration configuration = new InMemoryConfiguration(
this.mappedEntries, this.defaultEntries);
assertThat(this.defaultEntries)
.isEqualTo(configuration.getAppConfigurationEntry("missing"));
assertThat(this.mappedEntries.get("name"))
.isEqualTo(configuration.getAppConfigurationEntry("name"));
InMemoryConfiguration configuration = new InMemoryConfiguration(this.mappedEntries, this.defaultEntries);
assertThat(this.defaultEntries).isEqualTo(configuration.getAppConfigurationEntry("missing"));
assertThat(this.mappedEntries.get("name")).isEqualTo(configuration.getAppConfigurationEntry("name"));
}
@Test
@@ -105,4 +95,5 @@ public class InMemoryConfigurationTests {
Method method = InMemoryConfiguration.class.getDeclaredMethod("refresh");
assertThat(method.getDeclaringClass()).isEqualTo(InMemoryConfiguration.class);
}
}

View File

@@ -31,6 +31,7 @@ import org.springframework.security.core.Authentication;
* @author Ben Alex
*/
public class RemoteAuthenticationManagerImplTests {
// ~ Methods
// ========================================================================================================
@@ -38,8 +39,7 @@ public class RemoteAuthenticationManagerImplTests {
public void testFailedAuthenticationReturnsRemoteAuthenticationException() {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(
new BadCredentialsException(""));
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
manager.setAuthenticationManager(am);
manager.attemptAuthentication("rod", "password");
@@ -65,10 +65,10 @@ public class RemoteAuthenticationManagerImplTests {
public void testSuccessfulAuthentication() {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenReturn(
new TestingAuthenticationToken("u", "p", "A"));
when(am.authenticate(any(Authentication.class))).thenReturn(new TestingAuthenticationToken("u", "p", "A"));
manager.setAuthenticationManager(am);
manager.attemptAuthentication("rod", "password");
}
}

View File

@@ -34,18 +34,17 @@ import static org.assertj.core.api.Assertions.fail;
* @author Ben Alex
*/
public class RemoteAuthenticationProviderTests {
// ~ Methods
// ========================================================================================================
@Test
public void testExceptionsGetPassedBackToCaller() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(
new MockRemoteAuthenticationManager(false));
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
try {
provider.authenticate(
new UsernamePasswordAuthenticationToken("rod", "password"));
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
fail("Should have thrown RemoteAuthenticationException");
}
catch (RemoteAuthenticationException expected) {
@@ -56,8 +55,7 @@ public class RemoteAuthenticationProviderTests {
@Test
public void testGettersSetters() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(
new MockRemoteAuthenticationManager(true));
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true));
assertThat(provider.getRemoteAuthenticationManager()).isNotNull();
}
@@ -73,8 +71,7 @@ public class RemoteAuthenticationProviderTests {
}
provider.setRemoteAuthenticationManager(
new MockRemoteAuthenticationManager(true));
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true));
provider.afterPropertiesSet();
}
@@ -82,11 +79,9 @@ public class RemoteAuthenticationProviderTests {
@Test
public void testSuccessfulAuthenticationCreatesObject() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(
new MockRemoteAuthenticationManager(true));
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true));
Authentication result = provider
.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
Authentication result = provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
assertThat(result.getPrincipal()).isEqualTo("rod");
assertThat(result.getCredentials()).isEqualTo("password");
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains("foo");
@@ -95,8 +90,7 @@ public class RemoteAuthenticationProviderTests {
@Test
public void testNullCredentialsDoesNotCauseNullPointerException() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(
new MockRemoteAuthenticationManager(false));
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
try {
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", null));
@@ -117,14 +111,15 @@ public class RemoteAuthenticationProviderTests {
// ==================================================================================================
private class MockRemoteAuthenticationManager implements RemoteAuthenticationManager {
private boolean grantAccess;
MockRemoteAuthenticationManager(boolean grantAccess) {
this.grantAccess = grantAccess;
}
public Collection<? extends GrantedAuthority> attemptAuthentication(
String username, String password) throws RemoteAuthenticationException {
public Collection<? extends GrantedAuthority> attemptAuthentication(String username, String password)
throws RemoteAuthenticationException {
if (this.grantAccess) {
return AuthorityUtils.createAuthorityList("foo");
}
@@ -132,5 +127,7 @@ public class RemoteAuthenticationProviderTests {
throw new RemoteAuthenticationException("as requested");
}
}
}
}

View File

@@ -34,15 +34,14 @@ import static org.assertj.core.api.Assertions.fail;
* @author Ben Alex
*/
public class RememberMeAuthenticationProviderTests {
// ~ Methods
// ========================================================================================================
@Test
public void testDetectsAnInvalidKey() {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(
"WRONG_KEY", "Test",
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("WRONG_KEY", "Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
try {
@@ -66,19 +65,16 @@ public class RememberMeAuthenticationProviderTests {
@Test
public void testGettersSetters() throws Exception {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
aap.afterPropertiesSet();
assertThat(aap.getKey()).isEqualTo("qwerty");
}
@Test
public void testIgnoresClassesItDoesNotSupport() {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
TestingAuthenticationToken token = new TestingAuthenticationToken("user",
"password", "ROLE_A");
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password", "ROLE_A");
assertThat(aap.supports(TestingAuthenticationToken.class)).isFalse();
// Try it anyway
@@ -87,11 +83,10 @@ public class RememberMeAuthenticationProviderTests {
@Test
public void testNormalOperation() {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("qwerty",
"Test", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("qwerty", "Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
Authentication result = aap.authenticate(token);
@@ -100,9 +95,9 @@ public class RememberMeAuthenticationProviderTests {
@Test
public void testSupports() {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
assertThat(aap.supports(RememberMeAuthenticationToken.class)).isTrue();
assertThat(aap.supports(TestingAuthenticationToken.class)).isFalse();
}
}

View File

@@ -16,7 +16,6 @@
package org.springframework.security.authentication.rememberme;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
@@ -34,8 +33,8 @@ import org.springframework.security.core.authority.AuthorityUtils;
* @author Ben Alex
*/
public class RememberMeAuthenticationTokenTests {
private static final List<GrantedAuthority> ROLES_12 = AuthorityUtils
.createAuthorityList("ROLE_ONE", "ROLE_TWO");
private static final List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
// ~ Methods
// ========================================================================================================
@@ -70,18 +69,15 @@ public class RememberMeAuthenticationTokenTests {
@Test
public void testEqualsWhenEqual() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
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);
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
assertThat(token.getPrincipal()).isEqualTo("Test");
@@ -93,40 +89,36 @@ public class RememberMeAuthenticationTokenTests {
@Test
public void testNotEqualsDueToAbstractParentEqualsCheck() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("key",
"DIFFERENT_PRINCIPAL", ROLES_12);
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("key", "DIFFERENT_PRINCIPAL",
ROLES_12);
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testNotEqualsDueToDifferentAuthenticationClass() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken(
"Test", "Password", ROLES_12);
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
ROLES_12);
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testNotEqualsDueToKey() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken(
"DIFFERENT_KEY", "Test", ROLES_12);
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("DIFFERENT_KEY", "Test", ROLES_12);
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testSetAuthenticatedIgnored() {
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key", "Test", ROLES_12);
assertThat(token.isAuthenticated()).isTrue();
token.setAuthenticated(false);
assertThat(!token.isAuthenticated()).isTrue();
}
}

View File

@@ -35,11 +35,12 @@ import static org.mockito.Mockito.when;
*/
@RunWith(MockitoJUnitRunner.class)
public class AuthenticatedReactiveAuthorizationManagerTests {
@Mock
Authentication authentication;
AuthenticatedReactiveAuthorizationManager<Object> manager = AuthenticatedReactiveAuthorizationManager
.authenticated();
.authenticated();
@Test
public void checkWhenAuthenticatedThenReturnTrue() {
@@ -77,9 +78,7 @@ public class AuthenticatedReactiveAuthorizationManagerTests {
public void checkWhenErrorThenError() {
Mono<AuthorizationDecision> result = manager.check(Mono.error(new RuntimeException("ooops")), null);
StepVerifier
.create(result)
.expectError()
.verify();
StepVerifier.create(result).expectError().verify();
}
}

View File

@@ -36,11 +36,11 @@ import static org.mockito.Mockito.when;
*/
@RunWith(MockitoJUnitRunner.class)
public class AuthorityReactiveAuthorizationManagerTests {
@Mock
Authentication authentication;
AuthorityReactiveAuthorizationManager<Object> manager = AuthorityReactiveAuthorizationManager
.hasAuthority("ADMIN");
AuthorityReactiveAuthorizationManager<Object> manager = AuthorityReactiveAuthorizationManager.hasAuthority("ADMIN");
@Test
public void checkWhenHasAuthorityAndNotAuthenticatedThenReturnFalse() {
@@ -60,10 +60,7 @@ public class AuthorityReactiveAuthorizationManagerTests {
public void checkWhenHasAuthorityAndErrorThenError() {
Mono<AuthorizationDecision> result = manager.check(Mono.error(new RuntimeException("ooops")), null);
StepVerifier
.create(result)
.expectError()
.verify();
StepVerifier.create(result).expectError().verify();
}
@Test
@@ -171,4 +168,5 @@ public class AuthorityReactiveAuthorizationManagerTests {
String authority2 = null;
AuthorityReactiveAuthorizationManager.hasAnyAuthority(authority1, authority2);
}
}

View File

@@ -39,10 +39,12 @@ import org.mockito.Mock;
* @see CurrentDelegatingSecurityContextExecutorServiceTests
* @see ExplicitDelegatingSecurityContextExecutorServiceTests
*/
public abstract class AbstractDelegatingSecurityContextExecutorServiceTests extends
AbstractDelegatingSecurityContextExecutorTests {
public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
extends AbstractDelegatingSecurityContextExecutorTests {
@Mock
private Future<Object> expectedFutureObject;
@Mock
private Object resultArg;
@@ -89,8 +91,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests exte
public void awaitTermination() throws InterruptedException {
boolean result = executor.awaitTermination(1, TimeUnit.SECONDS);
verify(delegate).awaitTermination(1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(delegate.awaitTermination(1, TimeUnit.SECONDS))
.isNotNull();
assertThat(result).isEqualTo(delegate.awaitTermination(1, TimeUnit.SECONDS)).isNotNull();
}
@Test
@@ -103,8 +104,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests exte
@Test
public void submitRunnableWithResult() {
when(delegate.submit(wrappedRunnable, resultArg))
.thenReturn(expectedFutureObject);
when(delegate.submit(wrappedRunnable, resultArg)).thenReturn(expectedFutureObject);
Future<Object> result = executor.submit(runnable, resultArg);
verify(delegate).submit(wrappedRunnable, resultArg);
assertThat(result).isEqualTo(expectedFutureObject);
@@ -113,8 +113,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests exte
@Test
@SuppressWarnings("unchecked")
public void submitRunnable() {
when((Future<Object>) delegate.submit(wrappedRunnable)).thenReturn(
expectedFutureObject);
when((Future<Object>) delegate.submit(wrappedRunnable)).thenReturn(expectedFutureObject);
Future<?> result = executor.submit(runnable);
verify(delegate).submit(wrappedRunnable);
assertThat(result).isEqualTo(expectedFutureObject);
@@ -136,10 +135,8 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests exte
public void invokeAllTimeout() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
when(delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(
exectedResult);
List<Future<Object>> result = executor.invokeAll(Arrays.asList(callable), 1,
TimeUnit.SECONDS);
when(delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
List<Future<Object>> result = executor.invokeAll(Arrays.asList(callable), 1, TimeUnit.SECONDS);
verify(delegate).invokeAll(wrappedCallables, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(exectedResult);
}
@@ -160,12 +157,12 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests exte
public void invokeAnyTimeout() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
when(delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(
exectedResult);
when(delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
Object result = executor.invokeAny(Arrays.asList(callable), 1, TimeUnit.SECONDS);
verify(delegate).invokeAny(wrappedCallables, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(exectedResult);
}
protected abstract DelegatingSecurityContextExecutorService create();
}

View File

@@ -33,8 +33,9 @@ import org.mockito.Mock;
* @see CurrentDelegatingSecurityContextExecutorTests
* @see ExplicitDelegatingSecurityContextExecutorTests
*/
public abstract class AbstractDelegatingSecurityContextExecutorTests extends
AbstractDelegatingSecurityContextTestSupport {
public abstract class AbstractDelegatingSecurityContextExecutorTests
extends AbstractDelegatingSecurityContextTestSupport {
@Mock
protected ScheduledExecutorService delegate;
@@ -61,4 +62,5 @@ public abstract class AbstractDelegatingSecurityContextExecutorTests extends
}
protected abstract DelegatingSecurityContextExecutor create();
}

View File

@@ -38,6 +38,7 @@ import org.mockito.Mock;
*/
public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceTests
extends AbstractDelegatingSecurityContextExecutorServiceTests {
@Mock
private ScheduledFuture<Object> expectedResult;
@@ -51,9 +52,8 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
@SuppressWarnings("unchecked")
public void scheduleRunnable() {
when(
(ScheduledFuture<Object>) delegate.schedule(wrappedRunnable, 1,
TimeUnit.SECONDS)).thenReturn(expectedResult);
when((ScheduledFuture<Object>) delegate.schedule(wrappedRunnable, 1, TimeUnit.SECONDS))
.thenReturn(expectedResult);
ScheduledFuture<?> result = executor.schedule(runnable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(expectedResult);
verify(delegate).schedule(wrappedRunnable, 1, TimeUnit.SECONDS);
@@ -61,9 +61,7 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
public void scheduleCallable() {
when(
delegate.schedule(wrappedCallable, 1,
TimeUnit.SECONDS)).thenReturn(expectedResult);
when(delegate.schedule(wrappedCallable, 1, TimeUnit.SECONDS)).thenReturn(expectedResult);
ScheduledFuture<Object> result = executor.schedule(callable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(expectedResult);
verify(delegate).schedule(wrappedCallable, 1, TimeUnit.SECONDS);
@@ -72,11 +70,9 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
@SuppressWarnings("unchecked")
public void scheduleAtFixedRate() {
when(
(ScheduledFuture<Object>) delegate.scheduleAtFixedRate(wrappedRunnable,
1, 2, TimeUnit.SECONDS)).thenReturn(expectedResult);
ScheduledFuture<?> result = executor.scheduleAtFixedRate(runnable, 1, 2,
TimeUnit.SECONDS);
when((ScheduledFuture<Object>) delegate.scheduleAtFixedRate(wrappedRunnable, 1, 2, TimeUnit.SECONDS))
.thenReturn(expectedResult);
ScheduledFuture<?> result = executor.scheduleAtFixedRate(runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(expectedResult);
verify(delegate).scheduleAtFixedRate(wrappedRunnable, 1, 2, TimeUnit.SECONDS);
}
@@ -84,16 +80,14 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
@SuppressWarnings("unchecked")
public void scheduleWithFixedDelay() {
when(
(ScheduledFuture<Object>) delegate.scheduleWithFixedDelay(
wrappedRunnable, 1, 2, TimeUnit.SECONDS)).thenReturn(
expectedResult);
ScheduledFuture<?> result = executor.scheduleWithFixedDelay(runnable, 1, 2,
TimeUnit.SECONDS);
when((ScheduledFuture<Object>) delegate.scheduleWithFixedDelay(wrappedRunnable, 1, 2, TimeUnit.SECONDS))
.thenReturn(expectedResult);
ScheduledFuture<?> result = executor.scheduleWithFixedDelay(runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(expectedResult);
verify(delegate).scheduleWithFixedDelay(wrappedRunnable, 1, 2, TimeUnit.SECONDS);
}
@Override
protected abstract DelegatingSecurityContextScheduledExecutorService create();
}

View File

@@ -41,9 +41,9 @@ import org.springframework.security.core.context.SecurityContextHolder;
*
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ DelegatingSecurityContextRunnable.class,
DelegatingSecurityContextCallable.class })
@PrepareForTest({ DelegatingSecurityContextRunnable.class, DelegatingSecurityContextCallable.class })
public abstract class AbstractDelegatingSecurityContextTestSupport {
@Mock
protected SecurityContext securityContext;
@@ -67,20 +67,18 @@ public abstract class AbstractDelegatingSecurityContextTestSupport {
public final void explicitSecurityContextPowermockSetup() throws Exception {
spy(DelegatingSecurityContextCallable.class);
doReturn(wrappedCallable).when(DelegatingSecurityContextCallable.class, "create",
eq(callable), securityContextCaptor.capture());
doReturn(wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", eq(callable),
securityContextCaptor.capture());
spy(DelegatingSecurityContextRunnable.class);
doReturn(wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create",
eq(runnable), securityContextCaptor.capture());
doReturn(wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", eq(runnable),
securityContextCaptor.capture());
}
public final void currentSecurityContextPowermockSetup() throws Exception {
spy(DelegatingSecurityContextCallable.class);
doReturn(wrappedCallable).when(DelegatingSecurityContextCallable.class, "create",
callable, null);
doReturn(wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", callable, null);
spy(DelegatingSecurityContextRunnable.class);
doReturn(wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create",
runnable, null);
doReturn(wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", runnable, null);
}
@Before
@@ -92,4 +90,5 @@ public abstract class AbstractDelegatingSecurityContextTestSupport {
public final void clearContext() {
SecurityContextHolder.clearContext();
}
}

View File

@@ -25,8 +25,8 @@ import org.junit.Before;
* @since 3.2
*
*/
public class CurrentDelegatingSecurityContextExecutorServiceTests extends
AbstractDelegatingSecurityContextExecutorServiceTests {
public class CurrentDelegatingSecurityContextExecutorServiceTests
extends AbstractDelegatingSecurityContextExecutorServiceTests {
@Before
public void setUp() throws Exception {
@@ -37,4 +37,5 @@ public class CurrentDelegatingSecurityContextExecutorServiceTests extends
protected DelegatingSecurityContextExecutorService create() {
return new DelegatingSecurityContextExecutorService(delegate);
}
}

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