Remove blank lines from all tests

Remove all blank lines from test code so that test methods are
visually grouped together. This generally helps to make the test
classes easer to scan, however, the "given" / "when" / "then"
blocks used by some tests are now not as easy to discern.

Issue gh-8945
This commit is contained in:
Phillip Webb 2020-08-01 19:33:21 -07:00 committed by Rob Winch
parent 5bdd757108
commit a5aa6b3d7f
787 changed files with 9 additions and 10241 deletions

View File

@ -39,21 +39,18 @@ public class AclFormattingUtilsTests {
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH");
}
@ -68,7 +65,6 @@ public class AclFormattingUtilsTests {
String removeBits = "...............................R";
assertThat(AclFormattingUtils.demergePatterns(original, removeBits))
.isEqualTo("...........................A....");
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF");
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo("......");
}
@ -81,21 +77,18 @@ public class AclFormattingUtilsTests {
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH");
}
@ -108,7 +101,6 @@ public class AclFormattingUtilsTests {
String original = "...............................R";
String extraBits = "...........................A....";
assertThat(AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo("...........................A...R");
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF");
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")).isEqualTo("GHIJKL");
}
@ -116,21 +108,18 @@ public class AclFormattingUtilsTests {
@Test
public final void testBinaryPrints() {
assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****");
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
}
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
}
assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx");
}

View File

@ -54,9 +54,7 @@ public class AclPermissionCacheOptimizerTests {
ObjectIdentity[] oids = { new ObjectIdentityImpl("A", "1"), new ObjectIdentityImpl("A", "2") };
given(oidStrat.getObjectIdentity(dos[0])).willReturn(oids[0]);
given(oidStrat.getObjectIdentity(dos[2])).willReturn(oids[1]);
pco.cachePermissionsFor(mock(Authentication.class), Arrays.asList(dos));
// AclService should be invoked with the list of required Oids
verify(service).readAclsById(eq(Arrays.asList(oids)), any(List.class));
}
@ -69,9 +67,7 @@ public class AclPermissionCacheOptimizerTests {
SidRetrievalStrategy sids = mock(SidRetrievalStrategy.class);
pco.setObjectIdentityRetrievalStrategy(oids);
pco.setSidRetrievalStrategy(sids);
pco.cachePermissionsFor(mock(Authentication.class), Collections.emptyList());
verifyZeroInteractions(service, sids, oids);
}

View File

@ -50,10 +50,8 @@ public class AclPermissionEvaluatorTests {
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
}
@ -61,7 +59,6 @@ public class AclPermissionEvaluatorTests {
public void resolvePermissionNonEnglishLocale() {
Locale systemLocale = Locale.getDefault();
Locale.setDefault(new Locale("tr"));
AclService service = mock(AclService.class);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
@ -70,12 +67,9 @@ public class AclPermissionEvaluatorTests {
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();
Locale.setDefault(systemLocale);
}

View File

@ -58,7 +58,6 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"),
new ArrayList(Arrays.asList(new Object(), new Object())));
@ -76,7 +75,6 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(
mock(AclService.class), Arrays.asList(mock(Permission.class)));
Object returned = new Object();
assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(),
Collections.<ConfigAttribute>emptyList(), returned));
}
@ -86,7 +84,6 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
AclService service = mock(AclService.class);
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(
service, Arrays.asList(mock(Permission.class)));
assertThat(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null)).isNull();
verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class));

View File

@ -74,7 +74,6 @@ public class AclEntryAfterInvocationProviderTests {
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = new Object();
assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
@ -84,7 +83,6 @@ public class AclEntryAfterInvocationProviderTests {
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(mock(AclService.class),
Arrays.asList(mock(Permission.class)));
Object returned = new Object();
assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(),
Collections.<ConfigAttribute>emptyList(), returned));
}
@ -96,7 +94,6 @@ public class AclEntryAfterInvocationProviderTests {
provider.setProcessDomainObjectClass(String.class);
// Not a String
Object returned = new Object();
assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
@ -133,7 +130,6 @@ public class AclEntryAfterInvocationProviderTests {
AclService service = mock(AclService.class);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service,
Arrays.asList(mock(Permission.class)));
assertThat(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null)).isNull();
verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class));

View File

@ -46,7 +46,6 @@ public class AccessControlImplEntryTests {
}
catch (IllegalArgumentException expected) {
}
// Check Sid field is present
try {
new AccessControlEntryImpl(null, mock(Acl.class), null, BasePermission.ADMINISTRATION, true, true, true);
@ -54,7 +53,6 @@ public class AccessControlImplEntryTests {
}
catch (IllegalArgumentException expected) {
}
// Check Permission field is present
try {
new AccessControlEntryImpl(null, mock(Acl.class), new PrincipalSid("johndoe"), null, true, true, true);
@ -68,11 +66,9 @@ public class AccessControlImplEntryTests {
public void testAccessControlEntryImplGetters() {
Acl mockAcl = mock(Acl.class);
Sid sid = new PrincipalSid("johndoe");
// Create a sample entry
AccessControlEntry ace = new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true,
true);
// and check every get() method
assertThat(ace.getId()).isEqualTo(1L);
assertThat(ace.getAcl()).isEqualTo(mockAcl);
@ -87,13 +83,10 @@ public class AccessControlImplEntryTests {
public void testEquals() {
final Acl mockAcl = mock(Acl.class);
final ObjectIdentity oid = mock(ObjectIdentity.class);
given(mockAcl.getObjectIdentity()).willReturn(oid);
Sid sid = new PrincipalSid("johndoe");
AccessControlEntry ace = new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true,
true);
assertThat(ace).isNotNull();
assertThat(ace).isNotEqualTo(100L);
assertThat(ace).isEqualTo(ace);

View File

@ -156,7 +156,6 @@ public class AclImplTests {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
MockAclService service = new MockAclService();
// Insert one permission
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
service.updateAcl(acl);
@ -165,7 +164,6 @@ public class AclImplTests {
assertThat(acl).isEqualTo(acl.getEntries().get(0).getAcl());
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission());
assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST1"));
// Add a second permission
acl.insertAce(1, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
service.updateAcl(acl);
@ -174,7 +172,6 @@ public class AclImplTests {
assertThat(acl).isEqualTo(acl.getEntries().get(1).getAcl());
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(1).getPermission());
assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2"));
// Add a third permission, after the first one
acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_TEST3"), false);
service.updateAcl(acl);
@ -193,11 +190,9 @@ public class AclImplTests {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
MockAclService service = new MockAclService();
// Insert one permission
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
service.updateAcl(acl);
acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
}
@ -206,20 +201,17 @@ public class AclImplTests {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
MockAclService service = new MockAclService();
// Add several permissions
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
acl.insertAce(1, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
acl.insertAce(2, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST3"), true);
service.updateAcl(acl);
// Delete first permission and check the order of the remaining permissions is
// kept
acl.deleteAce(0);
assertThat(acl.getEntries()).hasSize(2);
assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2"));
assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST3"));
// Add one more permission and remove the permission in the middle
acl.insertAce(2, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST4"), true);
service.updateAcl(acl);
@ -227,7 +219,6 @@ public class AclImplTests {
assertThat(acl.getEntries()).hasSize(2);
assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2"));
assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST4"));
// Remove remaining permissions
acl.deleteAce(1);
acl.deleteAce(0);
@ -274,17 +265,14 @@ public class AclImplTests {
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity rootOid = new ObjectIdentityImpl(TARGET_CLASS, 100);
// Create an ACL which owner is not the authenticated principal
MutableAcl rootAcl = new AclImpl(rootOid, 1, this.authzStrategy, this.pgs, null, null, false,
new PrincipalSid("joe"));
// Grant some permissions
rootAcl.insertAce(0, BasePermission.READ, new PrincipalSid("ben"), false);
rootAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid("scott"), true);
rootAcl.insertAce(2, BasePermission.WRITE, new PrincipalSid("rod"), false);
rootAcl.insertAce(3, BasePermission.WRITE, new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), true);
// Check permissions granting
List<Permission> permissions = Arrays.asList(BasePermission.READ, BasePermission.CREATE);
List<Sid> sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST"));
@ -320,7 +308,6 @@ public class AclImplTests {
ObjectIdentity parentOid2 = new ObjectIdentityImpl(TARGET_CLASS, 102);
ObjectIdentity childOid1 = new ObjectIdentityImpl(TARGET_CLASS, 103);
ObjectIdentity childOid2 = new ObjectIdentityImpl(TARGET_CLASS, 104);
// Create ACLs
PrincipalSid joe = new PrincipalSid("joe");
MutableAcl grandParentAcl = new AclImpl(grandParentOid, 1, this.authzStrategy, this.pgs, null, null, false,
@ -329,13 +316,11 @@ public class AclImplTests {
MutableAcl parentAcl2 = new AclImpl(parentOid2, 3, this.authzStrategy, this.pgs, null, null, true, joe);
MutableAcl childAcl1 = new AclImpl(childOid1, 4, this.authzStrategy, this.pgs, null, null, true, joe);
MutableAcl childAcl2 = new AclImpl(childOid2, 4, this.authzStrategy, this.pgs, null, null, false, joe);
// Create hierarchies
childAcl2.setParent(childAcl1);
childAcl1.setParent(parentAcl1);
parentAcl2.setParent(grandParentAcl);
parentAcl1.setParent(grandParentAcl);
// Add some permissions
grandParentAcl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
grandParentAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid("ben"), true);
@ -345,7 +330,6 @@ public class AclImplTests {
parentAcl1.insertAce(1, BasePermission.DELETE, new PrincipalSid("scott"), false);
parentAcl2.insertAce(0, BasePermission.CREATE, new PrincipalSid("ben"), true);
childAcl1.insertAce(0, BasePermission.CREATE, new PrincipalSid("scott"), true);
// Check granting process for parent1
assertThat(parentAcl1.isGranted(READ, SCOTT, false)).isTrue();
assertThat(parentAcl1.isGranted(READ, Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false))
@ -353,18 +337,15 @@ public class AclImplTests {
assertThat(parentAcl1.isGranted(WRITE, BEN, false)).isTrue();
assertThat(parentAcl1.isGranted(DELETE, BEN, false)).isFalse();
assertThat(parentAcl1.isGranted(DELETE, SCOTT, false)).isFalse();
// Check granting process for parent2
assertThat(parentAcl2.isGranted(CREATE, BEN, false)).isTrue();
assertThat(parentAcl2.isGranted(WRITE, BEN, false)).isTrue();
assertThat(parentAcl2.isGranted(DELETE, BEN, false)).isFalse();
// Check granting process for child1
assertThat(childAcl1.isGranted(CREATE, SCOTT, false)).isTrue();
assertThat(childAcl1.isGranted(READ, Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false))
.isTrue();
assertThat(childAcl1.isGranted(DELETE, BEN, false)).isFalse();
// Check granting process for child2 (doesn't inherit the permissions from its
// parent)
try {
@ -389,21 +370,17 @@ public class AclImplTests {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, false,
new PrincipalSid("joe"));
MockAclService service = new MockAclService();
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
acl.insertAce(2, BasePermission.CREATE, new PrincipalSid("ben"), true);
service.updateAcl(acl);
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission());
assertThat(BasePermission.WRITE).isEqualTo(acl.getEntries().get(1).getPermission());
assertThat(BasePermission.CREATE).isEqualTo(acl.getEntries().get(2).getPermission());
// Change each permission
acl.updateAce(0, BasePermission.CREATE);
acl.updateAce(1, BasePermission.DELETE);
acl.updateAce(2, BasePermission.READ);
// Check the change was successfully made
assertThat(BasePermission.CREATE).isEqualTo(acl.getEntries().get(0).getPermission());
assertThat(BasePermission.DELETE).isEqualTo(acl.getEntries().get(1).getPermission());
@ -418,20 +395,16 @@ public class AclImplTests {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, false,
new PrincipalSid("joe"));
MockAclService service = new MockAclService();
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
service.updateAcl(acl);
assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditFailure()).isFalse();
assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditFailure()).isFalse();
assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditSuccess()).isFalse();
assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditSuccess()).isFalse();
// Change each permission
((AuditableAcl) acl).updateAuditing(0, true, true);
((AuditableAcl) acl).updateAuditing(1, true, true);
// Check the change was successfuly made
assertThat(acl.getEntries()).extracting("auditSuccess").containsOnly(true, true);
assertThat(acl.getEntries()).extracting("auditFailure").containsOnly(true, true);
@ -452,20 +425,16 @@ public class AclImplTests {
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
service.updateAcl(acl);
assertThat(1).isEqualTo(acl.getId());
assertThat(identity).isEqualTo(acl.getObjectIdentity());
assertThat(new PrincipalSid("joe")).isEqualTo(acl.getOwner());
assertThat(acl.getParentAcl()).isNull();
assertThat(acl.isEntriesInheriting()).isTrue();
assertThat(acl.getEntries()).hasSize(2);
acl.setParent(parentAcl);
assertThat(parentAcl).isEqualTo(acl.getParentAcl());
acl.setEntriesInheriting(false);
assertThat(acl.isEntriesInheriting()).isFalse();
acl.setOwner(new PrincipalSid("ben"));
assertThat(new PrincipalSid("ben")).isEqualTo(acl.getOwner());
}
@ -475,7 +444,6 @@ public class AclImplTests {
List<Sid> loadedSids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_IGNORED"));
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, loadedSids, true,
new PrincipalSid("joe"));
assertThat(acl.isSidLoaded(loadedSids)).isTrue();
assertThat(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new PrincipalSid("ben"))))
.isTrue();
@ -534,7 +502,6 @@ public class AclImplTests {
AclImpl parentAcl = new AclImpl(this.objectIdentity, 1L, this.authzStrategy, this.mockAuditLogger);
AclImpl childAcl = new AclImpl(this.objectIdentity, 2L, this.authzStrategy, this.mockAuditLogger);
AclImpl changeParentAcl = new AclImpl(this.objectIdentity, 3L, this.authzStrategy, this.mockAuditLogger);
childAcl.setParent(parentAcl);
childAcl.setParent(changeParentAcl);
}
@ -562,10 +529,8 @@ public class AclImplTests {
ObjectIdentity oid = new ObjectIdentityImpl("type", 1);
AclAuthorizationStrategy authStrategy = new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("role"));
PermissionGrantingStrategy grantingStrategy = new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger());
AclImpl acl = new AclImpl(oid, 1L, authStrategy, grantingStrategy, null, null, false, sid);
AccessControlEntryImpl ace = new AccessControlEntryImpl(1L, acl, sid, BasePermission.READ, true, true, true);
Field fieldAces = FieldUtils.getField(AclImpl.class, "aces");
fieldAces.setAccessible(true);
List<AccessControlEntryImpl> aces = (List<AccessControlEntryImpl>) fieldAces.get(acl);
@ -617,7 +582,6 @@ public class AclImplTests {
try {
newAces = (List) acesField.get(acl);
newAces.clear();
for (int i = 0; i < oldAces.size(); i++) {
AccessControlEntry ac = oldAces.get(i);
// Just give an ID to all this acl's aces, rest of the fields are just
@ -630,7 +594,6 @@ public class AclImplTests {
catch (IllegalAccessException ex) {
ex.printStackTrace();
}
return acl;
}

View File

@ -58,18 +58,14 @@ public class AclImplementationSecurityCheckTests {
"ROLE_OWNERSHIP");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL"));
Acl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL);
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING);
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
// Create another authorization strategy
AclAuthorizationStrategy aclAuthorizationStrategy2 = new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_ONE"), new SimpleGrantedAuthority("ROLE_TWO"),
@ -102,21 +98,17 @@ public class AclImplementationSecurityCheckTests {
Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L);
// Authorization strategy will require a different role for each access
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL"));
// Let's give the principal the ADMINISTRATION permission, without
// granting access
MutableAcl aclFirstDeny = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
aclFirstDeny.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
// The CHANGE_GENERAL test should pass as the principal has ROLE_GENERAL
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_GENERAL);
// The CHANGE_AUDITING and CHANGE_OWNERSHIP should fail since the
// principal doesn't have these authorities,
// nor granting access
@ -132,7 +124,6 @@ public class AclImplementationSecurityCheckTests {
}
catch (AccessDeniedException expected) {
}
// Add granting access to this principal
aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// and try again for CHANGE_AUDITING - the first ACE's granting flag
@ -143,27 +134,21 @@ public class AclImplementationSecurityCheckTests {
}
catch (AccessDeniedException expected) {
}
// Create another ACL and give the principal the ADMINISTRATION
// permission, with granting access
MutableAcl aclFirstAllow = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
aclFirstAllow.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// The CHANGE_AUDITING test should pass as there is one ACE with
// granting access
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
// Add a deny ACE and test again for CHANGE_AUDITING
aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
try {
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
}
catch (AccessDeniedException notExpected) {
fail("It shouldn't have thrown AccessDeniedException");
}
// Create an ACL with no ACE
MutableAcl aclNoACE = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
try {
@ -171,12 +156,10 @@ public class AclImplementationSecurityCheckTests {
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
// and still grant access for CHANGE_GENERAL
try {
aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL);
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
@ -189,19 +172,16 @@ public class AclImplementationSecurityCheckTests {
Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100);
// Authorization strategy will require a different role for each access
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_ONE"), new SimpleGrantedAuthority("ROLE_TWO"),
new SimpleGrantedAuthority("ROLE_GENERAL"));
// Let's give the principal an ADMINISTRATION permission, with granting
// access
MutableAcl parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
parentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
MutableAcl childAcl = new AclImpl(identity, 2, aclAuthorizationStrategy, new ConsoleAuditLogger());
// Check against the 'child' acl, which doesn't offer any authorization
// rights on CHANGE_OWNERSHIP
try {
@ -209,21 +189,17 @@ public class AclImplementationSecurityCheckTests {
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
// Link the child with its parent and test again against the
// CHANGE_OWNERSHIP right
childAcl.setParent(parentAcl);
childAcl.setEntriesInheriting(true);
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
}
// Create a root parent and link it to the middle parent
MutableAcl rootParentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
@ -233,7 +209,6 @@ public class AclImplementationSecurityCheckTests {
childAcl.setParent(parentAcl);
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
@ -245,12 +220,10 @@ public class AclImplementationSecurityCheckTests {
Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_ONE");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL"));
Acl acl = new AclImpl(identity, 1, aclAuthorizationStrategy,
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false,
new PrincipalSid(auth));

View File

@ -76,7 +76,6 @@ public class AuditLoggerTests {
@Test
public void successIsLoggedIfAceRequiresSuccessAudit() {
given(this.ace.isAuditSuccess()).willReturn(true);
this.logger.logIfNeeded(true, this.ace);
assertThat(this.bytes.toString()).startsWith("GRANTED due to ACE");
}

View File

@ -42,7 +42,6 @@ public class ObjectIdentityImplTests {
}
catch (IllegalArgumentException expected) {
}
// Check String-Serializable constructor required field
try {
new ObjectIdentityImpl("", 1L);
@ -50,7 +49,6 @@ public class ObjectIdentityImplTests {
}
catch (IllegalArgumentException expected) {
}
// Check Serializable parameter is not null
try {
new ObjectIdentityImpl(DOMAIN_CLASS, null);
@ -58,7 +56,6 @@ public class ObjectIdentityImplTests {
}
catch (IllegalArgumentException expected) {
}
// The correct way of using String-Serializable constructor
try {
new ObjectIdentityImpl(DOMAIN_CLASS, 1L);
@ -66,7 +63,6 @@ public class ObjectIdentityImplTests {
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
// Check the Class-Serializable constructor
try {
new ObjectIdentityImpl(MockIdDomainObject.class, null);
@ -91,9 +87,7 @@ public class ObjectIdentityImplTests {
fail("It should have thrown IdentityUnavailableException");
}
catch (IdentityUnavailableException expected) {
}
// getId() should return a non-null value
MockIdDomainObject mockId = new MockIdDomainObject();
try {
@ -101,9 +95,7 @@ public class ObjectIdentityImplTests {
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// getId() should return a Serializable object
mockId.setId(new MockIdDomainObject());
try {
@ -112,7 +104,6 @@ public class ObjectIdentityImplTests {
}
catch (IllegalArgumentException expected) {
}
// getId() should return a Serializable object
mockId.setId(100L);
try {
@ -132,7 +123,6 @@ public class ObjectIdentityImplTests {
ObjectIdentity obj = new ObjectIdentityImpl(DOMAIN_CLASS, 1L);
MockIdDomainObject mockObj = new MockIdDomainObject();
mockObj.setId(1L);
String string = "SOME_STRING";
assertThat(string).isNotSameAs(obj);
assertThat(obj).isNotNull();
@ -155,7 +145,6 @@ public class ObjectIdentityImplTests {
public void longAndIntegerIdsWithSameValueAreEqualAndHaveSameHashcode() {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, 5L);
ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, 5);
assertThat(obj2).isEqualTo(obj);
assertThat(obj2.hashCode()).isEqualTo(obj.hashCode());
}

View File

@ -34,10 +34,8 @@ public class ObjectIdentityRetrievalStrategyImplTests {
public void testObjectIdentityCreation() {
MockIdDomainObject domain = new MockIdDomainObject();
domain.setId(1);
ObjectIdentityRetrievalStrategy retStrategy = new ObjectIdentityRetrievalStrategyImpl();
ObjectIdentity identity = retStrategy.getObjectIdentity(domain);
assertThat(identity).isNotNull();
assertThat(new ObjectIdentityImpl(domain)).isEqualTo(identity);
}

View File

@ -62,26 +62,19 @@ public class PermissionTests {
@Test
public void stringConversion() {
this.permissionFactory.registerPublicPermissions(SpecialPermission.class);
assertThat(BasePermission.READ.toString()).isEqualTo("BasePermission[...............................R=1]");
assertThat(BasePermission.ADMINISTRATION.toString())
.isEqualTo("BasePermission[...........................A....=16]");
assertThat(new CumulativePermission().set(BasePermission.READ).toString())
.isEqualTo("CumulativePermission[...............................R=1]");
assertThat(
new CumulativePermission().set(SpecialPermission.ENTER).set(BasePermission.ADMINISTRATION).toString())
.isEqualTo("CumulativePermission[..........................EA....=48]");
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ).toString())
.isEqualTo("CumulativePermission[...........................A...R=17]");
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
.clear(BasePermission.ADMINISTRATION).toString())
.isEqualTo("CumulativePermission[...............................R=1]");
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
.clear(BasePermission.ADMINISTRATION).clear(BasePermission.READ).toString())
.isEqualTo("CumulativePermission[................................=0]");

View File

@ -147,7 +147,6 @@ public abstract class AbstractBasicLookupStrategyTests {
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101L);
// Deliberately use an integer for the child, to reproduce bug report in SEC-819
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102);
Map<ObjectIdentity, Acl> map = this.strategy
.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map);
@ -158,15 +157,12 @@ public abstract class AbstractBasicLookupStrategyTests {
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100);
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101L);
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L);
// Objects were put in cache
this.strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
// Let's empty the database to force acls retrieval from cache
emptyDatabase();
Map<ObjectIdentity, Acl> map = this.strategy
.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
@ -175,7 +171,6 @@ public abstract class AbstractBasicLookupStrategyTests {
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101);
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L);
// Set a batch size to allow multiple database queries in order to retrieve all
// acls
this.strategy.setBatchSize(1);
@ -187,31 +182,25 @@ public abstract class AbstractBasicLookupStrategyTests {
private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid,
Map<ObjectIdentity, Acl> map) {
assertThat(map).hasSize(3);
MutableAcl topParent = (MutableAcl) map.get(topParentOid);
MutableAcl middleParent = (MutableAcl) map.get(middleParentOid);
MutableAcl child = (MutableAcl) map.get(childOid);
// Check the retrieved versions has IDs
assertThat(topParent.getId()).isNotNull();
assertThat(middleParent.getId()).isNotNull();
assertThat(child.getId()).isNotNull();
// Check their parents were correctly retrieved
assertThat(topParent.getParentAcl()).isNull();
assertThat(middleParent.getParentAcl().getObjectIdentity()).isEqualTo(topParentOid);
assertThat(child.getParentAcl().getObjectIdentity()).isEqualTo(middleParentOid);
// Check their ACEs were correctly retrieved
assertThat(topParent.getEntries()).hasSize(2);
assertThat(middleParent.getEntries()).hasSize(1);
assertThat(child.getEntries()).hasSize(1);
// Check object identities were correctly retrieved
assertThat(topParent.getObjectIdentity()).isEqualTo(topParentOid);
assertThat(middleParent.getObjectIdentity()).isEqualTo(middleParentOid);
assertThat(child.getObjectIdentity()).isEqualTo(childOid);
// Check each entry
assertThat(topParent.isEntriesInheriting()).isTrue();
assertThat(Long.valueOf(1)).isEqualTo(topParent.getId());
@ -222,14 +211,12 @@ public abstract class AbstractBasicLookupStrategyTests {
assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditFailure()).isFalse();
assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditSuccess()).isFalse();
assertThat((topParent.getEntries().get(0)).isGranting()).isTrue();
assertThat(Long.valueOf(2)).isEqualTo(topParent.getEntries().get(1).getId());
assertThat(topParent.getEntries().get(1).getPermission()).isEqualTo(BasePermission.WRITE);
assertThat(topParent.getEntries().get(1).getSid()).isEqualTo(new PrincipalSid("ben"));
assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditFailure()).isFalse();
assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditSuccess()).isFalse();
assertThat(topParent.getEntries().get(1).isGranting()).isFalse();
assertThat(middleParent.isEntriesInheriting()).isTrue();
assertThat(Long.valueOf(2)).isEqualTo(middleParent.getId());
assertThat(new PrincipalSid("ben")).isEqualTo(middleParent.getOwner());
@ -239,7 +226,6 @@ public abstract class AbstractBasicLookupStrategyTests {
assertThat(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditFailure()).isFalse();
assertThat(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditSuccess()).isFalse();
assertThat(middleParent.getEntries().get(0).isGranting()).isTrue();
assertThat(child.isEntriesInheriting()).isTrue();
assertThat(Long.valueOf(3)).isEqualTo(child.getId());
assertThat(new PrincipalSid("ben")).isEqualTo(child.getOwner());
@ -255,15 +241,12 @@ public abstract class AbstractBasicLookupStrategyTests {
public void testAllParentsAreRetrievedWhenChildIsLoaded() {
String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,103,1,1,1);";
getJdbcTemplate().execute(query);
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101L);
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L);
ObjectIdentity middleParent2Oid = new ObjectIdentityImpl(TARGET_CLASS, 103L);
// Retrieve the child
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(Arrays.asList(childOid), null);
// Check that the child and all its parents were retrieved
assertThat(map.get(childOid)).isNotNull();
assertThat(map.get(childOid).getObjectIdentity()).isEqualTo(childOid);
@ -271,7 +254,6 @@ public abstract class AbstractBasicLookupStrategyTests {
assertThat(map.get(middleParentOid).getObjectIdentity()).isEqualTo(middleParentOid);
assertThat(map.get(topParentOid)).isNotNull();
assertThat(map.get(topParentOid).getObjectIdentity()).isEqualTo(topParentOid);
// The second parent shouldn't have been retrieved
assertThat(map.get(middleParent2Oid)).isNull();
}
@ -287,26 +269,21 @@ public abstract class AbstractBasicLookupStrategyTests {
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (9,2,108,7,1,1);"
+ "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (7,6,0,1,1,1,0,0)";
getJdbcTemplate().execute(query);
ObjectIdentity grandParentOid = new ObjectIdentityImpl(TARGET_CLASS, 104L);
ObjectIdentity parent1Oid = new ObjectIdentityImpl(TARGET_CLASS, 105L);
ObjectIdentity parent2Oid = new ObjectIdentityImpl(TARGET_CLASS, 106);
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 107);
// First lookup only child, thus populating the cache with grandParent,
// parent1
// and child
List<Permission> checkPermission = Arrays.asList(BasePermission.READ);
List<Sid> sids = Arrays.asList(BEN_SID);
List<ObjectIdentity> childOids = Arrays.asList(childOid);
this.strategy.setBatchSize(6);
Map<ObjectIdentity, Acl> foundAcls = this.strategy.readAclsById(childOids, sids);
Acl foundChildAcl = foundAcls.get(childOid);
assertThat(foundChildAcl).isNotNull();
assertThat(foundChildAcl.isGranted(checkPermission, sids, false)).isTrue();
// Search for object identities has to be done in the following order:
// last
// element have to be one which
@ -315,12 +292,10 @@ public abstract class AbstractBasicLookupStrategyTests {
List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid);
try {
foundAcls = this.strategy.readAclsById(allOids, sids);
}
catch (NotFoundException notExpected) {
fail("It shouldn't have thrown NotFoundException");
}
Acl foundParent2Acl = foundAcls.get(parent2Oid);
assertThat(foundParent2Acl).isNotNull();
assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue();
@ -329,18 +304,14 @@ public abstract class AbstractBasicLookupStrategyTests {
@Test(expected = IllegalArgumentException.class)
public void nullOwnerIsNotSupported() {
String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,104,null,null,1);";
getJdbcTemplate().execute(query);
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 104L);
this.strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID));
}
@Test
public void testCreatePrincipalSid() {
Sid result = this.strategy.createSid(true, "sid");
assertThat(result.getClass()).isEqualTo(PrincipalSid.class);
assertThat(((PrincipalSid) result).getPrincipal()).isEqualTo("sid");
}
@ -348,7 +319,6 @@ public abstract class AbstractBasicLookupStrategyTests {
@Test
public void testCreateGrantedAuthority() {
Sid result = this.strategy.createSid(false, "sid");
assertThat(result.getClass()).isEqualTo(GrantedAuthoritySid.class);
assertThat(((GrantedAuthoritySid) result).getGrantedAuthority()).isEqualTo("sid");
}

View File

@ -58,12 +58,10 @@ public class BasicLookupStrategyTestsDbHelper {
else {
connectionUrl = "jdbc:hsqldb:mem:lookupstrategytestWithAclClassIdType";
sqlClassPathResource = ACL_SCHEMA_SQL_FILE_WITH_ACL_CLASS_ID;
}
this.dataSource = new SingleConnectionDataSource(connectionUrl, "sa", "", true);
this.dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
Resource resource = new ClassPathResource(sqlClassPathResource);
String sql = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
this.jdbcTemplate.execute(sql);

View File

@ -35,7 +35,6 @@ public class DatabaseSeeder {
public DatabaseSeeder(DataSource dataSource, Resource resource) throws IOException {
Assert.notNull(dataSource, "dataSource required");
Assert.notNull(resource, "resource required");
JdbcTemplate template = new JdbcTemplate(dataSource);
String sql = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
template.execute(sql);

View File

@ -82,12 +82,10 @@ public class EhCacheBasedAclCacheTests {
this.myCache = new EhCacheBasedAclCache(this.cache,
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER")));
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL"));
this.acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
}
@ -111,7 +109,6 @@ public class EhCacheBasedAclCacheTests {
}
catch (IllegalArgumentException expected) {
}
try {
ObjectIdentity obj = null;
this.myCache.evictFromCache(obj);
@ -119,7 +116,6 @@ public class EhCacheBasedAclCacheTests {
}
catch (IllegalArgumentException expected) {
}
try {
Serializable id = null;
this.myCache.getFromCache(id);
@ -127,7 +123,6 @@ public class EhCacheBasedAclCacheTests {
}
catch (IllegalArgumentException expected) {
}
try {
ObjectIdentity obj = null;
this.myCache.getFromCache(obj);
@ -135,7 +130,6 @@ public class EhCacheBasedAclCacheTests {
}
catch (IllegalArgumentException expected) {
}
try {
MutableAcl acl = null;
this.myCache.putInCache(acl);
@ -154,17 +148,13 @@ public class EhCacheBasedAclCacheTests {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this.acl);
oos.close();
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
MutableAcl retrieved = (MutableAcl) ois.readObject();
ois.close();
assertThat(retrieved).isEqualTo(this.acl);
Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", retrieved);
assertThat(retrieved1).isNull();
Object retrieved2 = FieldUtils.getProtectedFieldValue("permissionGrantingStrategy", retrieved);
assertThat(retrieved2).isNull();
}
@ -172,14 +162,12 @@ public class EhCacheBasedAclCacheTests {
@Test
public void clearCache() {
this.myCache.clearCache();
verify(this.cache).removeAll();
}
@Test
public void putInCache() {
this.myCache.putInCache(this.acl);
verify(this.cache, times(2)).put(this.element.capture());
assertThat(this.element.getValue().getKey()).isEqualTo(this.acl.getId());
assertThat(this.element.getValue().getObjectValue()).isEqualTo(this.acl);
@ -192,29 +180,21 @@ public class EhCacheBasedAclCacheTests {
Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identityParent = new ObjectIdentityImpl(TARGET_CLASS, 2L);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL"));
MutableAcl parentAcl = new AclImpl(identityParent, 2L, aclAuthorizationStrategy, new ConsoleAuditLogger());
this.acl.setParent(parentAcl);
this.myCache.putInCache(this.acl);
verify(this.cache, times(4)).put(this.element.capture());
List<Element> allValues = this.element.getAllValues();
assertThat(allValues.get(0).getKey()).isEqualTo(parentAcl.getObjectIdentity());
assertThat(allValues.get(0).getObjectValue()).isEqualTo(parentAcl);
assertThat(allValues.get(1).getKey()).isEqualTo(parentAcl.getId());
assertThat(allValues.get(1).getObjectValue()).isEqualTo(parentAcl);
assertThat(allValues.get(2).getKey()).isEqualTo(this.acl.getObjectIdentity());
assertThat(allValues.get(2).getObjectValue()).isEqualTo(this.acl);
assertThat(allValues.get(3).getKey()).isEqualTo(this.acl.getId());
assertThat(allValues.get(3).getObjectValue()).isEqualTo(this.acl);
}
@ -222,21 +202,16 @@ public class EhCacheBasedAclCacheTests {
@Test
public void getFromCacheSerializable() {
given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl));
assertThat(this.myCache.getFromCache(this.acl.getId())).isEqualTo(this.acl);
}
@Test
public void getFromCacheSerializablePopulatesTransient() {
given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl));
this.myCache.putInCache(this.acl);
ReflectionTestUtils.setField(this.acl, "permissionGrantingStrategy", null);
ReflectionTestUtils.setField(this.acl, "aclAuthorizationStrategy", null);
MutableAcl fromCache = this.myCache.getFromCache(this.acl.getId());
assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull();
assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull();
}
@ -244,21 +219,16 @@ public class EhCacheBasedAclCacheTests {
@Test
public void getFromCacheObjectIdentity() {
given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl));
assertThat(this.myCache.getFromCache(this.acl.getId())).isEqualTo(this.acl);
}
@Test
public void getFromCacheObjectIdentityPopulatesTransient() {
given(this.cache.get(this.acl.getObjectIdentity())).willReturn(new Element(this.acl.getId(), this.acl));
this.myCache.putInCache(this.acl);
ReflectionTestUtils.setField(this.acl, "permissionGrantingStrategy", null);
ReflectionTestUtils.setField(this.acl, "aclAuthorizationStrategy", null);
MutableAcl fromCache = this.myCache.getFromCache(this.acl.getObjectIdentity());
assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull();
assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull();
}
@ -266,9 +236,7 @@ public class EhCacheBasedAclCacheTests {
@Test
public void evictCacheSerializable() {
given(this.cache.get(this.acl.getObjectIdentity())).willReturn(new Element(this.acl.getId(), this.acl));
this.myCache.evictFromCache(this.acl.getObjectIdentity());
verify(this.cache).remove(this.acl.getId());
verify(this.cache).remove(this.acl.getObjectIdentity());
}
@ -276,9 +244,7 @@ public class EhCacheBasedAclCacheTests {
@Test
public void evictCacheObjectIdentity() {
given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl));
this.myCache.evictFromCache(this.acl.getId());
verify(this.cache).remove(this.acl.getId());
verify(this.cache).remove(this.acl.getObjectIdentity());
}

View File

@ -97,7 +97,6 @@ public class JdbcAclServiceTests {
given(this.lookupStrategy.readAclsById(anyList(), anyList())).willReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 1);
List<Sid> sids = Arrays.<Sid>asList(new PrincipalSid("user"));
this.aclService.readAclById(objectIdentity, sids);
}
@ -108,7 +107,6 @@ public class JdbcAclServiceTests {
Object[] args = { "1", "org.springframework.security.acls.jdbc.JdbcAclServiceTests$MockLongIdDomainObject" };
given(this.jdbcOperations.query(anyString(), eq(args), any(RowMapper.class))).willReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L);
List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("5577");
@ -117,7 +115,6 @@ public class JdbcAclServiceTests {
@Test
public void findNoChildren() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L);
List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity);
assertThat(objectIdentities).isNull();
}
@ -125,7 +122,6 @@ public class JdbcAclServiceTests {
@Test
public void findChildrenWithoutIdType() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 4711L);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo(MockUntypedIdDomainObject.class.getName());
@ -135,7 +131,6 @@ public class JdbcAclServiceTests {
@Test
public void findChildrenForUnknownObject() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 33);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities).isNull();
}
@ -143,7 +138,6 @@ public class JdbcAclServiceTests {
@Test
public void findChildrenOfIdTypeLong() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US-PAL");
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(2);
assertThat(objectIdentities.get(0).getType()).isEqualTo(MockLongIdDomainObject.class.getName());
@ -155,7 +149,6 @@ public class JdbcAclServiceTests {
@Test
public void findChildrenOfIdTypeString() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US");
this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);
@ -166,7 +159,6 @@ public class JdbcAclServiceTests {
@Test
public void findChildrenOfIdTypeUUID() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockUntypedIdDomainObject.class, 5000L);
this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);

View File

@ -142,123 +142,97 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Transactional
public void testLifecycle() {
SecurityContextHolder.getContext().setAuthentication(this.auth);
MutableAcl topParent = this.jdbcMutableAclService.createAcl(getTopParentOid());
MutableAcl middleParent = this.jdbcMutableAclService.createAcl(getMiddleParentOid());
MutableAcl child = this.jdbcMutableAclService.createAcl(getChildOid());
// Specify the inheritance hierarchy
middleParent.setParent(topParent);
child.setParent(middleParent);
// Now let's add a couple of permissions
topParent.insertAce(0, BasePermission.READ, new PrincipalSid(this.auth), true);
topParent.insertAce(1, BasePermission.WRITE, new PrincipalSid(this.auth), false);
middleParent.insertAce(0, BasePermission.DELETE, new PrincipalSid(this.auth), true);
child.insertAce(0, BasePermission.DELETE, new PrincipalSid(this.auth), false);
// Explicitly save the changed ACL
this.jdbcMutableAclService.updateAcl(topParent);
this.jdbcMutableAclService.updateAcl(middleParent);
this.jdbcMutableAclService.updateAcl(child);
// Let's check if we can read them back correctly
Map<ObjectIdentity, Acl> map = this.jdbcMutableAclService
.readAclsById(Arrays.asList(getTopParentOid(), getMiddleParentOid(), getChildOid()));
assertThat(map).hasSize(3);
// Replace our current objects with their retrieved versions
topParent = (MutableAcl) map.get(getTopParentOid());
middleParent = (MutableAcl) map.get(getMiddleParentOid());
child = (MutableAcl) map.get(getChildOid());
// Check the retrieved versions has IDs
assertThat(topParent.getId()).isNotNull();
assertThat(middleParent.getId()).isNotNull();
assertThat(child.getId()).isNotNull();
// Check their parents were correctly persisted
assertThat(topParent.getParentAcl()).isNull();
assertThat(middleParent.getParentAcl().getObjectIdentity()).isEqualTo(getTopParentOid());
assertThat(child.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid());
// Check their ACEs were correctly persisted
assertThat(topParent.getEntries()).hasSize(2);
assertThat(middleParent.getEntries()).hasSize(1);
assertThat(child.getEntries()).hasSize(1);
// Check the retrieved rights are correct
List<Permission> read = Arrays.asList(BasePermission.READ);
List<Permission> write = Arrays.asList(BasePermission.WRITE);
List<Permission> delete = Arrays.asList(BasePermission.DELETE);
List<Sid> pSid = Arrays.asList((Sid) new PrincipalSid(this.auth));
assertThat(topParent.isGranted(read, pSid, false)).isTrue();
assertThat(topParent.isGranted(write, pSid, false)).isFalse();
assertThat(middleParent.isGranted(delete, pSid, false)).isTrue();
assertThat(child.isGranted(delete, pSid, false)).isFalse();
try {
child.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false);
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
// Now check the inherited rights (when not explicitly overridden) also look OK
assertThat(child.isGranted(read, pSid, false)).isTrue();
assertThat(child.isGranted(write, pSid, false)).isFalse();
assertThat(child.isGranted(delete, pSid, false)).isFalse();
// Next change the child so it doesn't inherit permissions from above
child.setEntriesInheriting(false);
this.jdbcMutableAclService.updateAcl(child);
child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(child.isEntriesInheriting()).isFalse();
// Check the child permissions no longer inherit
assertThat(child.isGranted(delete, pSid, true)).isFalse();
try {
child.isGranted(read, pSid, true);
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
child.isGranted(write, pSid, true);
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
// Let's add an identical permission to the child, but it'll appear AFTER the
// current permission, so has no impact
child.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true);
// Let's also add another permission to the child
child.insertAce(2, BasePermission.CREATE, new PrincipalSid(this.auth), true);
// Save the changed child
this.jdbcMutableAclService.updateAcl(child);
child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(child.getEntries()).hasSize(3);
// Output permissions
for (int i = 0; i < child.getEntries().size(); i++) {
System.out.println(child.getEntries().get(i));
}
// Check the permissions are as they should be
assertThat(child.isGranted(delete, pSid, true)).isFalse(); // as earlier
// permission
// overrode
assertThat(child.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue();
// Now check the first ACE (index 0) really is DELETE for our Sid and is
// non-granting
AccessControlEntry entry = child.getEntries().get(0);
@ -266,15 +240,12 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
assertThat(entry.getSid()).isEqualTo(new PrincipalSid(this.auth));
assertThat(entry.isGranting()).isFalse();
assertThat(entry.getId()).isNotNull();
// Now delete that first ACE
child.deleteAce(0);
// Save and check it worked
child = this.jdbcMutableAclService.updateAcl(child);
assertThat(child.getEntries()).hasSize(2);
assertThat(child.isGranted(delete, pSid, false)).isTrue();
SecurityContextHolder.clearContext();
}
@ -285,7 +256,6 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Transactional
public void deleteAclAlsoDeletesChildren() {
SecurityContextHolder.getContext().setAuthentication(this.auth);
this.jdbcMutableAclService.createAcl(getTopParentOid());
MutableAcl middleParent = this.jdbcMutableAclService.createAcl(getMiddleParentOid());
MutableAcl child = this.jdbcMutableAclService.createAcl(getChildOid());
@ -294,27 +264,21 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
this.jdbcMutableAclService.updateAcl(child);
// Check the childOid really is a child of middleParentOid
Acl childAcl = this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(childAcl.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid());
// Delete the mid-parent and test if the child was deleted, as well
this.jdbcMutableAclService.deleteAcl(getMiddleParentOid(), true);
try {
this.jdbcMutableAclService.readAclById(getMiddleParentOid());
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
this.jdbcMutableAclService.readAclById(getChildOid());
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
Acl acl = this.jdbcMutableAclService.readAclById(getTopParentOid());
assertThat(acl).isNotNull();
assertThat(getTopParentOid()).isEqualTo(acl.getObjectIdentity());
@ -328,14 +292,12 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
}
catch (IllegalArgumentException expected) {
}
try {
new JdbcMutableAclService(this.dataSource, null, this.aclCache);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null);
fail("It should have thrown IllegalArgumentException");
@ -386,11 +348,9 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
SecurityContextHolder.getContext().setAuthentication(this.auth);
MutableAcl parent = this.jdbcMutableAclService.createAcl(getTopParentOid());
MutableAcl child = this.jdbcMutableAclService.createAcl(getMiddleParentOid());
// Specify the inheritance hierarchy
child.setParent(parent);
this.jdbcMutableAclService.updateAcl(child);
try {
this.jdbcMutableAclService.setForeignKeysInDatabase(false); // switch on FK
// checking in the
@ -413,13 +373,11 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
MutableAcl child = this.jdbcMutableAclService.createAcl(getChildOid());
child.insertAce(0, BasePermission.DELETE, new PrincipalSid(this.auth), false);
this.jdbcMutableAclService.updateAcl(child);
// Remove the child and check all related database rows were removed accordingly
this.jdbcMutableAclService.deleteAcl(getChildOid(), false);
assertThat(this.jdbcTemplate.queryForList(SELECT_ALL_CLASSES, new Object[] { getTargetClass() })).hasSize(1);
assertThat(this.jdbcTemplate.queryForList("select * from acl_object_identity")).isEmpty();
assertThat(this.jdbcTemplate.queryForList("select * from acl_entry")).isEmpty();
// Check the cache
assertThat(this.aclCache.getFromCache(getChildOid())).isNull();
assertThat(this.aclCache.getFromCache(102L)).isNull();
@ -432,7 +390,6 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
SecurityContextHolder.getContext().setAuthentication(this.auth);
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 101);
this.jdbcMutableAclService.createAcl(oid);
assertThat(this.jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 101L))).isNotNull();
}
@ -445,27 +402,20 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity parentOid = new ObjectIdentityImpl(TARGET_CLASS, 104L);
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 105L);
MutableAcl parent = this.jdbcMutableAclService.createAcl(parentOid);
MutableAcl child = this.jdbcMutableAclService.createAcl(childOid);
child.setParent(parent);
this.jdbcMutableAclService.updateAcl(child);
parent = (AclImpl) this.jdbcMutableAclService.readAclById(parentOid);
parent.insertAce(0, BasePermission.READ, new PrincipalSid("ben"), true);
this.jdbcMutableAclService.updateAcl(parent);
parent = (AclImpl) this.jdbcMutableAclService.readAclById(parentOid);
parent.insertAce(1, BasePermission.READ, new PrincipalSid("scott"), true);
this.jdbcMutableAclService.updateAcl(parent);
child = (MutableAcl) this.jdbcMutableAclService.readAclById(childOid);
parent = (MutableAcl) child.getParentAcl();
assertThat(parent.getEntries()).hasSize(2)
.withFailMessage("Fails because child has a stale reference to its parent");
assertThat(parent.getEntries().get(0).getPermission().getMask()).isEqualTo(1);
@ -483,22 +433,16 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
Authentication auth = new TestingAuthenticationToken("system", "secret", "ROLE_IGNORED");
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentityImpl rootObject = new ObjectIdentityImpl(TARGET_CLASS, 1L);
MutableAcl parent = this.jdbcMutableAclService.createAcl(rootObject);
MutableAcl child = this.jdbcMutableAclService.createAcl(new ObjectIdentityImpl(TARGET_CLASS, 2L));
child.setParent(parent);
this.jdbcMutableAclService.updateAcl(child);
parent.insertAce(0, BasePermission.ADMINISTRATION, new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true);
this.jdbcMutableAclService.updateAcl(parent);
parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true);
this.jdbcMutableAclService.updateAcl(parent);
child = (MutableAcl) this.jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 2L));
parent = (MutableAcl) child.getParentAcl();
assertThat(parent.getEntries()).hasSize(2);
assertThat(parent.getEntries().get(0).getPermission().getMask()).isEqualTo(16);
assertThat(parent.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"));
@ -512,24 +456,19 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 110L);
MutableAcl topParent = this.jdbcMutableAclService.createAcl(topParentOid);
// Add an ACE permission entry
Permission cm = new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION);
assertThat(cm.getMask()).isEqualTo(17);
Sid benSid = new PrincipalSid(auth);
topParent.insertAce(0, cm, benSid, true);
assertThat(topParent.getEntries()).hasSize(1);
// Explicitly save the changed ACL
topParent = this.jdbcMutableAclService.updateAcl(topParent);
// Check the mask was retrieved correctly
assertThat(topParent.getEntries().get(0).getPermission().getMask()).isEqualTo(17);
assertThat(topParent.isGranted(Arrays.asList(cm), Arrays.asList(benSid), true)).isTrue();
SecurityContextHolder.clearContext();
}
@ -539,9 +478,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
new CustomJdbcMutableAclService(this.dataSource, this.lookupStrategy, this.aclCache));
CustomSid customSid = new CustomSid("Custom sid");
given(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).willReturn(1L);
Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(customSid, false);
assertThat(new Long(1L)).isEqualTo(result);
}

View File

@ -75,11 +75,9 @@ public class JdbcMutableAclServiceTestsWithAclClassId extends JdbcMutableAclServ
@Transactional
public void identityWithUuidIdIsSupportedByCreateAcl() {
SecurityContextHolder.getContext().setAuthentication(getAuth());
UUID id = UUID.randomUUID();
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, id);
getJdbcMutableAclService().createAcl(oid);
assertThat(getJdbcMutableAclService().readAclById(new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, id)))
.isNotNull();
}

View File

@ -89,37 +89,28 @@ public class SpringCacheBasedAclCacheTests {
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL"));
AuditLogger auditLogger = new ConsoleAuditLogger();
PermissionGrantingStrategy permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(auditLogger);
SpringCacheBasedAclCache myCache = new SpringCacheBasedAclCache(cache, permissionGrantingStrategy,
aclAuthorizationStrategy);
MutableAcl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, auditLogger);
assertThat(realCache).isEmpty();
myCache.putInCache(acl);
// Check we can get from cache the same objects we put in
assertThat(acl).isEqualTo(myCache.getFromCache(1L));
assertThat(acl).isEqualTo(myCache.getFromCache(identity));
// Put another object in cache
ObjectIdentity identity2 = new ObjectIdentityImpl(TARGET_CLASS, 101L);
MutableAcl acl2 = new AclImpl(identity2, 2L, aclAuthorizationStrategy, new ConsoleAuditLogger());
myCache.putInCache(acl2);
// Try to evict an entry that doesn't exist
myCache.evictFromCache(3L);
myCache.evictFromCache(new ObjectIdentityImpl(TARGET_CLASS, 102L));
assertThat(realCache).hasSize(4);
myCache.evictFromCache(1L);
assertThat(realCache).hasSize(2);
// Check the second object inserted
assertThat(acl2).isEqualTo(myCache.getFromCache(2L));
assertThat(acl2).isEqualTo(myCache.getFromCache(identity2));
myCache.evictFromCache(identity2);
assertThat(realCache).isEmpty();
}
@ -129,31 +120,24 @@ public class SpringCacheBasedAclCacheTests {
public void cacheOperationsAclWithParent() throws Exception {
Cache cache = getCache();
Map realCache = (Map) cache.getNativeCache();
Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 1L);
ObjectIdentity identityParent = new ObjectIdentityImpl(TARGET_CLASS, 2L);
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL"));
AuditLogger auditLogger = new ConsoleAuditLogger();
PermissionGrantingStrategy permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(auditLogger);
SpringCacheBasedAclCache myCache = new SpringCacheBasedAclCache(cache, permissionGrantingStrategy,
aclAuthorizationStrategy);
MutableAcl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, auditLogger);
MutableAcl parentAcl = new AclImpl(identityParent, 2L, aclAuthorizationStrategy, auditLogger);
acl.setParent(parentAcl);
assertThat(realCache).isEmpty();
myCache.putInCache(acl);
assertThat(4).isEqualTo(realCache.size());
// Check we can get from cache the same objects we put in
AclImpl aclFromCache = (AclImpl) myCache.getFromCache(1L);
assertThat(aclFromCache).isEqualTo(acl);

View File

@ -50,16 +50,13 @@ public class SidRetrievalStrategyTests {
public void correctSidsAreRetrieved() {
SidRetrievalStrategy retrStrategy = new SidRetrievalStrategyImpl();
List<Sid> sids = retrStrategy.getSids(this.authentication);
assertThat(sids).isNotNull();
assertThat(sids).hasSize(4);
assertThat(sids.get(0)).isNotNull();
assertThat(sids.get(0) instanceof PrincipalSid).isTrue();
for (int i = 1; i < sids.size(); i++) {
assertThat(sids.get(i) instanceof GrantedAuthoritySid).isTrue();
}
assertThat(((PrincipalSid) sids.get(0)).getPrincipal()).isEqualTo("scott");
assertThat(((GrantedAuthoritySid) sids.get(1)).getGrantedAuthority()).isEqualTo("A");
assertThat(((GrantedAuthoritySid) sids.get(2)).getGrantedAuthority()).isEqualTo("B");
@ -72,7 +69,6 @@ public class SidRetrievalStrategyTests {
List rhAuthorities = AuthorityUtils.createAuthorityList("D");
given(rh.getReachableGrantedAuthorities(anyCollection())).willReturn(rhAuthorities);
SidRetrievalStrategy strat = new SidRetrievalStrategyImpl(rh);
List<Sid> sids = strat.getSids(this.authentication);
assertThat(sids).hasSize(2);
assertThat(sids.get(0)).isNotNull();

View File

@ -46,17 +46,14 @@ public class SidTests {
}
catch (IllegalArgumentException expected) {
}
try {
new PrincipalSid("");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
new PrincipalSid("johndoe");
// throws no exception
// Check one Authentication-argument constructor
try {
Authentication authentication = null;
@ -65,7 +62,6 @@ public class SidTests {
}
catch (IllegalArgumentException expected) {
}
try {
Authentication authentication = new TestingAuthenticationToken(null, "password");
new PrincipalSid(authentication);
@ -73,7 +69,6 @@ public class SidTests {
}
catch (IllegalArgumentException expected) {
}
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
new PrincipalSid(authentication);
// throws no exception
@ -88,25 +83,19 @@ public class SidTests {
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new GrantedAuthoritySid("");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new GrantedAuthoritySid("ROLE_TEST");
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
// Check one GrantedAuthority-argument constructor
try {
GrantedAuthority ga = null;
@ -114,22 +103,17 @@ public class SidTests {
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
GrantedAuthority ga = new SimpleGrantedAuthority(null);
new GrantedAuthoritySid(ga);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
new GrantedAuthoritySid(ga);
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
@ -140,7 +124,6 @@ public class SidTests {
public void testPrincipalSidEquals() {
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
Sid principalSid = new PrincipalSid(authentication);
assertThat(principalSid.equals(null)).isFalse();
assertThat(principalSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse();
assertThat(principalSid.equals(principalSid)).isTrue();
@ -155,7 +138,6 @@ public class SidTests {
public void testGrantedAuthoritySidEquals() {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
Sid gaSid = new GrantedAuthoritySid(ga);
assertThat(gaSid.equals(null)).isFalse();
assertThat(gaSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse();
assertThat(gaSid.equals(gaSid)).isTrue();
@ -170,7 +152,6 @@ public class SidTests {
public void testPrincipalSidHashCode() {
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
Sid principalSid = new PrincipalSid(authentication);
assertThat(principalSid.hashCode()).isEqualTo("johndoe".hashCode());
assertThat(principalSid.hashCode()).isEqualTo(new PrincipalSid("johndoe").hashCode());
assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid("scott").hashCode());
@ -182,7 +163,6 @@ public class SidTests {
public void testGrantedAuthoritySidHashCode() {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
Sid gaSid = new GrantedAuthoritySid(ga);
assertThat(gaSid.hashCode()).isEqualTo("ROLE_TEST".hashCode());
assertThat(gaSid.hashCode()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST").hashCode());
assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid("ROLE_TEST_2").hashCode());
@ -196,10 +176,8 @@ public class SidTests {
PrincipalSid principalSid = new PrincipalSid(authentication);
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
GrantedAuthoritySid gaSid = new GrantedAuthoritySid(ga);
assertThat("johndoe".equals(principalSid.getPrincipal())).isTrue();
assertThat("scott".equals(principalSid.getPrincipal())).isFalse();
assertThat("ROLE_TEST".equals(gaSid.getGrantedAuthority())).isTrue();
assertThat("ROLE_TEST2".equals(gaSid.getGrantedAuthority())).isFalse();
}
@ -209,7 +187,6 @@ public class SidTests {
User user = new User("user", "password", Collections.singletonList(new SimpleGrantedAuthority("ROLE_TEST")));
Authentication authentication = new TestingAuthenticationToken(user, "password");
PrincipalSid principalSid = new PrincipalSid(authentication);
assertThat("user").isEqualTo(principalSid.getPrincipal());
}
@ -217,7 +194,6 @@ public class SidTests {
public void getPrincipalWhenPrincipalNotInstanceOfUserDetailsThenReturnsPrincipalName() {
Authentication authentication = new TestingAuthenticationToken("token", "password");
PrincipalSid principalSid = new PrincipalSid(authentication);
assertThat("token").isEqualTo(principalSid.getPrincipal());
}
@ -225,7 +201,6 @@ public class SidTests {
public void getPrincipalWhenCustomAuthenticationPrincipalThenReturnsPrincipalName() {
Authentication authentication = new CustomAuthenticationToken(new CustomToken("token"), null);
PrincipalSid principalSid = new PrincipalSid(authentication);
assertThat("token").isEqualTo(principalSid.getPrincipal());
}

View File

@ -111,7 +111,6 @@ public class AnnotationSecurityAspectTests {
@Test(expected = AccessDeniedException.class)
public void internalPrivateCallIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(this.anne);
try {
this.secured.publicCallsPrivate();
fail("Expected AccessDeniedException");
@ -124,7 +123,6 @@ public class AnnotationSecurityAspectTests {
@Test(expected = AccessDeniedException.class)
public void protectedMethodIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(this.anne);
this.secured.protectedMethod();
}

View File

@ -35,11 +35,9 @@ public abstract class AbstractStatelessTicketCacheTests {
protected CasAuthenticationToken getToken() {
List<String> proxyList = new ArrayList<>();
proxyList.add("https://localhost/newPortal/login/cas");
User user = new User("rod", "password", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
final Assertion assertion = new AssertionImpl("rod");
return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), user, assertion);
}

View File

@ -71,7 +71,6 @@ public class CasAuthenticationProviderTests {
final ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setSendRenew(false);
serviceProperties.setService("http://test.com");
return serviceProperties;
}
@ -80,27 +79,20 @@ public class CasAuthenticationProviderTests {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache);
cap.setServiceProperties(makeServiceProperties());
cap.setTicketValidator(new MockTicketValidator(true));
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, "ST-123");
token.setDetails("details");
Authentication result = cap.authenticate(token);
// Confirm ST-123 was NOT added to the cache
assertThat(cache.getByTicketId("ST-456") == null).isTrue();
if (!(result instanceof CasAuthenticationToken)) {
fail("Should have returned a CasAuthenticationToken");
}
CasAuthenticationToken casResult = (CasAuthenticationToken) result;
assertThat(casResult.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator());
assertThat(casResult.getCredentials()).isEqualTo("ST-123");
@ -108,11 +100,9 @@ public class CasAuthenticationProviderTests {
assertThat(casResult.getAuthorities()).contains(new SimpleGrantedAuthority("ROLE_B"));
assertThat(casResult.getKeyHash()).isEqualTo(cap.getKey().hashCode());
assertThat(casResult.getDetails()).isEqualTo("details");
// Now confirm the CasAuthenticationToken is automatically re-accepted.
// To ensure TicketValidator not called again, set it to deliver an exception...
cap.setTicketValidator(new MockTicketValidator(false));
Authentication laterResult = cap.authenticate(result);
assertThat(laterResult).isEqualTo(result);
}
@ -122,34 +112,26 @@ public class CasAuthenticationProviderTests {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache);
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, "ST-456");
token.setDetails("details");
Authentication result = cap.authenticate(token);
// Confirm ST-456 was added to the cache
assertThat(cache.getByTicketId("ST-456") != null).isTrue();
if (!(result instanceof CasAuthenticationToken)) {
fail("Should have returned a CasAuthenticationToken");
}
assertThat(result.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator());
assertThat(result.getCredentials()).isEqualTo("ST-456");
assertThat(result.getDetails()).isEqualTo("details");
// Now try to authenticate again. To ensure TicketValidator not
// called again, set it to deliver an exception...
cap.setTicketValidator(new MockTicketValidator(false));
// Previously created UsernamePasswordAuthenticationToken is OK
Authentication newResult = cap.authenticate(token);
assertThat(newResult.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator());
@ -163,22 +145,17 @@ public class CasAuthenticationProviderTests {
given(details.getServiceUrl()).willReturn(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
cap.setTicketValidator(validator);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
String ticket = "ST-456";
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, ticket);
Authentication result = cap.authenticate(token);
}
@ -189,40 +166,31 @@ public class CasAuthenticationProviderTests {
given(details.getServiceUrl()).willReturn(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
cap.setTicketValidator(validator);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
String ticket = "ST-456";
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, ticket);
Authentication result = cap.authenticate(token);
verify(validator).validate(ticket, serviceProperties.getService());
serviceProperties.setAuthenticateAllArtifacts(true);
result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceProperties.getService());
token.setDetails(details);
result = cap.authenticate(token);
verify(validator).validate(ticket, serviceUrl);
serviceProperties.setAuthenticateAllArtifacts(false);
serviceProperties.setService(null);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceUrl);
token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
try {
cap.authenticate(token);
@ -230,7 +198,6 @@ public class CasAuthenticationProviderTests {
}
catch (IllegalStateException success) {
}
cap.setServiceProperties(null);
cap.afterPropertiesSet();
try {
@ -246,16 +213,13 @@ public class CasAuthenticationProviderTests {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache);
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, "");
cap.authenticate(token);
}
@ -265,16 +229,13 @@ public class CasAuthenticationProviderTests {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache);
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials",
AuthorityUtils.createAuthorityList("XX"), makeUserDetails(), assertion);
cap.authenticate(token);
}
@ -329,7 +290,6 @@ public class CasAuthenticationProviderTests {
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
// TODO disabled because why do we need to expose this?
// assertThat(cap.getUserDetailsService() != null).isTrue();
assertThat(cap.getKey()).isEqualTo("qwerty");
@ -346,10 +306,8 @@ public class CasAuthenticationProviderTests {
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password", "ROLE_A");
assertThat(cap.supports(TestingAuthenticationToken.class)).isFalse();
// Try it anyway
assertThat(cap.authenticate(token)).isNull();
}
@ -363,7 +321,6 @@ public class CasAuthenticationProviderTests {
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user",
"password", AuthorityUtils.createAuthorityList("ROLE_A"));
assertThat(cap.authenticate(token)).isNull();

View File

@ -59,35 +59,30 @@ public class CasAuthenticationTokenTests {
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), null, this.ROLES, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password",
AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion);
@ -106,13 +101,10 @@ public class CasAuthenticationTokenTests {
@Test
public void testEqualsWhenEqual() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion);
assertThat(token2).isEqualTo(token1);
}
@ -138,30 +130,24 @@ public class CasAuthenticationTokenTests {
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
}
}
@Test
public void testNotEqualsDueToAbstractParentEqualsCheck() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails("OTHER_NAME"), "Password",
this.ROLES, makeUserDetails(), assertion);
assertThat(!token1.equals(token2)).isTrue();
}
@Test
public void testNotEqualsDueToDifferentAuthenticationClass() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
this.ROLES);
assertThat(!token1.equals(token2)).isTrue();
@ -170,13 +156,10 @@ public class CasAuthenticationTokenTests {
@Test
public void testNotEqualsDueToKey() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY", makeUserDetails(), "Password",
this.ROLES, makeUserDetails(), assertion);
assertThat(!token1.equals(token2)).isTrue();
}
@ -184,13 +167,10 @@ public class CasAuthenticationTokenTests {
public void testNotEqualsDueToAssertion() {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion2 = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion2);
assertThat(!token1.equals(token2)).isTrue();
}

View File

@ -52,17 +52,13 @@ public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTe
EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache();
cache.setCache(cacheManager.getCache("castickets"));
cache.afterPropertiesSet();
final CasAuthenticationToken token = getToken();
// Check it gets stored in the cache
cache.putTicketInCache(token);
assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isEqualTo(token);
// Check it gets removed from the cache
cache.removeTicketFromCache(getToken());
assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isNull();
// Check it doesn't return values for null or unknown service tickets
assertThat(cache.getByTicketId(null)).isNull();
assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull();
@ -71,15 +67,12 @@ public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTe
@Test
public void testStartupDetectsMissingCache() throws Exception {
EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache();
try {
cache.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
Ehcache myCache = cacheManager.getCache("castickets");
cache.setCache(myCache);
assertThat(cache.getCache()).isEqualTo(myCache);

View File

@ -44,17 +44,13 @@ public class SpringCacheBasedTicketCacheTests extends AbstractStatelessTicketCac
@Test
public void testCacheOperation() throws Exception {
SpringCacheBasedTicketCache cache = new SpringCacheBasedTicketCache(cacheManager.getCache("castickets"));
final CasAuthenticationToken token = getToken();
// Check it gets stored in the cache
cache.putTicketInCache(token);
assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isEqualTo(token);
// Check it gets removed from the cache
cache.removeTicketFromCache(getToken());
assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isNull();
// Check it doesn't return values for null or unknown service tickets
assertThat(cache.getByTicketId(null)).isNull();
assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull();

View File

@ -74,7 +74,6 @@ public class CasAuthenticationTokenMixinTests {
+ "\"authorities\": " + AUTHORITIES_SET_JSON
+ "}";
// @formatter:on
private static final String CAS_TOKEN_JSON = "{"
+ "\"@class\": \"org.springframework.security.cas.authentication.CasAuthenticationToken\", "
+ "\"keyHash\": " + KEY.hashCode() + "," + "\"principal\": " + USER_JSON + ", " + "\"credentials\": "

View File

@ -38,7 +38,6 @@ public class CasAuthenticationEntryPointTests {
public void testDetectsMissingLoginFormUrl() throws Exception {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setServiceProperties(new ServiceProperties());
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@ -52,7 +51,6 @@ public class CasAuthenticationEntryPointTests {
public void testDetectsMissingServiceProperties() throws Exception {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login");
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@ -67,7 +65,6 @@ public class CasAuthenticationEntryPointTests {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login");
assertThat(ep.getLoginUrl()).isEqualTo("https://cas/login");
ep.setServiceProperties(new ServiceProperties());
assertThat(ep.getServiceProperties() != null).isTrue();
}
@ -77,19 +74,14 @@ public class CasAuthenticationEntryPointTests {
ServiceProperties sp = new ServiceProperties();
sp.setSendRenew(false);
sp.setService("https://mycompany.com/bigWebApp/login/cas");
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login");
ep.setServiceProperties(sp);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/some_path");
MockHttpServletResponse response = new MockHttpServletResponse();
ep.afterPropertiesSet();
ep.commence(request, response, null);
assertThat(
"https://cas/login?service=" + URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", "UTF-8"))
.isEqualTo(response.getRedirectedUrl());
@ -100,16 +92,12 @@ public class CasAuthenticationEntryPointTests {
ServiceProperties sp = new ServiceProperties();
sp.setSendRenew(true);
sp.setService("https://mycompany.com/bigWebApp/login/cas");
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login");
ep.setServiceProperties(sp);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/some_path");
MockHttpServletResponse response = new MockHttpServletResponse();
ep.afterPropertiesSet();
ep.commence(request, response, null);
assertThat("https://cas/login?service="

View File

@ -69,12 +69,9 @@ public class CasAuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/login/cas");
request.addParameter("ticket", "ST-0-ER94xMJmn6pha35CQRoZ");
CasAuthenticationFilter filter = new CasAuthenticationFilter();
filter.setAuthenticationManager((a) -> a);
assertThat(filter.requiresAuthentication(request, new MockHttpServletResponse())).isTrue();
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(result != null).isTrue();
}
@ -85,7 +82,6 @@ public class CasAuthenticationFilterTests {
filter.setAuthenticationManager((a) -> {
throw new BadCredentialsException("Rejected");
});
filter.attemptAuthentication(new MockHttpServletRequest(), new MockHttpServletResponse());
}
@ -96,7 +92,6 @@ public class CasAuthenticationFilterTests {
filter.setFilterProcessesUrl(url);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath(url);
assertThat(filter.requiresAuthentication(request, response)).isTrue();
}
@ -106,7 +101,6 @@ public class CasAuthenticationFilterTests {
CasAuthenticationFilter filter = new CasAuthenticationFilter();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath("/pgtCallback");
assertThat(filter.requiresAuthentication(request, response)).isFalse();
filter.setProxyReceptorUrl(request.getServletPath());
@ -121,17 +115,14 @@ public class CasAuthenticationFilterTests {
public void testRequiresAuthenticationAuthAll() {
ServiceProperties properties = new ServiceProperties();
properties.setAuthenticateAllArtifacts(true);
String url = "/login/cas";
CasAuthenticationFilter filter = new CasAuthenticationFilter();
filter.setFilterProcessesUrl(url);
filter.setServiceProperties(properties);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath(url);
assertThat(filter.requiresAuthentication(request, response)).isTrue();
request.setServletPath("/other");
assertThat(filter.requiresAuthentication(request, response)).isFalse();
request.setParameter(properties.getArtifactParameter(), "value");
@ -151,7 +142,6 @@ public class CasAuthenticationFilterTests {
CasAuthenticationFilter filter = new CasAuthenticationFilter();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath("/pgtCallback");
filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class));
filter.setProxyReceptorUrl(request.getServletPath());
@ -171,20 +161,17 @@ public class CasAuthenticationFilterTests {
request.setServletPath("/authenticate");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
CasAuthenticationFilter filter = new CasAuthenticationFilter();
filter.setServiceProperties(serviceProperties);
filter.setAuthenticationSuccessHandler(successHandler);
filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class));
filter.setAuthenticationManager(manager);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull()
.withFailMessage("Authentication should not be null");
verify(chain).doFilter(request, response);
verifyZeroInteractions(successHandler);
// validate for when the filterProcessUrl matches
filter.setFilterProcessesUrl(request.getServletPath());
SecurityContextHolder.clearContext();
@ -200,11 +187,9 @@ public class CasAuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
request.setServletPath("/pgtCallback");
filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class));
filter.setProxyReceptorUrl(request.getServletPath());
filter.doFilter(request, response, chain);
verifyZeroInteractions(chain);
}

View File

@ -68,10 +68,8 @@ public class ServicePropertiesTests {
assertThat(sp.getArtifactParameter()).isEqualTo("notticket");
sp.setServiceParameter("notservice");
assertThat(sp.getServiceParameter()).isEqualTo("notservice");
sp.setService("https://mycompany.com/service");
assertThat(sp.getService()).isEqualTo("https://mycompany.com/service");
sp.afterPropertiesSet();
}
}

View File

@ -55,7 +55,6 @@ public class DefaultServiceAuthenticationDetailsTests {
this.request.setRequestURI("/cas-sample/secure/");
this.artifactPattern = DefaultServiceAuthenticationDetails
.createArtifactPattern(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER);
}
@After

View File

@ -86,7 +86,6 @@ public class HelloRSocketITests {
public void retrieveMonoWhenSecureThenDenied() throws Exception {
this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
.connectTcp("localhost", this.server.address().getPort()).block();
String data = "rob";
assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
.isNotNull();
@ -106,7 +105,6 @@ public class HelloRSocketITests {
String hiRob = this.requester.route("secure.retrieve-mono")
.metadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE).data(data)
.retrieveMono(String.class).block();
assertThat(hiRob).isEqualTo("Hi rob");
assertThat(this.controller.payloads).containsOnly(data);
}

View File

@ -102,9 +102,7 @@ public class JwtITests {
this.requester = requester()
.setupMetadata(credentials.getToken(), BearerTokenMetadata.BEARER_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
String hiRob = this.requester.route("secure.retrieve-mono").data("rob").retrieveMono(String.class).block();
assertThat(hiRob).isEqualTo("Hi rob");
}
@ -112,14 +110,11 @@ public class JwtITests {
public void routeWhenAuthenticationBearerThenAuthorized() {
MimeType authenticationMimeType = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
BearerTokenMetadata credentials = new BearerTokenMetadata("token");
given(this.decoder.decode(any())).willReturn(Mono.just(jwt()));
this.requester = requester().setupMetadata(credentials, authenticationMimeType)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
String hiRob = this.requester.route("secure.retrieve-mono").data("rob").retrieveMono(String.class).block();
assertThat(hiRob).isEqualTo("Hi rob");
}

View File

@ -94,9 +94,7 @@ public class RSocketMessageHandlerConnectionITests {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
String hiRob = this.requester.route("secure.retrieve-mono").data("rob").retrieveMono(String.class).block();
assertThat(hiRob).isEqualTo("Hi rob");
}
@ -105,7 +103,6 @@ public class RSocketMessageHandlerConnectionITests {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
assertThatCode(() -> this.requester.route("secure.admin.retrieve-mono").data("data").retrieveMono(String.class)
.block()).isInstanceOf(ApplicationErrorException.class);
}
@ -116,12 +113,10 @@ public class RSocketMessageHandlerConnectionITests {
this.requester = requester()
.setupMetadata(connectCredentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
String hiRob = this.requester.route("secure.admin.retrieve-mono")
.metadata(new UsernamePasswordMetadata("admin", "password"),
UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.data("rob").retrieveMono(String.class).block();
assertThat(hiRob).isEqualTo("Hi rob");
}
@ -131,12 +126,10 @@ public class RSocketMessageHandlerConnectionITests {
this.requester = requester()
.setupMetadata(connectCredentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
String hiUser = this.requester.route("secure.authority.retrieve-mono")
.metadata(new UsernamePasswordMetadata("admin", "password"),
UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.data("Felipe").retrieveMono(String.class).block();
assertThat(hiUser).isEqualTo("Hi Felipe");
}
@ -144,7 +137,6 @@ public class RSocketMessageHandlerConnectionITests {
public void connectWhenNotAuthenticated() {
this.requester = requester().connectTcp(this.server.address().getHostName(), this.server.address().getPort())
.block();
assertThatCode(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
.isNotNull();
// FIXME: https://github.com/rsocket/rsocket-java/issues/686
@ -156,7 +148,6 @@ public class RSocketMessageHandlerConnectionITests {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("evil", "password");
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
assertThatCode(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
.isNotNull();
// FIXME: https://github.com/rsocket/rsocket-java/issues/686
@ -168,7 +159,6 @@ public class RSocketMessageHandlerConnectionITests {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
assertThatCode(() -> this.requester.route("prohibit").data("data").retrieveMono(String.class).block())
.isInstanceOf(ApplicationErrorException.class);
}
@ -178,9 +168,7 @@ public class RSocketMessageHandlerConnectionITests {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
String hiRob = this.requester.route("anyroute").data("rob").retrieveMono(String.class).block();
assertThat(hiRob).isEqualTo("Hi rob");
}
@ -189,9 +177,7 @@ public class RSocketMessageHandlerConnectionITests {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("admin", "password");
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
String hiEbert = this.requester.route("management.users").data("admin").retrieveMono(String.class).block();
assertThat(hiEbert).isEqualTo("Hi admin");
}

View File

@ -79,7 +79,6 @@ public class RSocketMessageHandlerITests {
this.server = RSocketFactory.receive().frameDecoder(PayloadDecoder.ZERO_COPY)
.addSocketAcceptorPlugin(this.interceptor).acceptor(this.handler.responder())
.transport(TcpServerTransport.create("localhost", 0)).start().block();
this.requester = RSocketRequester.builder()
// .rsocketFactory((factory) ->
// factory.addRequesterPlugin(payloadInterceptor))
@ -99,7 +98,6 @@ public class RSocketMessageHandlerITests {
String data = "rob";
assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
.isInstanceOf(ApplicationErrorException.class).hasMessageContaining("Access Denied");
assertThat(this.controller.payloads).isEmpty();
}
@ -111,7 +109,6 @@ public class RSocketMessageHandlerITests {
.metadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE).data(data)
.retrieveMono(String.class).block()).isInstanceOf(ApplicationErrorException.class)
.hasMessageContaining("Invalid Credentials");
assertThat(this.controller.payloads).isEmpty();
}
@ -122,7 +119,6 @@ public class RSocketMessageHandlerITests {
String hiRob = this.requester.route("secure.retrieve-mono")
.metadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE).data(data)
.retrieveMono(String.class).block();
assertThat(hiRob).isEqualTo("Hi rob");
assertThat(this.controller.payloads).containsOnly(data);
}
@ -131,7 +127,6 @@ public class RSocketMessageHandlerITests {
public void retrieveMonoWhenPublicThenGranted() throws Exception {
String data = "rob";
String hiRob = this.requester.route("retrieve-mono").data(data).retrieveMono(String.class).block();
assertThat(hiRob).isEqualTo("Hi rob");
assertThat(this.controller.payloads).containsOnly(data);
}
@ -142,7 +137,6 @@ public class RSocketMessageHandlerITests {
assertThatCode(() -> this.requester.route("secure.retrieve-flux").data(data, String.class)
.retrieveFlux(String.class).collectList().block()).isInstanceOf(ApplicationErrorException.class)
.hasMessageContaining("Access Denied");
assertThat(this.controller.payloads).isEmpty();
}
@ -151,7 +145,6 @@ public class RSocketMessageHandlerITests {
Flux<String> data = Flux.just("a", "b", "c");
List<String> hi = this.requester.route("retrieve-flux").data(data, String.class).retrieveFlux(String.class)
.collectList().block();
assertThat(hi).containsOnly("hello a", "hello b", "hello c");
assertThat(this.controller.payloads).containsOnlyElementsOf(data.collectList().block());
}
@ -162,7 +155,6 @@ public class RSocketMessageHandlerITests {
assertThatCode(
() -> this.requester.route("secure.hello").data(data).retrieveFlux(String.class).collectList().block())
.isInstanceOf(ApplicationErrorException.class).hasMessageContaining("Access Denied");
assertThat(this.controller.payloads).isEmpty();
}
@ -170,7 +162,6 @@ public class RSocketMessageHandlerITests {
public void sendWhenSecureThenDenied() throws Exception {
String data = "hi";
this.requester.route("secure.send").data(data).send().block();
assertThat(this.controller.payloads).isEmpty();
}
@ -248,7 +239,6 @@ public class RSocketMessageHandlerITests {
@MessageMapping({ "secure.send", "send" })
Mono<Void> send(Mono<String> payload) {
return payload.doOnNext(this::add).then(Mono.fromRunnable(() -> doNotifyAll()));
}
private synchronized void doNotifyAll() {

View File

@ -92,7 +92,6 @@ public class SimpleAuthenticationITests {
public void retrieveMonoWhenSecureThenDenied() throws Exception {
this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
.connectTcp("localhost", this.server.address().getPort()).block();
String data = "rob";
assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
.isInstanceOf(ApplicationErrorException.class);
@ -103,7 +102,6 @@ public class SimpleAuthenticationITests {
public void retrieveMonoWhenAuthorizedThenGranted() {
MimeType authenticationMimeType = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("rob", "password");
this.requester = RSocketRequester.builder().setupMetadata(credentials, authenticationMimeType)
.rsocketStrategies(this.handler.getRSocketStrategies())
@ -111,7 +109,6 @@ public class SimpleAuthenticationITests {
String data = "rob";
String hiRob = this.requester.route("secure.retrieve-mono").metadata(credentials, authenticationMimeType)
.data(data).retrieveMono(String.class).block();
assertThat(hiRob).isEqualTo("Hi rob");
assertThat(this.controller.payloads).containsOnly(data);
}

View File

@ -34,13 +34,11 @@ public class DataSourcePopulator implements InitializingBean {
@Override
public void afterPropertiesSet() {
Assert.notNull(this.template, "dataSource required");
this.template.execute(
"CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(500) NOT NULL,ENABLED BOOLEAN NOT NULL);");
this.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));");
this.template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);");
/*
* Passwords encoded using MD5, NOT in Base64 format, with null as salt Encoded
* password for rod is "koala" Encoded password for dianne is "emu" Encoded

View File

@ -111,7 +111,6 @@ public class FilterChainProxyConfigTests {
@Test
public void mixingPatternsAndPlaceholdersDoesntCauseOrderingIssues() {
FilterChainProxy fcp = this.appCtx.getBean("sec1235FilterChainProxy", FilterChainProxy.class);
List<SecurityFilterChain> chains = fcp.getFilterChains();
assertThat(getPattern(chains.get(0))).isEqualTo("/login*");
assertThat(getPattern(chains.get(1))).isEqualTo("/logout");
@ -127,17 +126,14 @@ public class FilterChainProxyConfigTests {
List<Filter> filters = filterChainProxy.getFilters("/foo/blah;x=1");
assertThat(filters).hasSize(1);
assertThat(filters.get(0) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
filters = filterChainProxy.getFilters("/some;x=2,y=3/other/path;z=4/blah");
assertThat(filters).isNotNull();
assertThat(filters).hasSize(3);
assertThat(filters.get(0) instanceof SecurityContextPersistenceFilter).isTrue();
assertThat(filters.get(1) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
assertThat(filters.get(2) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
filters = filterChainProxy.getFilters("/do/not/filter;x=7");
assertThat(filters).isEmpty();
filters = filterChainProxy.getFilters("/another/nonspecificmatch");
assertThat(filters).hasSize(3);
assertThat(filters.get(0) instanceof SecurityContextPersistenceFilter).isTrue();
@ -148,13 +144,10 @@ public class FilterChainProxyConfigTests {
private void doNormalOperation(FilterChainProxy filterChainProxy) throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/foo/secure/super/somefile.html");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filterChainProxy.doFilter(request, response, chain);
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
request.setServletPath("/a/path/which/doesnt/match/any/filter.html");
chain = mock(FilterChain.class);
filterChainProxy.doFilter(request, response, chain);

View File

@ -37,7 +37,6 @@ public class MockUserServiceBeanPostProcessor implements BeanPostProcessor {
if (bean instanceof PostProcessedMockUserDetailsService) {
((PostProcessedMockUserDetailsService) bean).setPostProcessorWasHere("Hello from the post processor!");
}
return bean;
}

View File

@ -90,13 +90,10 @@ public class SecurityNamespaceHandlerTests {
PowerMockito.spy(ClassUtils.class);
PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
Log logger = mock(Log.class);
SecurityNamespaceHandler handler = new SecurityNamespaceHandler();
ReflectionTestUtils.setField(handler, "logger", logger);
handler.init();
PowerMockito.verifyStatic(ClassUtils.class);
ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
verifyZeroInteractions(logger);

View File

@ -43,10 +43,8 @@ public class SecurityConfigurerAdapterClosureTests {
return l;
}
});
this.conf.init(builder);
this.conf.configure(builder);
assertThat(this.conf.list).contains("a");
}

View File

@ -36,7 +36,6 @@ public class SecurityConfigurerAdapterTests {
public void postProcessObjectPostProcessorsAreSorted() {
this.adapter.addObjectPostProcessor(new OrderedObjectPostProcessor(Ordered.LOWEST_PRECEDENCE));
this.adapter.addObjectPostProcessor(new OrderedObjectPostProcessor(Ordered.HIGHEST_PRECEDENCE));
assertThat(this.adapter.postProcess("hi"))
.isEqualTo("hi " + Ordered.HIGHEST_PRECEDENCE + " " + Ordered.LOWEST_PRECEDENCE);
}

View File

@ -76,11 +76,9 @@ public class AuthenticationManagerBuilderTests {
public void buildWhenAddAuthenticationProviderThenDoesNotPerformRegistration() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationProvider provider = mock(AuthenticationProvider.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.authenticationProvider(provider);
builder.build();
verify(opp, never()).postProcess(provider);
}
@ -92,13 +90,11 @@ public class AuthenticationManagerBuilderTests {
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build();
try {
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
catch (AuthenticationException success) {
}
verify(aep).publishAuthenticationFailure(any(), any());
}
@ -107,9 +103,7 @@ public class AuthenticationManagerBuilderTests {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThat(auth.getName()).isEqualTo("user");
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
}
@ -119,9 +113,7 @@ public class AuthenticationManagerBuilderTests {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThat(auth.getName()).isEqualTo("user");
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
}
@ -129,9 +121,7 @@ public class AuthenticationManagerBuilderTests {
@Test
public void authenticationManagerWhenMultipleProvidersThenWorks() throws Exception {
this.spring.register(MultiAuthenticationProvidersConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user").withRoles("USER"));
this.mockMvc.perform(formLogin().user("admin"))
.andExpect(authenticated().withUsername("admin").withRoles("USER", "ADMIN"));
}
@ -140,11 +130,9 @@ public class AuthenticationManagerBuilderTests {
public void buildWhenAuthenticationProviderThenIsConfigured() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationProvider provider = mock(AuthenticationProvider.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.authenticationProvider(provider);
builder.build();
assertThat(builder.isConfigured()).isTrue();
}
@ -152,27 +140,22 @@ public class AuthenticationManagerBuilderTests {
public void buildWhenParentThenIsConfigured() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationManager parent = mock(AuthenticationManager.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.parentAuthenticationManager(parent);
builder.build();
assertThat(builder.isConfigured()).isTrue();
}
@Test
public void buildWhenNotConfiguredThenIsConfiguredFalse() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.build();
assertThat(builder.isConfigured()).isFalse();
}
public void buildWhenUserFromProperties() throws Exception {
this.spring.register(UserFromPropertiesConfig.class).autowire();
this.mockMvc.perform(formLogin().user("joe", "joespassword"))
.andExpect(authenticated().withUsername("joe").withRoles("USER"));
}

View File

@ -47,10 +47,8 @@ public class NamespaceAuthenticationManagerTests {
@Test
public void authenticationMangerWhenDefaultThenEraseCredentialsIsTrue() throws Exception {
this.spring.register(EraseCredentialsTrueDefaultConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNull()));
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNull()));
// no exception due to username being cleared out
@ -59,10 +57,8 @@ public class NamespaceAuthenticationManagerTests {
@Test
public void authenticationMangerWhenEraseCredentialsIsFalseThenCredentialsNotNull() throws Exception {
this.spring.register(EraseCredentialsFalseConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
// no exception due to username being cleared out
@ -72,7 +68,6 @@ public class NamespaceAuthenticationManagerTests {
// SEC-2533
public void authenticationManagerWhenGlobalAndEraseCredentialsIsFalseThenCredentialsNotNull() throws Exception {
this.spring.register(GlobalEraseCredentialsFalseConfig.class).autowire();
this.mockMvc.perform(SecurityMockMvcRequestBuilders.formLogin()).andExpect(SecurityMockMvcResultMatchers
.authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
}

View File

@ -49,7 +49,6 @@ public class NamespaceAuthenticationProviderTests {
// authentication-provider@ref
public void authenticationProviderRef() throws Exception {
this.spring.register(AuthenticationProviderRefConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user"));
}
@ -57,7 +56,6 @@ public class NamespaceAuthenticationProviderTests {
// authentication-provider@user-service-ref
public void authenticationProviderUserServiceRef() throws Exception {
this.spring.register(AuthenticationProviderRefConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user"));
}

View File

@ -53,14 +53,12 @@ public class NamespaceJdbcUserServiceTests {
@Test
public void jdbcUserService() throws Exception {
this.spring.register(DataSourceConfig.class, JdbcUserServiceConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user"));
}
@Test
public void jdbcUserServiceCustom() throws Exception {
this.spring.register(CustomDataSourceConfig.class, CustomJdbcUserServiceSampleConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user").withRoles("DBA", "USER"));
}
@ -118,7 +116,6 @@ public class NamespaceJdbcUserServiceTests {
// jdbc-user-service@role-prefix
.rolePrefix("ROLE_");
// @formatter:on
}
static class CustomUserCache implements UserCache {

View File

@ -52,21 +52,18 @@ public class NamespacePasswordEncoderTests {
@Test
public void passwordEncoderRefWithInMemory() throws Exception {
this.spring.register(PasswordEncoderWithInMemoryConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated());
}
@Test
public void passwordEncoderRefWithJdbc() throws Exception {
this.spring.register(PasswordEncoderWithJdbcConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated());
}
@Test
public void passwordEncoderRefWithUserDetailsService() throws Exception {
this.spring.register(PasswordEncoderWithUserDetailsServiceConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated());
}
@ -91,7 +88,6 @@ public class NamespacePasswordEncoderTests {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// @formatter:off
auth

View File

@ -51,7 +51,6 @@ public class PasswordEncoderConfigurerTests {
@Test
public void passwordEncoderRefWhenAuthenticationManagerBuilderThenAuthenticationSuccess() throws Exception {
this.spring.register(PasswordEncoderNoAuthManagerLoadsConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated());
}

View File

@ -48,7 +48,6 @@ public class AuthenticationConfigurationPublishTests {
@Test
public void authenticationEventPublisherBeanUsedByDefault() {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThat(this.listener.getEvents()).hasSize(1);
}

View File

@ -88,7 +88,6 @@ public class AuthenticationConfigurationTests {
public void orderingAutowiredOnEnableGlobalMethodSecurity() {
this.spring.register(AuthenticationTestConfiguration.class, GlobalMethodSecurityAutowiredConfig.class,
ServicesConfig.class).autowire();
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.service.run();
@ -98,7 +97,6 @@ public class AuthenticationConfigurationTests {
public void orderingAutowiredOnEnableWebSecurity() {
this.spring.register(AuthenticationTestConfiguration.class, WebSecurityConfig.class,
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class).autowire();
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.service.run();
@ -108,7 +106,6 @@ public class AuthenticationConfigurationTests {
public void orderingAutowiredOnEnableWebMvcSecurity() {
this.spring.register(AuthenticationTestConfiguration.class, WebMvcSecurityConfig.class,
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class).autowire();
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.service.run();
@ -117,7 +114,6 @@ public class AuthenticationConfigurationTests {
@Test
public void getAuthenticationManagerWhenNoAuthenticationThenNull() throws Exception {
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class).autowire();
assertThat(this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager())
.isNull();
}
@ -126,7 +122,6 @@ public class AuthenticationConfigurationTests {
public void getAuthenticationManagerWhenNoOpGlobalAuthenticationConfigurerAdapterThenNull() throws Exception {
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
NoOpGlobalAuthenticationConfigurerAdapter.class).autowire();
assertThat(this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager())
.isNull();
}
@ -136,10 +131,8 @@ public class AuthenticationConfigurationTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
UserGlobalAuthenticationConfigurerAdapter.class).autowire();
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName());
}
@ -148,11 +141,9 @@ public class AuthenticationConfigurationTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
AuthenticationManagerBeanConfig.class).autowire();
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
given(authentication.authenticate(token)).willReturn(TestAuthentication.authenticatedUser());
assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName());
}
@ -173,13 +164,10 @@ public class AuthenticationConfigurationTests {
config.setGlobalAuthenticationConfigurers(Arrays.asList(new ConfiguresInMemoryConfigurerAdapter(),
new BootGlobalAuthenticationConfigurerAdapter()));
AuthenticationManager authenticationManager = config.getAuthenticationManager();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(
() -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password")))
.isInstanceOf(AuthenticationException.class);
}
@Test
@ -188,7 +176,6 @@ public class AuthenticationConfigurationTests {
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
config.setGlobalAuthenticationConfigurers(Arrays.asList(new BootGlobalAuthenticationConfigurerAdapter()));
AuthenticationManager authenticationManager = config.getAuthenticationManager();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password"));
}
@ -198,17 +185,14 @@ public class AuthenticationConfigurationTests {
this.spring.register(Sec2531Config.class).autowire();
ObjectPostProcessor<Object> opp = this.spring.getContext().getBean(ObjectPostProcessor.class);
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
config.getAuthenticationManager();
verify(opp).postProcess(any(ProxyFactoryBean.class));
}
@Test
public void getAuthenticationManagerWhenSec2822ThenCannotForceAuthenticationAlreadyBuilt() throws Exception {
this.spring.register(Sec2822WebSecurity.class, Sec2822UseAuth.class, Sec2822Config.class).autowire();
this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
// no exception
}
@ -222,9 +206,7 @@ public class AuthenticationConfigurationTests {
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
.isInstanceOf(AuthenticationException.class);
}
@ -239,9 +221,7 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
.isInstanceOf(AuthenticationException.class);
}
@ -257,9 +237,7 @@ public class AuthenticationConfigurationTests {
given(manager.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build());
given(manager.updatePassword(any(), any())).willReturn(user);
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
verify(manager).updatePassword(eq(user), startsWith("{bcrypt}"));
}
@ -272,7 +250,6 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
@ -285,7 +262,6 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
@ -314,9 +290,7 @@ public class AuthenticationConfigurationTests {
throws Exception {
this.spring.register(AuthenticationConfigurationSubclass.class).autowire();
AuthenticationManagerBuilder ap = this.spring.getContext().getBean(AuthenticationManagerBuilder.class);
this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
assertThatThrownBy(ap::build).isInstanceOf(AlreadyBuiltException.class);
}
@ -447,15 +421,11 @@ public class AuthenticationConfigurationTests {
if (auth.isConfigured()) {
return;
}
UserDetails user = User.withUserDetails(PasswordEncodedUser.user()).username("boot").build();
List<UserDetails> users = Arrays.asList(user);
InMemoryUserDetailsManager inMemory = new InMemoryUserDetailsManager(users);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(inMemory);
auth.authenticationProvider(provider);
}

View File

@ -40,29 +40,23 @@ public class EnableGlobalAuthenticationTests {
@Test
public void authenticationConfigurationWhenGetAuthenticationManagerThenNotNull() throws Exception {
this.spring.register(Config.class).autowire();
AuthenticationConfiguration auth = this.spring.getContext().getBean(AuthenticationConfiguration.class);
assertThat(auth.getAuthenticationManager()).isNotNull();
}
@Test
public void enableGlobalAuthenticationWhenNoConfigurationAnnotationThenBeanProxyingEnabled() {
this.spring.register(BeanProxyEnabledByDefaultConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isSameAs(childBean);
}
@Test
public void enableGlobalAuthenticationWhenProxyBeanMethodsFalseThenBeanProxyingDisabled() {
this.spring.register(BeanProxyDisabledConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isNotSameAs(childBean);
}

View File

@ -40,7 +40,6 @@ public class LdapAuthenticationProviderConfigurerTests {
assertThat(this.configurer.getAuthoritiesMapper()).isInstanceOf(SimpleAuthorityMapper.class);
this.configurer.authoritiesMapper(new NullAuthoritiesMapper());
assertThat(this.configurer.getAuthoritiesMapper()).isInstanceOf(NullAuthoritiesMapper.class);
}
}

View File

@ -46,7 +46,6 @@ public class UserDetailsManagerConfigurerTests {
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
this.userDetailsManager).withUser("user").password("password").roles("USER").disabled(true)
.accountExpired(true).accountLocked(true).credentialsExpired(true).build();
assertThat(userDetails.getUsername()).isEqualTo("user");
assertThat(userDetails.getPassword()).isEqualTo("password");
assertThat(userDetails.getAuthorities().stream().findFirst().get().getAuthority()).isEqualTo("ROLE_USER");
@ -59,31 +58,25 @@ public class UserDetailsManagerConfigurerTests {
@Test
public void authoritiesWithGrantedAuthorityWorks() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
this.userDetailsManager).withUser("user").password("password").authorities(authority).build();
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority);
}
@Test
public void authoritiesWithStringAuthorityWorks() {
String authority = "ROLE_USER";
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
this.userDetailsManager).withUser("user").password("password").authorities(authority).build();
assertThat(userDetails.getAuthorities().stream().findFirst().get().getAuthority()).isEqualTo(authority);
}
@Test
public void authoritiesWithAListOfGrantedAuthorityWorks() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
this.userDetailsManager).withUser("user").password("password").authorities(Arrays.asList(authority))
.build();
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority);
}

View File

@ -54,7 +54,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenApplicationContextAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
ApplicationContextAware toPostProcess = mock(ApplicationContextAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setApplicationContext(isNotNull());
@ -63,17 +62,14 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenApplicationEventPublisherAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
ApplicationEventPublisherAware toPostProcess = mock(ApplicationEventPublisherAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setApplicationEventPublisher(isNotNull());
}
@Test
public void postProcessWhenBeanClassLoaderAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
BeanClassLoaderAware toPostProcess = mock(BeanClassLoaderAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setBeanClassLoader(isNotNull());
@ -82,7 +78,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenBeanFactoryAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
BeanFactoryAware toPostProcess = mock(BeanFactoryAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setBeanFactory(isNotNull());
@ -91,7 +86,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenEnvironmentAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
EnvironmentAware toPostProcess = mock(EnvironmentAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setEnvironment(isNotNull());
@ -100,7 +94,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenMessageSourceAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
MessageSourceAware toPostProcess = mock(MessageSourceAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setMessageSource(isNotNull());
@ -109,7 +102,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenServletContextAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
ServletContextAware toPostProcess = mock(ServletContextAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setServletContext(isNotNull());
@ -118,21 +110,16 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenDisposableBeanThenAwareInvoked() throws Exception {
this.spring.register(Config.class).autowire();
DisposableBean toPostProcess = mock(DisposableBean.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
this.spring.getContext().close();
verify(toPostProcess).destroy();
}
@Test
public void postProcessWhenSmartInitializingSingletonThenAwareInvoked() {
this.spring.register(Config.class, SmartConfig.class).autowire();
SmartConfig config = this.spring.getContext().getBean(SmartConfig.class);
verify(config.toTest).afterSingletonsInstantiated();
}
@ -140,9 +127,7 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
// SEC-2382
public void autowireBeanFactoryWhenBeanNameAutoProxyCreatorThenWorks() {
this.spring.testConfigLocations("AutowireBeanFactoryObjectPostProcessorTests-aopconfig.xml").autowire();
MyAdvisedBean bean = this.spring.getContext().getBean(MyAdvisedBean.class);
assertThat(bean.doStuff()).isEqualTo("null");
}

View File

@ -52,12 +52,10 @@ public class ApplicationConfig {
vendorAdapter.setDatabase(Database.HSQL);
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(User.class.getPackage().getName());
factory.setDataSource(dataSource());
return factory;
}

View File

@ -81,23 +81,19 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoWhenPermitAllThenAopDoesNotSubscribe() {
given(this.delegate.monoFindById(1L)).willReturn(Mono.from(this.result));
this.delegate.monoFindById(1L);
this.result.assertNoSubscribers();
}
@Test
public void monoWhenPermitAllThenSuccess() {
given(this.delegate.monoFindById(1L)).willReturn(Mono.just("success"));
StepVerifier.create(this.delegate.monoFindById(1L)).expectNext("success").verifyComplete();
}
@Test
public void monoPreAuthorizeHasRoleWhenGrantedThenSuccess() {
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
@ -106,28 +102,23 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void monoPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void monoPreAuthorizeBeanWhenGrantedThenSuccess() {
given(this.delegate.monoPreAuthorizeBeanFindById(2L)).willReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(2L).subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@ -135,7 +126,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeBeanWhenNotAuthenticatedAndGrantedThenSuccess() {
given(this.delegate.monoPreAuthorizeBeanFindById(2L)).willReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@ -143,27 +133,22 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
given(this.delegate.monoPreAuthorizeBeanFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void monoPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
given(this.delegate.monoPreAuthorizeBeanFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void monoPostAuthorizeWhenAuthorizedThenSuccess() {
given(this.delegate.monoPostAuthorizeFindById(1L)).willReturn(Mono.just("user"));
Mono<String> findById = this.messageService.monoPostAuthorizeFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@ -171,7 +156,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenNotAuthorizedThenDenied() {
given(this.delegate.monoPostAuthorizeBeanFindById(1L)).willReturn(Mono.just("not-authorized"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@ -179,7 +163,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
given(this.delegate.monoPostAuthorizeBeanFindById(2L)).willReturn(Mono.just("user"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(2L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@ -187,7 +170,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenBeanAndNotAuthenticatedAndAuthorizedThenSuccess() {
given(this.delegate.monoPostAuthorizeBeanFindById(2L)).willReturn(Mono.just("anonymous"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("anonymous").verifyComplete();
}
@ -195,33 +177,27 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
given(this.delegate.monoPostAuthorizeBeanFindById(1L)).willReturn(Mono.just("not-authorized"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
// Flux tests
@Test
public void fluxWhenPermitAllThenAopDoesNotSubscribe() {
given(this.delegate.fluxFindById(1L)).willReturn(Flux.from(this.result));
this.delegate.fluxFindById(1L);
this.result.assertNoSubscribers();
}
@Test
public void fluxWhenPermitAllThenSuccess() {
given(this.delegate.fluxFindById(1L)).willReturn(Flux.just("success"));
StepVerifier.create(this.delegate.fluxFindById(1L)).expectNext("success").verifyComplete();
}
@Test
public void fluxPreAuthorizeHasRoleWhenGrantedThenSuccess() {
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).consumeNextWith((s) -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
@ -231,28 +207,23 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void fluxPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void fluxPreAuthorizeBeanWhenGrantedThenSuccess() {
given(this.delegate.fluxPreAuthorizeBeanFindById(2L)).willReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(2L).subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@ -260,7 +231,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeBeanWhenNotAuthenticatedAndGrantedThenSuccess() {
given(this.delegate.fluxPreAuthorizeBeanFindById(2L)).willReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@ -268,27 +238,22 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
given(this.delegate.fluxPreAuthorizeBeanFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void fluxPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
given(this.delegate.fluxPreAuthorizeBeanFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void fluxPostAuthorizeWhenAuthorizedThenSuccess() {
given(this.delegate.fluxPostAuthorizeFindById(1L)).willReturn(Flux.just("user"));
Flux<String> findById = this.messageService.fluxPostAuthorizeFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@ -296,7 +261,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenNotAuthorizedThenDenied() {
given(this.delegate.fluxPostAuthorizeBeanFindById(1L)).willReturn(Flux.just("not-authorized"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@ -304,7 +268,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
given(this.delegate.fluxPostAuthorizeBeanFindById(2L)).willReturn(Flux.just("user"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(2L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@ -312,7 +275,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenBeanAndNotAuthenticatedAndAuthorizedThenSuccess() {
given(this.delegate.fluxPostAuthorizeBeanFindById(2L)).willReturn(Flux.just("anonymous"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("anonymous").verifyComplete();
}
@ -320,33 +282,27 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
given(this.delegate.fluxPostAuthorizeBeanFindById(1L)).willReturn(Flux.just("not-authorized"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
// Publisher tests
@Test
public void publisherWhenPermitAllThenAopDoesNotSubscribe() {
given(this.delegate.publisherFindById(1L)).willReturn(this.result);
this.delegate.publisherFindById(1L);
this.result.assertNoSubscribers();
}
@Test
public void publisherWhenPermitAllThenSuccess() {
given(this.delegate.publisherFindById(1L)).willReturn(publisherJust("success"));
StepVerifier.create(this.delegate.publisherFindById(1L)).expectNext("success").verifyComplete();
}
@Test
public void publisherPreAuthorizeHasRoleWhenGrantedThenSuccess() {
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(publisherJust("result"));
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).consumeNextWith((s) -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
@ -356,28 +312,23 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(this.result);
Publisher<String> findById = this.messageService.publisherPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void publisherPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(this.result);
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void publisherPreAuthorizeBeanWhenGrantedThenSuccess() {
given(this.delegate.publisherPreAuthorizeBeanFindById(2L)).willReturn(publisherJust("result"));
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(2L))
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
@ -386,7 +337,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeBeanWhenNotAuthenticatedAndGrantedThenSuccess() {
given(this.delegate.publisherPreAuthorizeBeanFindById(2L)).willReturn(publisherJust("result"));
Publisher<String> findById = this.messageService.publisherPreAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@ -394,28 +344,23 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
given(this.delegate.publisherPreAuthorizeBeanFindById(1L)).willReturn(this.result);
Publisher<String> findById = this.messageService.publisherPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void publisherPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
given(this.delegate.publisherPreAuthorizeBeanFindById(1L)).willReturn(this.result);
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void publisherPostAuthorizeWhenAuthorizedThenSuccess() {
given(this.delegate.publisherPostAuthorizeFindById(1L)).willReturn(publisherJust("user"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
@ -424,7 +369,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenNotAuthorizedThenDenied() {
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@ -433,7 +377,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
given(this.delegate.publisherPostAuthorizeBeanFindById(2L)).willReturn(publisherJust("user"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(2L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
@ -442,7 +385,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenBeanAndNotAuthenticatedAndAuthorizedThenSuccess() {
given(this.delegate.publisherPostAuthorizeBeanFindById(2L)).willReturn(publisherJust("anonymous"));
Publisher<String> findById = this.messageService.publisherPostAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("anonymous").verifyComplete();
}
@ -450,7 +392,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();

View File

@ -110,13 +110,11 @@ public class GlobalMethodSecurityConfigurationTests {
@Test
public void methodSecurityAuthenticationManagerPublishesEvent() {
this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire();
try {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar"));
}
catch (AuthenticationException ex) {
}
assertThat(this.events.getEvents()).extracting(Object::getClass)
.containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class);
}
@ -125,14 +123,10 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void methodSecurityWhenAuthenticationTrustResolverIsBeanThenAutowires() {
this.spring.register(CustomTrustResolverConfig.class).autowire();
AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class);
given(trustResolver.isAnonymous(any())).willReturn(true, false);
assertThatThrownBy(() -> this.service.preAuthorizeNotAnonymous()).isInstanceOf(AccessDeniedException.class);
this.service.preAuthorizeNotAnonymous();
verify(trustResolver, atLeastOnce()).isAnonymous(any());
}
@ -142,9 +136,7 @@ public class GlobalMethodSecurityConfigurationTests {
public void defaultWebSecurityExpressionHandlerHasBeanResolverSet() {
this.spring.register(ExpressionHandlerHasBeanResolverSetConfig.class).autowire();
Authz authz = this.spring.getContext().getBean(Authz.class);
assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class);
this.service.preAuthorizeBean(true);
}
@ -152,9 +144,7 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void methodSecuritySupportsAnnotaitonsOnInterfaceParamerNames() {
this.spring.register(MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.postAnnotation("deny")).isInstanceOf(AccessDeniedException.class);
this.service.postAnnotation("grant");
// no exception
}
@ -165,17 +155,14 @@ public class GlobalMethodSecurityConfigurationTests {
this.spring.register(AutowirePermissionEvaluatorConfig.class).autowire();
PermissionEvaluator permission = this.spring.getContext().getBean(PermissionEvaluator.class);
given(permission.hasPermission(any(), eq("something"), eq("read"))).willReturn(true, false);
this.service.hasPermission("something");
// no exception
assertThatThrownBy(() -> this.service.hasPermission("something")).isInstanceOf(AccessDeniedException.class);
}
@Test
public void multiPermissionEvaluatorConfig() {
this.spring.register(MultiPermissionEvaluatorConfig.class).autowire();
// no exception
}
@ -184,7 +171,6 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void enableGlobalMethodSecurityWorksOnSuperclass() {
this.spring.register(ChildConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@ -200,7 +186,6 @@ public class GlobalMethodSecurityConfigurationTests {
child.register(Sec2479ChildConfig.class);
child.refresh();
this.spring.context(child).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
}
@ -209,9 +194,7 @@ public class GlobalMethodSecurityConfigurationTests {
@Test
public void enableGlobalMethodSecurityDoesNotTriggerEagerInitializationOfBeansInGlobalAuthenticationConfigurer() {
this.spring.register(Sec2815Config.class).autowire();
MockBeanPostProcessor pp = this.spring.getContext().getBean(MockBeanPostProcessor.class);
assertThat(pp.beforeInit).containsKeys("dataSource");
assertThat(pp.afterInit).containsKeys("dataSource");
}
@ -220,9 +203,9 @@ public class GlobalMethodSecurityConfigurationTests {
@Test
public void globalSecurityProxiesSecurity() {
this.spring.register(Sec3005Config.class).autowire();
assertThat(this.service.getClass()).matches((c) -> !Proxy.isProxyClass(c), "is not proxy class");
}
//
// // gh-3797
// def preAuthorizeBeanSpel() {
@ -241,14 +224,11 @@ public class GlobalMethodSecurityConfigurationTests {
// thrown(AccessDeniedException)
// }
//
@Test
@WithMockUser
public void preAuthorizeBeanSpel() {
this.spring.register(PreAuthorizeBeanSpelConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class);
this.service.preAuthorizeBean(true);
}
@ -257,7 +237,6 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void roleHierarchy() {
this.spring.register(RoleHierarchyConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
this.service.preAuthorizeAdmin();
}
@ -266,12 +245,9 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser(authorities = "ROLE:USER")
public void grantedAuthorityDefaultsAutowires() {
this.spring.register(CustomGrantedAuthorityConfig.class).autowire();
CustomGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
.getBean(CustomGrantedAuthorityConfig.CustomAuthorityService.class);
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
customService.customPrefixRoleUser();
// no exception
}
@ -280,12 +256,9 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser(authorities = "USER")
public void grantedAuthorityDefaultsWithEmptyRolePrefix() {
this.spring.register(EmptyRolePrefixGrantedAuthorityConfig.class).autowire();
EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
.getBean(EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService.class);
assertThatThrownBy(() -> this.service.securedUser()).isInstanceOf(AccessDeniedException.class);
customService.emptyPrefixRoleUser();
// no exception
}
@ -297,7 +270,6 @@ public class GlobalMethodSecurityConfigurationTests {
.getBean(MethodInterceptor.class);
MethodSecurityMetadataSource methodSecurityMetadataSource = this.spring.getContext()
.getBean(MethodSecurityMetadataSource.class);
assertThat(methodInterceptor.getSecurityMetadataSource()).isSameAs(methodSecurityMetadataSource);
}

View File

@ -54,9 +54,7 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
@WithMockUser
public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPreAuthorizesAccordingly() {
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.hasPermission("granted")).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.hasPermission("denied")).isInstanceOf(AccessDeniedException.class);
}
@ -64,9 +62,7 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
@WithMockUser
public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPostAuthorizesAccordingly() {
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.postHasPermission("granted")).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.postHasPermission("denied")).isInstanceOf(AccessDeniedException.class);
}
@ -76,7 +72,6 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(new PermissionEvaluator() {
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject,
@ -90,7 +85,6 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
throw new UnsupportedOperationException();
}
});
return expressionHandler;
}

View File

@ -78,18 +78,14 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenCustomAccessDecisionManagerThenAuthorizes() {
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class);
}
@Test
@WithMockUser
public void methodSecurityWhenCustomAfterInvocationManagerThenAuthorizes() {
this.spring.register(CustomAfterInvocationManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorizePermitAll()).isInstanceOf(AccessDeniedException.class);
}
@ -97,7 +93,6 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenCustomAuthenticationManagerThenAuthorizes() {
this.spring.register(CustomAuthenticationConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(UnsupportedOperationException.class);
}
@ -105,15 +100,10 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenJsr250EnabledThenAuthorizes() {
this.spring.register(Jsr250Config.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.preAuthorize()).doesNotThrowAnyException();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
assertThatCode(() -> this.service.jsr250PermitAll()).doesNotThrowAnyException();
}
@Test
@ -121,11 +111,8 @@ public class NamespaceGlobalMethodSecurityTests {
public void methodSecurityWhenCustomMethodSecurityMetadataSourceThenAuthorizes() {
this.spring.register(CustomMethodSecurityMetadataSourceConfig.class, MethodSecurityServiceConfig.class)
.autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
}
@ -133,12 +120,10 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void contextRefreshWhenUsingAspectJThenAutowire() throws Exception {
this.spring.register(AspectJModeConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.spring.getContext().getBean(
Class.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect")))
.isNotNull();
assertThat(this.spring.getContext().getBean(AspectJMethodSecurityInterceptor.class)).isNotNull();
// TODO diagnose why aspectj isn't weaving method security advice around
// MethodSecurityServiceImpl
}
@ -146,24 +131,19 @@ public class NamespaceGlobalMethodSecurityTests {
@Test
public void contextRefreshWhenUsingAspectJAndCustomGlobalMethodSecurityConfigurationThenAutowire()
throws Exception {
this.spring.register(AspectJModeExtendsGMSCConfig.class).autowire();
assertThat(this.spring.getContext().getBean(
Class.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect")))
.isNotNull();
assertThat(this.spring.getContext().getBean(AspectJMethodSecurityInterceptor.class)).isNotNull();
}
@Test
@WithMockUser
public void methodSecurityWhenOrderSpecifiedThenConfigured() {
this.spring.register(CustomOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(-135);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
}
@ -171,10 +151,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenOrderUnspecifiedThenConfiguredToLowestPrecedence() {
this.spring.register(DefaultOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class);
}
@ -183,10 +161,8 @@ public class NamespaceGlobalMethodSecurityTests {
public void methodSecurityWhenOrderUnspecifiedAndCustomGlobalMethodSecurityConfigurationThenConfiguredToLowestPrecedence() {
this.spring.register(DefaultOrderExtendsMethodSecurityConfig.class, MethodSecurityServiceConfig.class)
.autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class);
}
@ -194,11 +170,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenPrePostEnabledThenPreAuthorizes() {
this.spring.register(PreAuthorizeConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@ -206,11 +179,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenPrePostEnabledAndCustomGlobalMethodSecurityConfigurationThenPreAuthorizes() {
this.spring.register(PreAuthorizeExtendsGMSCConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@ -218,10 +188,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenProxyTargetClassThenDoesNotWireToInterface() {
this.spring.register(ProxyTargetClassConfig.class, MethodSecurityServiceConfig.class).autowire();
// make sure service was actually proxied
assertThat(this.service.getClass().getInterfaces()).doesNotContain(MethodSecurityService.class);
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@ -229,9 +197,7 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenDefaultProxyThenWiresToInterface() {
this.spring.register(DefaultProxyConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.service.getClass().getInterfaces()).contains(MethodSecurityService.class);
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@ -239,7 +205,6 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenCustomRunAsManagerThenRunAsWrapsAuthentication() {
this.spring.register(CustomRunAsManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.service.runAs().getAuthorities())
.anyMatch((authority) -> "ROLE_RUN_AS_SUPER".equals(authority.getAuthority()));
}
@ -248,13 +213,9 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenSecuredEnabledThenSecures() {
this.spring.register(SecuredConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class);
assertThatCode(() -> this.service.securedUser()).doesNotThrowAnyException();
assertThatCode(() -> this.service.preAuthorize()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
}
@ -269,11 +230,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenImportingGlobalMethodSecurityConfigurationSubclassThenAuthorizes() {
this.spring.register(ImportSubclassGMSCConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@ -320,7 +278,6 @@ public class NamespaceGlobalMethodSecurityTests {
@Override
public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> attributes,
Object returnedObject) throws AccessDeniedException {
throw new AccessDeniedException("custom AfterInvocationManager");
}
@ -403,7 +360,6 @@ public class NamespaceGlobalMethodSecurityTests {
BeanDefinitionRegistry registry) {
BeanDefinitionBuilder advice = BeanDefinitionBuilder.rootBeanDefinition(ExceptingInterceptor.class);
registry.registerBeanDefinition("exceptingInterceptor", advice.getBeanDefinition());
BeanDefinitionBuilder advisor = BeanDefinitionBuilder
.rootBeanDefinition(MethodSecurityMetadataSourceAdvisor.class);
advisor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

View File

@ -46,15 +46,12 @@ public class ReactiveMethodSecurityConfigurationTests {
@Test
public void rolePrefixWithGrantedAuthorityDefaults() throws NoSuchMethodException {
this.spring.register(WithRolePrefixConfiguration.class).autowire();
TestingAuthenticationToken authentication = new TestingAuthenticationToken("principal", "credential",
"CUSTOM_ABC");
MockMethodInvocation methodInvocation = new MockMethodInvocation(new Foo(), Foo.class, "bar", String.class);
EvaluationContext context = this.methodSecurityExpressionHandler.createEvaluationContext(authentication,
methodInvocation);
SecurityExpressionRoot root = (SecurityExpressionRoot) context.getRootObject().getValue();
assertThat(root.hasRole("ROLE_ABC")).isFalse();
assertThat(root.hasRole("ROLE_CUSTOM_ABC")).isFalse();
assertThat(root.hasRole("CUSTOM_ABC")).isTrue();
@ -64,15 +61,12 @@ public class ReactiveMethodSecurityConfigurationTests {
@Test
public void rolePrefixWithDefaultConfig() throws NoSuchMethodException {
this.spring.register(ReactiveMethodSecurityConfiguration.class).autowire();
TestingAuthenticationToken authentication = new TestingAuthenticationToken("principal", "credential",
"ROLE_ABC");
MockMethodInvocation methodInvocation = new MockMethodInvocation(new Foo(), Foo.class, "bar", String.class);
EvaluationContext context = this.methodSecurityExpressionHandler.createEvaluationContext(authentication,
methodInvocation);
SecurityExpressionRoot root = (SecurityExpressionRoot) context.getRootObject().getValue();
assertThat(root.hasRole("ROLE_ABC")).isTrue();
assertThat(root.hasRole("ABC")).isTrue();
}
@ -80,15 +74,12 @@ public class ReactiveMethodSecurityConfigurationTests {
@Test
public void rolePrefixWithGrantedAuthorityDefaultsAndSubclassWithProxyingEnabled() throws NoSuchMethodException {
this.spring.register(SubclassConfig.class).autowire();
TestingAuthenticationToken authentication = new TestingAuthenticationToken("principal", "credential",
"ROLE_ABC");
MockMethodInvocation methodInvocation = new MockMethodInvocation(new Foo(), Foo.class, "bar", String.class);
EvaluationContext context = this.methodSecurityExpressionHandler.createEvaluationContext(authentication,
methodInvocation);
SecurityExpressionRoot root = (SecurityExpressionRoot) context.getRootObject().getValue();
assertThat(root.hasRole("ROLE_ABC")).isTrue();
assertThat(root.hasRole("ABC")).isTrue();
}

View File

@ -60,19 +60,15 @@ public class SampleEnableGlobalMethodSecurityTests {
@Test
public void preAuthorize() {
this.spring.register(SampleWebSecurityConfig.class).autowire();
assertThat(this.methodSecurityService.secured()).isNull();
assertThat(this.methodSecurityService.jsr250()).isNull();
assertThatThrownBy(() -> this.methodSecurityService.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@Test
public void customPermissionHandler() {
this.spring.register(CustomPermissionEvaluatorWebSecurityConfig.class).autowire();
assertThat(this.methodSecurityService.hasPermission("allowed")).isNull();
assertThatThrownBy(() -> this.methodSecurityService.hasPermission("denied"))
.isInstanceOf(AccessDeniedException.class);
}

View File

@ -68,20 +68,15 @@ public class Sec2758Tests {
@WithMockUser(authorities = "CUSTOM")
@Test
public void requestWhenNullifyingRolePrefixThenPassivityRestored() throws Exception {
this.spring.register(SecurityConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@WithMockUser(authorities = "CUSTOM")
@Test
public void methodSecurityWhenNullifyingRolePrefixThenPassivityRestored() {
this.spring.register(SecurityConfig.class).autowire();
assertThatCode(() -> this.service.doJsr250()).doesNotThrowAnyException();
assertThatCode(() -> this.service.doPreAuthorize()).doesNotThrowAnyException();
}

View File

@ -77,7 +77,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.antMatchers("/demo/**").permitAll();
// @formatter:on
}
}
@ -93,7 +92,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.mvcMatchers("/demo/**").permitAll();
// @formatter:on
}
}
@ -109,7 +107,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.regexMatchers(".*").permitAll();
// @formatter:on
}
}
@ -125,7 +122,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.anyRequest().permitAll();
// @formatter:on
}
}
@ -141,7 +137,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.requestMatchers(new AntPathRequestMatcher("/**")).permitAll();
// @formatter:on
}
}

View File

@ -69,7 +69,6 @@ public class SampleWebSecurityConfigurerAdapterTests {
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "CSRF-TOKEN-TEST");
new HttpSessionCsrfTokenRepository().saveToken(csrfToken, this.request, this.response);
this.request.setParameter(csrfToken.getParameterName(), csrfToken.getToken());
@ -78,136 +77,112 @@ public class SampleWebSecurityConfigurerAdapterTests {
@Test
public void helloWorldSampleWhenRequestSecureResourceThenRedirectToLogin() throws Exception {
this.spring.register(HelloWorldWebSecurityConfigurerAdapter.class).autowire();
this.request.addHeader("Accept", "text/html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("http://localhost/login");
}
@Test
public void helloWorldSampleWhenRequestLoginWithoutCredentialsThenRedirectToLogin() throws Exception {
this.spring.register(HelloWorldWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addHeader("Accept", "text/html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/login?error");
}
@Test
public void helloWorldSampleWhenRequestLoginWithValidCredentialsThenRedirectToIndex() throws Exception {
this.spring.register(HelloWorldWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addHeader("Accept", "text/html");
this.request.addParameter("username", "user");
this.request.addParameter("password", "password");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/");
}
@Test
public void readmeSampleWhenRequestSecureResourceThenRedirectToLogin() throws Exception {
this.spring.register(SampleWebSecurityConfigurerAdapter.class).autowire();
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("http://localhost/login");
}
@Test
public void readmeSampleWhenRequestLoginWithoutCredentialsThenRedirectToLogin() throws Exception {
this.spring.register(SampleWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/login?error");
}
@Test
public void readmeSampleWhenRequestLoginWithValidCredentialsThenRedirectToIndex() throws Exception {
this.spring.register(SampleWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addParameter("username", "user");
this.request.addParameter("password", "password");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/");
}
@Test
public void multiHttpSampleWhenRequestSecureResourceThenRedirectToLogin() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("http://localhost/login");
}
@Test
public void multiHttpSampleWhenRequestLoginWithoutCredentialsThenRedirectToLogin() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/login?error");
}
@Test
public void multiHttpSampleWhenRequestLoginWithValidCredentialsThenRedirectToIndex() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addParameter("username", "user");
this.request.addParameter("password", "password");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/");
}
@Test
public void multiHttpSampleWhenRequestProtectedResourceThenStatusUnauthorized() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/api/admin/test");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void multiHttpSampleWhenRequestAdminResourceWithRegularUserThenStatusForbidden() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/api/admin/test");
this.request.addHeader("Authorization",
"Basic " + Base64.getEncoder().encodeToString("user:password".getBytes()));
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@Test
public void multiHttpSampleWhenRequestAdminResourceWithAdminUserThenStatusOk() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/api/admin/test");
this.request.addHeader("Authorization",
"Basic " + Base64.getEncoder().encodeToString("admin:password".getBytes()));
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}

View File

@ -84,9 +84,7 @@ public class WebSecurityConfigurerAdapterPowermockTests {
PowerMockito
.when(SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
.thenReturn(Arrays.<AbstractHttpConfigurer>asList(configurer));
loadConfig(Config.class);
assertThat(configurer.init).isTrue();
assertThat(configurer.configure).isTrue();
}
@ -94,21 +92,16 @@ public class WebSecurityConfigurerAdapterPowermockTests {
@Test
public void loadConfigWhenDefaultConfigThenWebAsyncManagerIntegrationFilterAdded() throws Exception {
this.spring.register(WebAsyncPopulatedByDefaultConfig.class).autowire();
WebAsyncManager webAsyncManager = mock(WebAsyncManager.class);
this.mockMvc.perform(get("/").requestAttr(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, webAsyncManager));
ArgumentCaptor<CallableProcessingInterceptor> callableProcessingInterceptorArgCaptor = ArgumentCaptor
.forClass(CallableProcessingInterceptor.class);
verify(webAsyncManager, atLeastOnce()).registerCallableInterceptor(any(),
callableProcessingInterceptorArgCaptor.capture());
CallableProcessingInterceptor callableProcessingInterceptor = callableProcessingInterceptorArgCaptor
.getAllValues().stream()
.filter((e) -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
.findFirst().orElse(null);
assertThat(callableProcessingInterceptor).isNotNull();
}

View File

@ -84,7 +84,6 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenRequestSecureThenDefaultSecurityHeadersReturned() throws Exception {
this.spring.register(HeadersArePopulatedByDefaultConfig.class).autowire();
this.mockMvc.perform(get("/").secure(true)).andExpect(header().string("X-Content-Type-Options", "nosniff"))
.andExpect(header().string("X-Frame-Options", "DENY"))
.andExpect(header().string("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"))
@ -96,9 +95,7 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenRequestAuthenticateThenAuthenticationEventPublished() throws Exception {
this.spring.register(InMemoryAuthWithWebSecurityConfigurerAdapter.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).isNotEmpty();
assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).hasSize(1);
}
@ -106,9 +103,7 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenInMemoryConfigureProtectedThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureProtectedConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
@ -116,9 +111,7 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenInMemoryConfigureGlobalThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureGlobalConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
@ -128,10 +121,8 @@ public class WebSecurityConfigurerAdapterTests {
OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN = mock(
ContentNegotiationStrategy.class);
this.spring.register(OverrideContentNegotiationStrategySharedObjectConfig.class).autowire();
OverrideContentNegotiationStrategySharedObjectConfig securityConfig = this.spring.getContext()
.getBean(OverrideContentNegotiationStrategySharedObjectConfig.class);
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
assertThat(securityConfig.contentNegotiationStrategySharedObject)
.isSameAs(OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN);
@ -140,10 +131,8 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenDefaultContentNegotiationStrategyThenHeaderContentNegotiationStrategy() {
this.spring.register(ContentNegotiationStrategyDefaultSharedObjectConfig.class).autowire();
ContentNegotiationStrategyDefaultSharedObjectConfig securityConfig = this.spring.getContext()
.getBean(ContentNegotiationStrategyDefaultSharedObjectConfig.class);
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
assertThat(securityConfig.contentNegotiationStrategySharedObject)
.isInstanceOf(HeaderContentNegotiationStrategy.class);
@ -152,9 +141,7 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenUserDetailsServiceHasCircularReferenceThenStillLoads() {
this.spring.register(RequiresUserDetailsServiceConfig.class, UserDetailsServiceConfig.class).autowire();
MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
assertThatCode(() -> myFilter.userDetailsService.loadUserByUsername("user")).doesNotThrowAnyException();
assertThatExceptionOfType(UsernameNotFoundException.class)
.isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
@ -164,10 +151,8 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenSharedObjectsCreatedThenApplicationContextAdded() {
this.spring.register(ApplicationContextSharedObjectConfig.class).autowire();
ApplicationContextSharedObjectConfig securityConfig = this.spring.getContext()
.getBean(ApplicationContextSharedObjectConfig.class);
assertThat(securityConfig.applicationContextSharedObject).isNotNull();
assertThat(securityConfig.applicationContextSharedObject).isSameAs(this.spring.getContext());
}
@ -176,9 +161,7 @@ public class WebSecurityConfigurerAdapterTests {
public void loadConfigWhenCustomAuthenticationTrustResolverBeanThenOverridesDefault() {
CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN = mock(AuthenticationTrustResolver.class);
this.spring.register(CustomTrustResolverConfig.class).autowire();
CustomTrustResolverConfig securityConfig = this.spring.getContext().getBean(CustomTrustResolverConfig.class);
assertThat(securityConfig.authenticationTrustResolverSharedObject).isNotNull();
assertThat(securityConfig.authenticationTrustResolverSharedObject)
.isSameAs(CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN);
@ -195,12 +178,9 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void performWhenUsingAuthenticationEventPublisherBeanThenUses() throws Exception {
this.spring.register(CustomAuthenticationEventPublisherBean.class).autowire();
AuthenticationEventPublisher authenticationEventPublisher = this.spring.getContext()
.getBean(AuthenticationEventPublisher.class);
this.mockMvc.perform(get("/").with(httpBasic("user", "password")));
verify(authenticationEventPublisher).publishAuthenticationSuccess(any(Authentication.class));
}
@ -208,14 +188,11 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void performWhenUsingAuthenticationEventPublisherInDslThenUses() throws Exception {
this.spring.register(CustomAuthenticationEventPublisherDsl.class).autowire();
AuthenticationEventPublisher authenticationEventPublisher = CustomAuthenticationEventPublisherDsl.EVENT_PUBLISHER;
this.mockMvc.perform(get("/").with(httpBasic("user", "password"))); // fails since
// no
// providers
// configured
verify(authenticationEventPublisher).publishAuthenticationFailure(any(AuthenticationException.class),
any(Authentication.class));
}

View File

@ -74,9 +74,7 @@ public class HttpConfigurationTests {
public void configureWhenAddFilterCasAuthenticationFilterThenFilterAdded() throws Exception {
CasAuthenticationFilterConfig.CAS_AUTHENTICATION_FILTER = spy(new CasAuthenticationFilter());
this.spring.register(CasAuthenticationFilterConfig.class).autowire();
this.mockMvc.perform(get("/"));
verify(CasAuthenticationFilterConfig.CAS_AUTHENTICATION_FILTER).doFilter(any(ServletRequest.class),
any(ServletResponse.class), any(FilterChain.class));
}
@ -84,7 +82,6 @@ public class HttpConfigurationTests {
@Test
public void configureWhenConfigIsRequestMatchersJavadocThenAuthorizationApplied() throws Exception {
this.spring.register(RequestMatcherRegistryConfigs.class).autowire();
this.mockMvc.perform(get("/oauth/a")).andExpect(status().isUnauthorized());
this.mockMvc.perform(get("/oauth/b")).andExpect(status().isUnauthorized());
this.mockMvc.perform(get("/api/a")).andExpect(status().isUnauthorized());

View File

@ -93,11 +93,8 @@ public class NamespaceHttpTests {
given(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(FilterInvocation.class)).willReturn(true);
given(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(any(ConfigAttribute.class)))
.willReturn(true);
this.spring.register(AccessDecisionManagerRefConfig.class).autowire();
this.mockMvc.perform(get("/"));
verify(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER, times(1)).decide(any(Authentication.class),
any(), anyCollection());
}
@ -105,7 +102,6 @@ public class NamespaceHttpTests {
@Test // http@access-denied-page
public void configureWhenAccessDeniedPageSetAndRequestForbiddenThenForwardedToAccessDeniedPage() throws Exception {
this.spring.register(AccessDeniedPageConfig.class).autowire();
this.mockMvc.perform(get("/admin").with(user(PasswordEncodedUser.user()))).andExpect(status().isForbidden())
.andExpect(forwardedUrl("/AccessDeniedPage"));
}
@ -114,19 +110,15 @@ public class NamespaceHttpTests {
public void configureWhenAuthenticationManagerProvidedThenVerifyUse() throws Exception {
AuthenticationManagerRefConfig.AUTHENTICATION_MANAGER = mock(AuthenticationManager.class);
this.spring.register(AuthenticationManagerRefConfig.class).autowire();
this.mockMvc.perform(formLogin());
verify(AuthenticationManagerRefConfig.AUTHENTICATION_MANAGER, times(1)).authenticate(any(Authentication.class));
}
@Test // http@create-session=always
public void configureWhenSessionCreationPolicyAlwaysThenSessionCreatedOnRequest() throws Exception {
this.spring.register(CreateSessionAlwaysConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNotNull();
assertThat(session.isNew()).isTrue();
}
@ -134,25 +126,19 @@ public class NamespaceHttpTests {
@Test // http@create-session=stateless
public void configureWhenSessionCreationPolicyStatelessThenSessionNotCreatedOnRequest() throws Exception {
this.spring.register(CreateSessionStatelessConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
}
@Test // http@create-session=ifRequired
public void configureWhenSessionCreationPolicyIfRequiredThenSessionCreatedWhenRequiredOnRequest() throws Exception {
this.spring.register(IfRequiredConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/unsecure")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
mvcResult = this.mockMvc.perform(formLogin()).andReturn();
session = mvcResult.getRequest().getSession(false);
assertThat(session).isNotNull();
assertThat(session.isNew()).isTrue();
}
@ -160,10 +146,8 @@ public class NamespaceHttpTests {
@Test // http@create-session=never
public void configureWhenSessionCreationPolicyNeverThenSessionNotCreatedOnRequest() throws Exception {
this.spring.register(CreateSessionNeverConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
}
@ -171,7 +155,6 @@ public class NamespaceHttpTests {
public void configureWhenAuthenticationEntryPointSetAndRequestUnauthorizedThenRedirectedToAuthenticationEntryPoint()
throws Exception {
this.spring.register(EntryPointRefConfig.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("**/entry-point"));
}
@ -180,22 +163,17 @@ public class NamespaceHttpTests {
public void configureWhenJaasApiIntegrationFilterAddedThenJaasSubjectObtained() throws Exception {
LoginContext loginContext = mock(LoginContext.class);
given(loginContext.getSubject()).willReturn(new Subject());
JaasAuthenticationToken authenticationToken = mock(JaasAuthenticationToken.class);
given(authenticationToken.isAuthenticated()).willReturn(true);
given(authenticationToken.getLoginContext()).willReturn(loginContext);
this.spring.register(JaasApiProvisionConfig.class).autowire();
this.mockMvc.perform(get("/").with(authentication(authenticationToken)));
verify(loginContext, times(1)).getSubject();
}
@Test // http@realm
public void configureWhenHttpBasicAndRequestUnauthorizedThenReturnWWWAuthenticateWithRealm() throws Exception {
this.spring.register(RealmConfig.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isUnauthorized())
.andExpect(header().string("WWW-Authenticate", "Basic realm=\"RealmConfig\""));
}
@ -203,9 +181,7 @@ public class NamespaceHttpTests {
@Test // http@request-matcher-ref ant
public void configureWhenAntPatternMatchingThenAntPathRequestMatcherUsed() {
this.spring.register(RequestMatcherAntConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
.get(0);
@ -215,9 +191,7 @@ public class NamespaceHttpTests {
@Test // http@request-matcher-ref regex
public void configureWhenRegexPatternMatchingThenRegexRequestMatcherUsed() {
this.spring.register(RequestMatcherRegexConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
.get(0);
@ -227,9 +201,7 @@ public class NamespaceHttpTests {
@Test // http@request-matcher-ref
public void configureWhenRequestMatcherProvidedThenRequestMatcherUsed() {
this.spring.register(RequestMatcherRefConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
.get(0);
@ -240,9 +212,7 @@ public class NamespaceHttpTests {
@Test // http@security=none
public void configureWhenIgnoredAntPatternsThenAntPathRequestMatcherUsedWithNoFilters() {
this.spring.register(SecurityNoneConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
.get(0);
@ -250,7 +220,6 @@ public class NamespaceHttpTests {
assertThat(((AntPathRequestMatcher) securityFilterChain.getRequestMatcher()).getPattern())
.isEqualTo("/resources/**");
assertThat(securityFilterChain.getFilters()).isEmpty();
assertThat(filterChainProxy.getFilterChains().get(1)).isInstanceOf(DefaultSecurityFilterChain.class);
securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains().get(1);
assertThat(securityFilterChain.getRequestMatcher()).isInstanceOf(AntPathRequestMatcher.class);
@ -262,7 +231,6 @@ public class NamespaceHttpTests {
@Test // http@security-context-repository-ref
public void configureWhenNullSecurityContextRepositoryThenSecurityContextNotSavedInSession() throws Exception {
this.spring.register(SecurityContextRepoConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(formLogin()).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
@ -271,9 +239,7 @@ public class NamespaceHttpTests {
@Test // http@servlet-api-provision=false
public void configureWhenServletApiDisabledThenRequestNotServletApiWrapper() throws Exception {
this.spring.register(ServletApiProvisionConfig.class, MainController.class).autowire();
this.mockMvc.perform(get("/"));
assertThat(MainController.HTTP_SERVLET_REQUEST_TYPE)
.isNotInstanceOf(SecurityContextHolderAwareRequestWrapper.class);
}
@ -281,9 +247,7 @@ public class NamespaceHttpTests {
@Test // http@servlet-api-provision defaults to true
public void configureWhenServletApiDefaultThenRequestIsServletApiWrapper() throws Exception {
this.spring.register(ServletApiProvisionDefaultsConfig.class, MainController.class).autowire();
this.mockMvc.perform(get("/"));
assertThat(SecurityContextHolderAwareRequestWrapper.class)
.isAssignableFrom(MainController.HTTP_SERVLET_REQUEST_TYPE);
}
@ -291,9 +255,7 @@ public class NamespaceHttpTests {
@Test // http@use-expressions=true
public void configureWhenUseExpressionsEnabledThenExpressionBasedSecurityMetadataSource() {
this.spring.register(UseExpressionsConfig.class).autowire();
UseExpressionsConfig config = this.spring.getContext().getBean(UseExpressionsConfig.class);
assertThat(ExpressionBasedFilterInvocationSecurityMetadataSource.class)
.isAssignableFrom(config.filterInvocationSecurityMetadataSourceType);
}
@ -301,9 +263,7 @@ public class NamespaceHttpTests {
@Test // http@use-expressions=false
public void configureWhenUseExpressionsDisabledThenDefaultSecurityMetadataSource() {
this.spring.register(DisableUseExpressionsConfig.class).autowire();
DisableUseExpressionsConfig config = this.spring.getContext().getBean(DisableUseExpressionsConfig.class);
assertThat(DefaultFilterInvocationSecurityMetadataSource.class)
.isAssignableFrom(config.filterInvocationSecurityMetadataSourceType);
}

View File

@ -75,66 +75,44 @@ public class WebSecurityTests {
@Test
public void ignoringMvcMatcher() throws Exception {
loadConfig(MvcMatcherConfig.class, LegacyMvcMatchingConfig.class);
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setRequestURI("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setRequestURI("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setRequestURI("/other");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void ignoringMvcMatcherServletPath() throws Exception {
loadConfig(MvcMatcherServletPathConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/other");
this.request.setRequestURI("/other/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@ -143,7 +121,6 @@ public class WebSecurityTests {
this.context.register(configs);
this.context.setServletContext(new MockServletContext());
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

View File

@ -67,9 +67,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
context.setAuthentication(
new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()));
SecurityContextHolder.setContext(context);
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
mockMvc.perform(get("/users/self")).andExpect(status().isOk()).andExpect(content().string("extracted-user"));
}
@ -84,12 +82,10 @@ public class AuthenticationPrincipalArgumentResolverTests {
.inMemoryAuthentication();
// @formatter:off
}
@Bean
public UsernameExtractor usernameExtractor() {
return new UsernameExtractor();
}
@RestController
static class UserController {
@GetMapping("/users/self")
@ -98,7 +94,6 @@ public class AuthenticationPrincipalArgumentResolverTests {
}
}
}
static class UsernameExtractor {
public String extract(User u) {
return "extracted-" + u.getUsername();

View File

@ -57,7 +57,6 @@ public class EnableWebSecurityTests {
@Test
public void configureWhenOverrideAuthenticationManagerBeanThenAuthenticationManagerBeanRegistered() {
this.spring.register(SecurityConfig.class).autowire();
AuthenticationManager authenticationManager = this.spring.getContext().getBean(AuthenticationManager.class);
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
@ -73,7 +72,6 @@ public class EnableWebSecurityTests {
@Test
public void configureWhenEnableWebMvcThenAuthenticationPrincipalResolvable() throws Exception {
this.spring.register(AuthenticationPrincipalConfig.class).autowire();
this.mockMvc.perform(get("/").with(authentication(new TestingAuthenticationToken("user1", "password"))))
.andExpect(content().string("user1"));
}
@ -81,7 +79,6 @@ public class EnableWebSecurityTests {
@Test
public void securityFilterChainWhenEnableWebMvcThenAuthenticationPrincipalResolvable() throws Exception {
this.spring.register(SecurityFilterChainAuthenticationPrincipalConfig.class).autowire();
this.mockMvc.perform(get("/").with(authentication(new TestingAuthenticationToken("user1", "password"))))
.andExpect(content().string("user1"));
}
@ -89,20 +86,16 @@ public class EnableWebSecurityTests {
@Test
public void enableWebSecurityWhenNoConfigurationAnnotationThenBeanProxyingEnabled() {
this.spring.register(BeanProxyEnabledByDefaultConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isSameAs(childBean);
}
@Test
public void enableWebSecurityWhenProxyBeanMethodsFalseThenBeanProxyingDisabled() {
this.spring.register(BeanProxyDisabledConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isNotSameAs(childBean);
}

View File

@ -81,7 +81,6 @@ public class HttpSecurityConfigurationTests {
@Test
public void getWhenDefaultFilterChainBeanThenDefaultHeadersInResponse() throws Exception {
this.spring.register(DefaultWithFilterChainConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS,
@ -100,48 +99,39 @@ public class HttpSecurityConfigurationTests {
@Test
public void logoutWhenDefaultFilterChainBeanThenCreatesDefaultLogoutEndpoint() throws Exception {
this.spring.register(DefaultWithFilterChainConfig.class).autowire();
this.mockMvc.perform(post("/logout").with(csrf())).andExpect(redirectedUrl("/login?logout"));
}
@Test
public void loadConfigWhenDefaultConfigThenWebAsyncManagerIntegrationFilterAdded() throws Exception {
this.spring.register(DefaultWithFilterChainConfig.class, NameController.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/name").with(user("Bob"))).andExpect(request().asyncStarted())
.andReturn();
this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk()).andExpect(content().string("Bob"));
}
@Test
public void getWhenDefaultFilterChainBeanThenAnonymousPermitted() throws Exception {
this.spring.register(AuthorizeRequestsConfig.class, UserDetailsConfig.class, BaseController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void authenticateWhenDefaultFilterChainBeanThenSessionIdChanges() throws Exception {
this.spring.register(SecurityEnabledConfig.class, UserDetailsConfig.class).autowire();
MockHttpSession session = new MockHttpSession();
String sessionId = session.getId();
MvcResult result = this.mockMvc.perform(
post("/login").param("username", "user").param("password", "password").session(session).with(csrf()))
.andReturn();
assertThat(result.getRequest().getSession(false).getId()).isNotEqualTo(sessionId);
}
@Test
public void authenticateWhenDefaultFilterChainBeanThenRedirectsToSavedRequest() throws Exception {
this.spring.register(SecurityEnabledConfig.class, UserDetailsConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mockMvc.perform(get("/messages")).andReturn().getRequest()
.getSession();
this.mockMvc.perform(
post("/login").param("username", "user").param("password", "password").session(session).with(csrf()))
.andExpect(redirectedUrl("http://localhost/messages"));
@ -150,7 +140,6 @@ public class HttpSecurityConfigurationTests {
@Test
public void authenticateWhenDefaultFilterChainBeanThenRolePrefixIsSet() throws Exception {
this.spring.register(SecurityEnabledConfig.class, UserDetailsConfig.class, UserController.class).autowire();
this.mockMvc
.perform(get("/user")
.with(authentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"))))
@ -160,7 +149,6 @@ public class HttpSecurityConfigurationTests {
@Test
public void loginWhenUsingDefaultsThenDefaultLoginPageGenerated() throws Exception {
this.spring.register(SecurityEnabledConfig.class).autowire();
this.mockMvc.perform(get("/login")).andExpect(status().isOk());
}

View File

@ -77,29 +77,23 @@ public class OAuth2ClientConfigurationTests {
String clientRegistrationId = "client1";
String principalName = "user1";
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.registrationId(clientRegistrationId).build();
given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId)))
.willReturn(clientRegistration);
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
given(authorizedClient.getClientRegistration()).willReturn(clientRegistration);
given(authorizedClientRepository.loadAuthorizedClient(eq(clientRegistrationId), eq(authentication),
any(HttpServletRequest.class))).willReturn(authorizedClient);
OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
given(authorizedClient.getAccessToken()).willReturn(accessToken);
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
this.mockMvc
.perform(get("/authorized-client")
.with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
@ -113,25 +107,20 @@ public class OAuth2ClientConfigurationTests {
String clientRegistrationId = "client1";
String principalName = "user1";
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.registrationId(clientRegistrationId).build();
given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration);
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
given(accessTokenResponseClient.getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class)))
.willReturn(accessTokenResponse);
OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
this.mockMvc
.perform(get("/authorized-client")
.with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
@ -177,28 +166,22 @@ public class OAuth2ClientConfigurationTests {
String clientRegistrationId = "client1";
String principalName = "user1";
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AuthorizedClientManager authorizedClientManager = mock(OAuth2AuthorizedClientManager.class);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.registrationId(clientRegistrationId).build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName,
TestOAuth2AccessTokens.noScopes());
given(authorizedClientManager.authorize(any())).willReturn(authorizedClient);
OAuth2AuthorizedClientManagerRegisteredConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_MANAGER = authorizedClientManager;
this.spring.register(OAuth2AuthorizedClientManagerRegisteredConfig.class).autowire();
this.mockMvc
.perform(get("/authorized-client")
.with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
.andExpect(status().isOk()).andExpect(content().string("resolved"));
verify(authorizedClientManager).authorize(any());
verifyNoInteractions(clientRegistrationRepository);
verifyNoInteractions(authorizedClientRepository);

View File

@ -60,7 +60,6 @@ public class Sec2515Tests {
.getContext();
context.setClassLoader(new URLClassLoader(new URL[0], context.getClassLoader()));
this.spring.autowire();
assertThat(this.spring.getContext().getBean(AuthenticationManager.class)).isNotNull();
} // SEC-2515

View File

@ -63,7 +63,6 @@ public class SecurityReactorContextConfigurationResourceServerTests {
public void requestWhenUsingFilterThenBearerTokenPropagated() throws Exception {
BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer();
this.spring.register(BearerFilterConfig.class, WebServerConfig.class, Controller.class).autowire();
this.mockMvc.perform(get("/token").with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
.andExpect(status().isOk()).andExpect(content().string("Bearer token"));
}
@ -73,7 +72,6 @@ public class SecurityReactorContextConfigurationResourceServerTests {
public void requestWhenNotUsingFilterThenBearerTokenNotPropagated() throws Exception {
BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer();
this.spring.register(BearerFilterlessConfig.class, WebServerConfig.class, Controller.class).autowire();
this.mockMvc.perform(get("/token").with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
.andExpect(status().isOk()).andExpect(content().string(""));
}
@ -155,7 +153,6 @@ public class SecurityReactorContextConfigurationResourceServerTests {
String header = request.getHeader("Authorization");
if (StringUtils.isBlank(header)) {
return response;
}
return response.setBody(header);
}

View File

@ -106,10 +106,8 @@ public class SecurityReactorContextConfigurationTests {
RequestContextHolder
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
SecurityContextHolder.getContext().setAuthentication(this.authentication);
String testKey = "test_key";
String testValue = "test_value";
BaseSubscriber<Object> parent = new BaseSubscriber<Object>() {
@Override
public Context currentContext() {
@ -117,9 +115,7 @@ public class SecurityReactorContextConfigurationTests {
}
};
CoreSubscriber<Object> subscriber = this.subscriberRegistrar.createSubscriberIfNecessary(parent);
Context resultContext = subscriber.currentContext();
assertThat(resultContext.getOrEmpty(testKey)).hasValue(testValue);
Map<Object, Object> securityContextAttributes = resultContext
.getOrDefault(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, null);
@ -134,7 +130,6 @@ public class SecurityReactorContextConfigurationTests {
RequestContextHolder
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
SecurityContextHolder.getContext().setAuthentication(this.authentication);
Context parentContext = Context.of(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES,
new HashMap<>());
BaseSubscriber<Object> parent = new BaseSubscriber<Object>() {
@ -144,7 +139,6 @@ public class SecurityReactorContextConfigurationTests {
}
};
CoreSubscriber<Object> subscriber = this.subscriberRegistrar.createSubscriberIfNecessary(parent);
Context resultContext = subscriber.currentContext();
assertThat(resultContext).isSameAs(parentContext);
}
@ -189,7 +183,6 @@ public class SecurityReactorContextConfigurationTests {
return null;
}
});
CoreSubscriber<Object> subscriber = this.subscriberRegistrar
.createSubscriberIfNecessary(Operators.emptySubscriber());
assertThat(subscriber).isInstanceOf(SecurityReactorContextConfiguration.SecurityReactorContextSubscriber.class);
@ -200,14 +193,11 @@ public class SecurityReactorContextConfigurationTests {
// Trigger the importing of SecurityReactorContextConfiguration via
// OAuth2ImportSelector
this.spring.register(SecurityConfig.class).autowire();
// Setup for SecurityReactorContextSubscriberRegistrar
RequestContextHolder
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
SecurityContextHolder.getContext().setAuthentication(this.authentication);
ClientResponse clientResponseOk = ClientResponse.create(HttpStatus.OK).build();
ExchangeFilterFunction filter = (req, next) -> Mono.subscriberContext()
.filter((ctx) -> ctx.hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES))
.map((ctx) -> ctx.get(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)).cast(Map.class)
@ -221,18 +211,14 @@ public class SecurityReactorContextConfigurationTests {
return ClientResponse.create(HttpStatus.NOT_FOUND).build();
}
});
ClientRequest clientRequest = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
MockExchangeFunction exchange = new MockExchangeFunction();
Map<Object, Object> expectedContextAttributes = new HashMap<>();
expectedContextAttributes.put(HttpServletRequest.class, this.servletRequest);
expectedContextAttributes.put(HttpServletResponse.class, this.servletResponse);
expectedContextAttributes.put(Authentication.class, this.authentication);
Mono<ClientResponse> clientResponseMono = filter.filter(clientRequest, exchange)
.flatMap((response) -> filter.filter(clientRequest, exchange));
StepVerifier.create(clientResponseMono).expectAccessibleContext()
.contains(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, expectedContextAttributes)
.then().expectNext(clientResponseOk).verifyComplete();

View File

@ -94,7 +94,6 @@ public class WebMvcSecurityConfigurationTests {
public void csrfToken() throws Exception {
CsrfToken csrfToken = new DefaultCsrfToken("headerName", "paramName", "token");
MockHttpServletRequestBuilder request = get("/csrf").requestAttr(CsrfToken.class.getName(), csrfToken);
this.mockMvc.perform(request).andExpect(assertResult(csrfToken));
}

View File

@ -89,30 +89,22 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenWebSecurityConfigurersHaveOrderThenFilterChainsOrdered() {
this.spring.register(SortedWebSecurityConfigurerAdaptersConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(6);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/ignore1");
assertThat(filterChains.get(0).matches(request)).isTrue();
assertThat(filterChains.get(0).getFilters()).isEmpty();
request.setServletPath("/ignore2");
assertThat(filterChains.get(1).matches(request)).isTrue();
assertThat(filterChains.get(1).getFilters()).isEmpty();
request.setServletPath("/role1/**");
assertThat(filterChains.get(2).matches(request)).isTrue();
request.setServletPath("/role2/**");
assertThat(filterChains.get(3).matches(request)).isTrue();
request.setServletPath("/role3/**");
assertThat(filterChains.get(4).matches(request)).isTrue();
request.setServletPath("/**");
assertThat(filterChains.get(5).matches(request)).isTrue();
}
@ -120,22 +112,16 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenSecurityFilterChainsHaveOrderThenFilterChainsOrdered() {
this.spring.register(SortedSecurityFilterChainConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(4);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/role1/**");
assertThat(filterChains.get(0).matches(request)).isTrue();
request.setServletPath("/role2/**");
assertThat(filterChains.get(1).matches(request)).isTrue();
request.setServletPath("/role3/**");
assertThat(filterChains.get(2).matches(request)).isTrue();
request.setServletPath("/**");
assertThat(filterChains.get(3).matches(request)).isTrue();
}
@ -143,7 +129,6 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenWebSecurityConfigurersHaveSameOrderThenThrowBeanCreationException() {
Throwable thrown = catchThrowable(() -> this.spring.register(DuplicateOrderConfig.class).autowire());
assertThat(thrown).isInstanceOf(BeanCreationException.class)
.hasMessageContaining("@Order on WebSecurityConfigurers must be unique")
.hasMessageContaining(DuplicateOrderConfig.WebConfigurer1.class.getName())
@ -153,9 +138,7 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenWebInvocationPrivilegeEvaluatorSetThenIsRegistered() {
PrivilegeEvaluatorConfigurerAdapterConfig.PRIVILEGE_EVALUATOR = mock(WebInvocationPrivilegeEvaluator.class);
this.spring.register(PrivilegeEvaluatorConfigurerAdapterConfig.class).autowire();
assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class))
.isSameAs(PrivilegeEvaluatorConfigurerAdapterConfig.PRIVILEGE_EVALUATOR);
}
@ -165,9 +148,7 @@ public class WebSecurityConfigurationTests {
WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER = mock(SecurityExpressionHandler.class);
given(WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER.getExpressionParser())
.willReturn(mock(ExpressionParser.class));
this.spring.register(WebSecurityExpressionHandlerConfig.class).autowire();
assertThat(this.spring.getContext().getBean(SecurityExpressionHandler.class))
.isSameAs(WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER);
}
@ -176,7 +157,6 @@ public class WebSecurityConfigurationTests {
public void loadConfigWhenSecurityExpressionHandlerIsNullThenException() {
Throwable thrown = catchThrowable(
() -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire());
assertThat(thrown).isInstanceOf(BeanCreationException.class);
assertThat(thrown).hasRootCauseExactlyInstanceOf(IllegalArgumentException.class);
}
@ -184,7 +164,6 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenDefaultSecurityExpressionHandlerThenDefaultIsRegistered() {
this.spring.register(WebSecurityExpressionHandlerDefaultsConfig.class).autowire();
assertThat(this.spring.getContext().getBean(SecurityExpressionHandler.class))
.isInstanceOf(DefaultWebSecurityExpressionHandler.class);
}
@ -195,7 +174,6 @@ public class WebSecurityConfigurationTests {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "notused", "ROLE_ADMIN");
FilterInvocation invocation = new FilterInvocation(new MockHttpServletRequest("GET", ""),
new MockHttpServletResponse(), new MockFilterChain());
AbstractSecurityExpressionHandler handler = this.spring.getContext()
.getBean(AbstractSecurityExpressionHandler.class);
EvaluationContext evaluationContext = handler.createEvaluationContext(authentication, invocation);
@ -210,7 +188,6 @@ public class WebSecurityConfigurationTests {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "notused");
FilterInvocation invocation = new FilterInvocation(new MockHttpServletRequest("GET", ""),
new MockHttpServletResponse(), new MockFilterChain());
AbstractSecurityExpressionHandler handler = this.spring.getContext()
.getBean(AbstractSecurityExpressionHandler.class);
EvaluationContext evaluationContext = handler.createEvaluationContext(authentication, invocation);
@ -222,7 +199,6 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenDefaultWebInvocationPrivilegeEvaluatorThenDefaultIsRegistered() {
this.spring.register(WebInvocationPrivilegeEvaluatorDefaultsConfig.class).autowire();
assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class))
.isInstanceOf(DefaultWebInvocationPrivilegeEvaluator.class);
}
@ -239,7 +215,6 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenDefaultSecurityExpressionHandlerThenBeanResolverSet() throws Exception {
this.spring.register(DefaultExpressionHandlerSetsBeanResolverConfig.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isOk());
this.mockMvc.perform(post("/")).andExpect(status().isForbidden());
}
@ -248,14 +223,11 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenMultipleWebSecurityConfigurationThenContextLoads() {
this.spring.register(ParentConfig.class).autowire();
this.child.register(ChildConfig.class);
this.child.getContext().setParent(this.spring.getContext());
this.child.autowire();
assertThat(this.spring.getContext().getBean("springSecurityFilterChain")).isNotNull();
assertThat(this.child.getContext().getBean("springSecurityFilterChain")).isNotNull();
assertThat(this.spring.getContext().containsBean("springSecurityFilterChain")).isTrue();
assertThat(this.child.getContext().containsBean("springSecurityFilterChain")).isTrue();
}
@ -271,17 +243,14 @@ public class WebSecurityConfigurationTests {
public void loadConfigWhenBeanProxyingEnabledAndSubclassThenFilterChainsCreated() {
this.spring.register(GlobalAuthenticationWebSecurityConfigurerAdaptersConfig.class, SubclassConfig.class)
.autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(4);
}
@Test
public void loadConfigWhenBothAdapterAndFilterChainConfiguredThenException() {
Throwable thrown = catchThrowable(() -> this.spring.register(AdapterAndFilterChainConfig.class).autowire());
assertThat(thrown).isInstanceOf(BeanCreationException.class)
.hasRootCauseExactlyInstanceOf(IllegalStateException.class)
.hasMessageContaining("Found WebSecurityConfigurerAdapter as well as SecurityFilterChain.");

View File

@ -39,10 +39,8 @@ public class Sec2377Tests {
@Test
public void refreshContextWhenParentAndChildRegisteredThenNoException() {
this.parent.register(Sec2377AConfig.class).autowire();
ConfigurableApplicationContext context = this.child.register(Sec2377BConfig.class).getContext();
context.setParent(this.parent.getContext());
this.child.autowire();
}

View File

@ -41,7 +41,6 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testGetRequestMatcherIsTypeRegexMatcher() {
List<RequestMatcher> requestMatchers = this.registry.regexMatchers(HttpMethod.GET, "/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(RegexRequestMatcher.class);
}
@ -50,7 +49,6 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testRequestMatcherIsTypeRegexMatcher() {
List<RequestMatcher> requestMatchers = this.registry.regexMatchers("/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(RegexRequestMatcher.class);
}
@ -59,7 +57,6 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testGetRequestMatcherIsTypeAntPathRequestMatcher() {
List<RequestMatcher> requestMatchers = this.registry.antMatchers(HttpMethod.GET, "/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(AntPathRequestMatcher.class);
}
@ -68,7 +65,6 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testRequestMatcherIsTypeAntPathRequestMatcher() {
List<RequestMatcher> requestMatchers = this.registry.antMatchers("/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(AntPathRequestMatcher.class);
}

View File

@ -52,28 +52,24 @@ public class AnonymousConfigurerTests {
@Test
public void requestWhenAnonymousTwiceInvokedThenDoesNotOverride() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverride.class, PrincipalController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(content().string("principal"));
}
@Test
public void requestWhenAnonymousPrincipalInLambdaThenPrincipalUsed() throws Exception {
this.spring.register(AnonymousPrincipalInLambdaConfig.class, PrincipalController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(content().string("principal"));
}
@Test
public void requestWhenAnonymousDisabledInLambdaThenRespondsWithForbidden() throws Exception {
this.spring.register(AnonymousDisabledInLambdaConfig.class, PrincipalController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isForbidden());
}
@Test
public void requestWhenAnonymousWithDefaultsInLambdaThenRespondsWithOk() throws Exception {
this.spring.register(AnonymousWithDefaultsInLambdaConfig.class, PrincipalController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isOk());
}

View File

@ -94,9 +94,7 @@ public class AuthorizeRequestsTests {
public void antMatchersMethodAndNoPatterns() throws Exception {
loadConfig(AntMatchersNoPatternsConfig.class);
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@ -104,9 +102,7 @@ public class AuthorizeRequestsTests {
public void postWhenPostDenyAllInLambdaThenRespondsWithForbidden() throws Exception {
loadConfig(AntMatchersNoPatternsInLambdaConfig.class);
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@ -114,18 +110,12 @@ public class AuthorizeRequestsTests {
@Test
public void antMatchersPathVariables() throws Exception {
loadConfig(AntPatchersPathVariables.class);
this.request.setServletPath("/user/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setServletPath("/user/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@ -133,18 +123,12 @@ public class AuthorizeRequestsTests {
@Test
public void antMatchersPathVariablesCaseInsensitive() throws Exception {
loadConfig(AntPatchersPathVariables.class);
this.request.setServletPath("/USER/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setServletPath("/USER/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@ -152,18 +136,12 @@ public class AuthorizeRequestsTests {
@Test
public void antMatchersPathVariablesCaseInsensitiveCamelCaseVariables() throws Exception {
loadConfig(AntMatchersPathVariablesCamelCaseVariables.class);
this.request.setServletPath("/USER/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setServletPath("/USER/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@ -171,185 +149,126 @@ public class AuthorizeRequestsTests {
@Test
public void roleHiearchy() throws Exception {
loadConfig(RoleHiearchyConfig.class);
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("test", "notused",
AuthorityUtils.createAuthorityList("ROLE_USER")));
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
securityContext);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void mvcMatcher() throws Exception {
loadConfig(MvcMatcherConfig.class, LegacyMvcMatchingConfig.class);
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setRequestURI("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void requestWhenMvcMatcherDenyAllThenRespondsWithUnauthorized() throws Exception {
loadConfig(MvcMatcherInLambdaConfig.class, LegacyMvcMatchingConfig.class);
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setRequestURI("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void requestWhenMvcMatcherServletPathDenyAllThenMatchesOnServletPath() throws Exception {
loadConfig(MvcMatcherServletPathInLambdaConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/foo");
this.request.setRequestURI("/foo/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/");
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void mvcMatcherPathVariables() throws Exception {
loadConfig(MvcMatcherPathVariablesConfig.class);
this.request.setRequestURI("/user/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setRequestURI("/user/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void requestWhenMvcMatcherPathVariablesThenMatchesOnPathVariables() throws Exception {
loadConfig(MvcMatcherPathVariablesInLambdaConfig.class);
this.request.setRequestURI("/user/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setRequestURI("/user/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void mvcMatcherServletPath() throws Exception {
loadConfig(MvcMatcherServletPathConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/foo");
this.request.setRequestURI("/foo/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/");
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@ -358,7 +277,6 @@ public class AuthorizeRequestsTests {
this.context.register(configs);
this.context.setServletContext(this.servletContext);
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

View File

@ -56,7 +56,6 @@ public class ChannelSecurityConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnInsecureChannelProcessor() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(InsecureChannelProcessor.class));
}
@ -64,7 +63,6 @@ public class ChannelSecurityConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnSecureChannelProcessor() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(SecureChannelProcessor.class));
}
@ -72,7 +70,6 @@ public class ChannelSecurityConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnChannelDecisionManagerImpl() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ChannelDecisionManagerImpl.class));
}
@ -80,21 +77,18 @@ public class ChannelSecurityConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnChannelProcessingFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ChannelProcessingFilter.class));
}
@Test
public void requiresChannelWhenInvokesTwiceThenUsesOriginalRequiresSecure() throws Exception {
this.spring.register(DuplicateInvocationsDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/"));
}
@Test
public void requestWhenRequiresChannelConfiguredInLambdaThenRedirectsToHttps() throws Exception {
this.spring.register(RequiresChannelInLambdaConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/"));
}

View File

@ -73,7 +73,6 @@ public class CorsConfigurerTests {
@Test
public void getWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
@ -82,7 +81,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsConfig.class).autowire();
this.mvc.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
@ -93,7 +91,6 @@ public class CorsConfigurerTests {
@Test
public void getWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsInLambdaConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
@ -102,7 +99,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsInLambdaConfig.class).autowire();
this.mvc.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
@ -113,7 +109,6 @@ public class CorsConfigurerTests {
@Test
public void getWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(ConfigSourceConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
@ -122,7 +117,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(ConfigSourceConfig.class).autowire();
this.mvc.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
@ -134,7 +128,6 @@ public class CorsConfigurerTests {
public void getWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders()
throws Exception {
this.spring.register(ConfigSourceInLambdaConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
@ -144,7 +137,6 @@ public class CorsConfigurerTests {
public void optionsWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders()
throws Exception {
this.spring.register(ConfigSourceInLambdaConfig.class).autowire();
this.mvc.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
@ -155,7 +147,6 @@ public class CorsConfigurerTests {
@Test
public void getWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
@ -164,7 +155,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterConfig.class).autowire();
this.mvc.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
@ -175,7 +165,6 @@ public class CorsConfigurerTests {
@Test
public void getWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterInLambdaConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
@ -184,7 +173,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterInLambdaConfig.class).autowire();
this.mvc.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())

View File

@ -50,43 +50,31 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@Test
public void requestWhenIgnoringRequestMatchersThenAugmentedByConfiguredRequestMatcher() throws Exception {
this.spring.register(IgnoringRequestMatchers.class, BasicController.class).autowire();
this.mvc.perform(get("/path")).andExpect(status().isForbidden());
this.mvc.perform(post("/path")).andExpect(status().isOk());
}
@Test
public void requestWhenIgnoringRequestMatchersInLambdaThenAugmentedByConfiguredRequestMatcher() throws Exception {
this.spring.register(IgnoringRequestInLambdaMatchers.class, BasicController.class).autowire();
this.mvc.perform(get("/path")).andExpect(status().isForbidden());
this.mvc.perform(post("/path")).andExpect(status().isOk());
}
@Test
public void requestWhenIgnoringRequestMatcherThenUnionsWithConfiguredIgnoringAntMatchers() throws Exception {
this.spring.register(IgnoringPathsAndMatchers.class, BasicController.class).autowire();
this.mvc.perform(put("/csrf")).andExpect(status().isForbidden());
this.mvc.perform(post("/csrf")).andExpect(status().isOk());
this.mvc.perform(put("/no-csrf")).andExpect(status().isOk());
}
@Test
public void requestWhenIgnoringRequestMatcherInLambdaThenUnionsWithConfiguredIgnoringAntMatchers()
throws Exception {
this.spring.register(IgnoringPathsAndMatchersInLambdaConfig.class, BasicController.class).autowire();
this.mvc.perform(put("/csrf")).andExpect(status().isForbidden());
this.mvc.perform(post("/csrf")).andExpect(status().isOk());
this.mvc.perform(put("/no-csrf")).andExpect(status().isOk());
}

View File

@ -50,21 +50,18 @@ public class CsrfConfigurerNoWebMvcTests {
@Test
public void missingDispatcherServletPreventsCsrfRequestDataValueProcessor() {
loadContext(EnableWebConfig.class);
assertThat(this.context.containsBeanDefinition("requestDataValueProcessor")).isTrue();
}
@Test
public void findDispatcherServletPreventsCsrfRequestDataValueProcessor() {
loadContext(EnableWebMvcConfig.class);
assertThat(this.context.containsBeanDefinition("requestDataValueProcessor")).isTrue();
}
@Test
public void overrideCsrfRequestDataValueProcessor() {
loadContext(EnableWebOverrideRequestDataConfig.class);
assertThat(this.context.getBean(RequestDataValueProcessor.class).getClass())
.isNotEqualTo(CsrfRequestDataValueProcessor.class);
}

View File

@ -96,7 +96,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(post("/")).andExpect(status().isForbidden());
}
@ -105,7 +104,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(put("/")).andExpect(status().isForbidden());
}
@ -114,7 +112,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(patch("/")).andExpect(status().isForbidden());
}
@ -123,7 +120,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(delete("/")).andExpect(status().isForbidden());
}
@ -132,7 +128,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(request("INVALID", URI.create("/"))).andExpect(status().isForbidden());
}
@ -141,7 +136,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@ -150,7 +144,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(head("/")).andExpect(status().isOk());
}
@ -159,7 +152,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(request(HttpMethod.TRACE, "/")).andExpect(status().isOk());
}
@ -168,28 +160,24 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(options("/")).andExpect(status().isOk());
}
@Test
public void enableWebSecurityWhenDefaultConfigurationThenCreatesRequestDataValueProcessor() {
this.spring.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class).autowire();
assertThat(this.spring.getContext().getBean(RequestDataValueProcessor.class)).isNotNull();
}
@Test
public void postWhenCsrfDisabledThenRespondsWithOk() throws Exception {
this.spring.register(DisableCsrfConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/")).andExpect(status().isOk());
}
@Test
public void postWhenCsrfDisabledInLambdaThenRespondsWithOk() throws Exception {
this.spring.register(DisableCsrfInLambdaConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/")).andExpect(status().isOk());
}
@ -197,9 +185,7 @@ public class CsrfConfigurerTests {
@Test
public void loginWhenCsrfDisabledThenRedirectsToPreviousPostRequest() throws Exception {
this.spring.register(DisableCsrfEnablesRequestCacheConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(post("/to-save")).andReturn();
this.mvc.perform(post("/login").param("username", "user").param("password", "password")
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/to-save"));
@ -212,12 +198,10 @@ public class CsrfConfigurerTests {
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.generateToken(any())).willReturn(csrfToken);
this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(post("/some-url")).andReturn();
this.mvc.perform(post("/login").param("username", "user").param("password", "password").with(csrf())
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound())
.andExpect(redirectedUrl("/"));
verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce())
.loadToken(any(HttpServletRequest.class));
}
@ -229,12 +213,10 @@ public class CsrfConfigurerTests {
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.generateToken(any())).willReturn(csrfToken);
this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/some-url")).andReturn();
this.mvc.perform(post("/login").param("username", "user").param("password", "password").with(csrf())
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/some-url"));
verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce())
.loadToken(any(HttpServletRequest.class));
}
@ -243,10 +225,8 @@ public class CsrfConfigurerTests {
@Test
public void postWhenCsrfEnabledAndSessionIsExpiredThenRespondsWithForbidden() throws Exception {
this.spring.register(InvalidSessionUrlConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(post("/").param("_csrf", "abc")).andExpect(status().isFound())
.andExpect(redirectedUrl("/error/sessionError")).andReturn();
this.mvc.perform(post("/").session((MockHttpSession) mvcResult.getRequest().getSession()))
.andExpect(status().isForbidden());
}
@ -255,7 +235,6 @@ public class CsrfConfigurerTests {
public void requireCsrfProtectionMatcherWhenRequestDoesNotMatchThenRespondsWithOk() throws Exception {
this.spring.register(RequireCsrfProtectionMatcherConfig.class, BasicController.class).autowire();
given(RequireCsrfProtectionMatcherConfig.MATCHER.matches(any())).willReturn(false);
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@ -264,7 +243,6 @@ public class CsrfConfigurerTests {
RequireCsrfProtectionMatcherConfig.MATCHER = mock(RequestMatcher.class);
given(RequireCsrfProtectionMatcherConfig.MATCHER.matches(any())).willReturn(true);
this.spring.register(RequireCsrfProtectionMatcherConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isForbidden());
}
@ -273,7 +251,6 @@ public class CsrfConfigurerTests {
RequireCsrfProtectionMatcherInLambdaConfig.MATCHER = mock(RequestMatcher.class);
this.spring.register(RequireCsrfProtectionMatcherInLambdaConfig.class, BasicController.class).autowire();
given(RequireCsrfProtectionMatcherInLambdaConfig.MATCHER.matches(any())).willReturn(false);
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@ -282,7 +259,6 @@ public class CsrfConfigurerTests {
RequireCsrfProtectionMatcherInLambdaConfig.MATCHER = mock(RequestMatcher.class);
given(RequireCsrfProtectionMatcherInLambdaConfig.MATCHER.matches(any())).willReturn(true);
this.spring.register(RequireCsrfProtectionMatcherInLambdaConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isForbidden());
}
@ -292,7 +268,6 @@ public class CsrfConfigurerTests {
given(CsrfTokenRepositoryConfig.REPO.loadToken(any()))
.willReturn(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token"));
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
verify(CsrfTokenRepositoryConfig.REPO).loadToken(any(HttpServletRequest.class));
}
@ -301,9 +276,7 @@ public class CsrfConfigurerTests {
public void logoutWhenCustomCsrfTokenRepositoryThenCsrfTokenIsCleared() throws Exception {
CsrfTokenRepositoryConfig.REPO = mock(CsrfTokenRepository.class);
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/logout").with(csrf()).with(user("user")));
verify(CsrfTokenRepositoryConfig.REPO).saveToken(isNull(), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@ -315,10 +288,8 @@ public class CsrfConfigurerTests {
given(CsrfTokenRepositoryConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfTokenRepositoryConfig.REPO.generateToken(any())).willReturn(csrfToken);
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andExpect(redirectedUrl("/"));
verify(CsrfTokenRepositoryConfig.REPO).saveToken(isNull(), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@ -329,7 +300,6 @@ public class CsrfConfigurerTests {
given(CsrfTokenRepositoryInLambdaConfig.REPO.loadToken(any()))
.willReturn(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token"));
this.spring.register(CsrfTokenRepositoryInLambdaConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
verify(CsrfTokenRepositoryInLambdaConfig.REPO).loadToken(any(HttpServletRequest.class));
}
@ -338,9 +308,7 @@ public class CsrfConfigurerTests {
public void getWhenCustomAccessDeniedHandlerThenHandlerIsUsed() throws Exception {
AccessDeniedHandlerConfig.DENIED_HANDLER = mock(AccessDeniedHandler.class);
this.spring.register(AccessDeniedHandlerConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/")).andExpect(status().isOk());
verify(AccessDeniedHandlerConfig.DENIED_HANDLER).handle(any(HttpServletRequest.class),
any(HttpServletResponse.class), any());
}
@ -348,7 +316,6 @@ public class CsrfConfigurerTests {
@Test
public void loginWhenNoCsrfTokenThenRespondsWithForbidden() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mvc.perform(post("/login").param("username", "user").param("password", "password"))
.andExpect(status().isForbidden()).andExpect(unauthenticated());
}
@ -356,7 +323,6 @@ public class CsrfConfigurerTests {
@Test
public void logoutWhenNoCsrfTokenThenRespondsWithForbidden() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mvc.perform(post("/logout").with(user("username"))).andExpect(status().isForbidden())
.andExpect(authenticated());
}
@ -365,14 +331,12 @@ public class CsrfConfigurerTests {
@Test
public void logoutWhenCsrfEnabledAndGetRequestThenDoesNotLogout() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mvc.perform(get("/logout").with(user("username"))).andExpect(authenticated());
}
@Test
public void logoutWhenGetRequestAndGetEnabledForLogoutThenLogsOut() throws Exception {
this.spring.register(LogoutAllowsGetConfig.class).autowire();
this.mvc.perform(get("/logout").with(user("username"))).andExpect(unauthenticated());
}
@ -386,9 +350,7 @@ public class CsrfConfigurerTests {
@Test
public void getWhenDefaultCsrfTokenRepositoryThenDoesNotCreateSession() throws Exception {
this.spring.register(DefaultDoesNotCreateSession.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();
assertThat(mvcResult.getRequest().getSession(false)).isNull();
}
@ -401,12 +363,9 @@ public class CsrfConfigurerTests {
@Test
public void csrfAuthenticationStrategyConfiguredThenStrategyUsed() throws Exception {
CsrfAuthenticationStrategyConfig.STRATEGY = mock(SessionAuthenticationStrategy.class);
this.spring.register(CsrfAuthenticationStrategyConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andExpect(redirectedUrl("/"));
verify(CsrfAuthenticationStrategyConfig.STRATEGY, atLeastOnce()).onAuthentication(any(Authentication.class),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}

View File

@ -100,10 +100,8 @@ public class DefaultFiltersTests {
assertThat(filterChains.size()).isEqualTo(2);
DefaultSecurityFilterChain firstFilter = (DefaultSecurityFilterChain) filterChains.get(0);
DefaultSecurityFilterChain secondFilter = (DefaultSecurityFilterChain) filterChains.get(1);
assertThat(firstFilter.getFilters().isEmpty()).isEqualTo(true);
assertThat(secondFilter.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
List<? extends Class<? extends Filter>> classes = secondFilter.getFilters().stream().map(Filter::getClass)
.collect(Collectors.toList());
assertThat(classes.contains(WebAsyncManagerIntegrationFilter.class)).isTrue();
@ -125,11 +123,9 @@ public class DefaultFiltersTests {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("POST", "");
request.setServletPath("/logout");
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
new HttpSessionCsrfTokenRepository().saveToken(csrfToken, request, response);
request.setParameter(csrfToken.getParameterName(), csrfToken.getToken());
this.spring.getContext().getBean("springSecurityFilterChain", Filter.class).doFilter(request, response,
new MockFilterChain());
assertThat(response.getRedirectedUrl()).isEqualTo("/login?logout");

View File

@ -68,7 +68,6 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void getWhenFormLoginEnabledThenRedirectsToLoginPage() throws Exception {
this.spring.register(DefaultLoginPageConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(redirectedUrl("http://localhost/login"));
}
@ -77,7 +76,6 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@ -103,7 +101,6 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void loginWhenNoCredentialsThenRedirectedToLoginPageWithError() throws Exception {
this.spring.register(DefaultLoginPageConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf())).andExpect(redirectedUrl("/login?error"));
}
@ -112,9 +109,7 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
MvcResult mvcResult = this.mvc.perform(post("/login").with(csrf())).andReturn();
this.mvc.perform(get("/login?error").session((MockHttpSession) mvcResult.getRequest().getSession())
.sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
@ -142,7 +137,6 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void loginWhenValidCredentialsThenRedirectsToDefaultSuccessPage() throws Exception {
this.spring.register(DefaultLoginPageConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andExpect(redirectedUrl("/"));
}
@ -152,7 +146,6 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login?logout").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@ -179,14 +172,12 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void loginPageWhenLoggedOutAndCustomLogoutSuccessHandlerThenDoesNotRenderLoginPage() throws Exception {
this.spring.register(DefaultLoginPageCustomLogoutSuccessHandlerConfig.class).autowire();
this.mvc.perform(get("/login?logout")).andExpect(content().string(""));
}
@Test
public void loginPageWhenLoggedOutAndCustomLogoutSuccessUrlThenDoesNotRenderLoginPage() throws Exception {
this.spring.register(DefaultLoginPageCustomLogoutSuccessUrlConfig.class).autowire();
this.mvc.perform(get("/login?logout")).andExpect(content().string(""));
}
@ -195,7 +186,6 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageWithRememberMeConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@ -223,10 +213,8 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void loginPageWhenOpenIdLoginConfiguredThenOpedIdLoginPage() throws Exception {
this.spring.register(DefaultLoginPageWithOpenIDConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@ -251,7 +239,6 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageWithFormLoginOpenIDRememberMeConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@ -290,7 +277,6 @@ public class DefaultLoginPageConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnDefaultLoginPageGeneratingFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(DefaultLoginPageGeneratingFilter.class));
}
@ -298,7 +284,6 @@ public class DefaultLoginPageConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnUsernamePasswordAuthenticationFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(UsernamePasswordAuthenticationFilter.class));
}
@ -307,7 +292,6 @@ public class DefaultLoginPageConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnLoginUrlAuthenticationEntryPoint() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(LoginUrlAuthenticationEntryPoint.class));
}
@ -315,14 +299,12 @@ public class DefaultLoginPageConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnExceptionTranslationFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ExceptionTranslationFilter.class));
}
@Test
public void configureWhenAuthenticationEntryPointThenNoDefaultLoginPageGeneratingFilter() {
this.spring.register(DefaultLoginWithCustomAuthenticationEntryPointConfig.class).autowire();
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChain.getFilterChains().get(0).getFilters().stream()
.filter((filter) -> filter.getClass().isAssignableFrom(DefaultLoginPageGeneratingFilter.class)).count())

View File

@ -55,9 +55,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
@WithMockUser(roles = "ANYTHING")
public void getWhenAccessDeniedOverriddenThenCustomizesResponseByRequest() throws Exception {
this.spring.register(RequestMatcherBasedAccessDeniedHandlerConfig.class).autowire();
this.mvc.perform(get("/hello")).andExpect(status().isIAmATeapot());
this.mvc.perform(get("/goodbye")).andExpect(status().isForbidden());
}
@ -65,9 +63,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
@WithMockUser(roles = "ANYTHING")
public void getWhenAccessDeniedOverriddenInLambdaThenCustomizesResponseByRequest() throws Exception {
this.spring.register(RequestMatcherBasedAccessDeniedHandlerInLambdaConfig.class).autowire();
this.mvc.perform(get("/hello")).andExpect(status().isIAmATeapot());
this.mvc.perform(get("/goodbye")).andExpect(status().isForbidden());
}
@ -75,9 +71,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
@WithMockUser(roles = "ANYTHING")
public void getWhenAccessDeniedOverriddenByOnlyOneHandlerThenAllRequestsUseThatHandler() throws Exception {
this.spring.register(SingleRequestMatcherAccessDeniedHandlerConfig.class).autowire();
this.mvc.perform(get("/hello")).andExpect(status().isIAmATeapot());
this.mvc.perform(get("/goodbye")).andExpect(status().isIAmATeapot());
}

View File

@ -67,7 +67,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnExceptionTranslationFilter() {
this.spring.register(ObjectPostProcessorConfig.class, DefaultSecurityConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ExceptionTranslationFilter.class));
}
@ -75,7 +74,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsApplicationXhtmlXmlThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XHTML_XML))
.andExpect(status().isFound());
}
@ -84,7 +82,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsImageGifThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.IMAGE_GIF)).andExpect(status().isFound());
}
@ -92,7 +89,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsImageJpgThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.IMAGE_JPEG)).andExpect(status().isFound());
}
@ -100,7 +96,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsImagePngThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.IMAGE_PNG)).andExpect(status().isFound());
}
@ -108,7 +103,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsTextHtmlThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML)).andExpect(status().isFound());
}
@ -116,7 +110,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsTextPlainThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN)).andExpect(status().isFound());
}
@ -124,7 +117,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsApplicationAtomXmlThenRespondsWith401() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_ATOM_XML))
.andExpect(status().isUnauthorized());
}
@ -133,7 +125,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsApplicationFormUrlEncodedThenRespondsWith401() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_FORM_URLENCODED))
.andExpect(status().isUnauthorized());
}
@ -142,7 +133,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsApplicationJsonThenRespondsWith401() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized());
}
@ -151,7 +141,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsApplicationOctetStreamThenRespondsWith401() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM))
.andExpect(status().isUnauthorized());
}
@ -160,7 +149,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsMultipartFormDataThenRespondsWith401() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isUnauthorized());
}
@ -169,7 +157,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsTextXmlThenRespondsWith401() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.TEXT_XML)).andExpect(status().isUnauthorized());
}
@ -177,14 +164,12 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptIsAnyThenRespondsWith401() throws Exception {
this.spring.register(DefaultSecurityConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.ALL)).andExpect(status().isUnauthorized());
}
@Test
public void getWhenAcceptIsChromeThenRespondsWith302() throws Exception {
this.spring.register(DefaultSecurityConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT,
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"))
.andExpect(status().isFound());
@ -193,7 +178,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptIsTextPlainAndXRequestedWithIsXHRThenRespondsWith401() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header("Accept", MediaType.TEXT_PLAIN).header("X-Requested-With", "XMLHttpRequest"))
.andExpect(status().isUnauthorized());
}
@ -202,9 +186,7 @@ public class ExceptionHandlingConfigurerTests {
public void getWhenCustomContentNegotiationStrategyThenStrategyIsUsed() throws Exception {
this.spring.register(OverrideContentNegotiationStrategySharedObjectConfig.class, DefaultSecurityConfig.class)
.autowire();
this.mvc.perform(get("/"));
verify(OverrideContentNegotiationStrategySharedObjectConfig.CNS, atLeastOnce())
.resolveMediaTypes(any(NativeWebRequest.class));
}
@ -212,7 +194,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenUsingDefaultsAndUnauthenticatedThenRedirectsToLogin() throws Exception {
this.spring.register(DefaultHttpConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, "bogus/type"))
.andExpect(redirectedUrl("http://localhost/login"));
}
@ -220,16 +201,13 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenDeclaringHttpBasicBeforeFormLoginThenRespondsWith401() throws Exception {
this.spring.register(BasicAuthenticationEntryPointBeforeFormLoginConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, "bogus/type")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenInvokingExceptionHandlingTwiceThenOriginalEntryPointUsed() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/"));
verify(InvokeTwiceDoesNotOverrideConfig.AEP).commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
}
@ -278,17 +256,14 @@ public class ExceptionHandlingConfigurerTests {
// @formatter:off
}
}
@EnableWebSecurity
static class HttpBasicAndFormLoginEntryPointsConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off

View File

@ -93,7 +93,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void configureWhenNoCustomAccessDecisionManagerThenUsesAffirmativeBased() {
this.spring.register(NoSpecificAccessDecisionManagerConfig.class).autowire();
verify(NoSpecificAccessDecisionManagerConfig.objectPostProcessor).postProcess(any(AffirmativeBased.class));
}
@ -113,7 +112,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenHasAnyAuthorityRoleUserConfiguredAndAuthorityIsRoleUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserAnyAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_USER"))))
.andExpect(status().isOk());
}
@ -122,7 +120,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenHasAnyAuthorityRoleUserConfiguredAndAuthorityIsRoleAdminThenRespondsWithForbidden()
throws Exception {
this.spring.register(RoleUserAnyAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))))
.andExpect(status().isForbidden());
}
@ -130,14 +127,12 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenHasAnyAuthorityRoleUserConfiguredAndNoAuthorityThenRespondsWithUnauthorized() throws Exception {
this.spring.register(RoleUserAnyAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenHasAuthorityRoleUserConfiguredAndAuthorityIsRoleUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_USER"))))
.andExpect(status().isOk());
}
@ -146,7 +141,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenHasAuthorityRoleUserConfiguredAndAuthorityIsRoleAdminThenRespondsWithForbidden()
throws Exception {
this.spring.register(RoleUserAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))))
.andExpect(status().isForbidden());
}
@ -154,14 +148,12 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenHasAuthorityRoleUserConfiguredAndNoAuthorityThenRespondsWithUnauthorized() throws Exception {
this.spring.register(RoleUserAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenAuthorityRoleUserOrAdminRequiredAndAuthorityIsRoleUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserOrRoleAdminAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_USER"))))
.andExpect(status().isOk());
}
@ -169,7 +161,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenAuthorityRoleUserOrAdminRequiredAndAuthorityIsRoleAdminThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserOrRoleAdminAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))))
.andExpect(status().isOk());
}
@ -178,7 +169,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenAuthorityRoleUserOrAdminRequiredAndAuthorityIsRoleOtherThenRespondsWithForbidden()
throws Exception {
this.spring.register(RoleUserOrRoleAdminAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_OTHER"))))
.andExpect(status().isForbidden());
}
@ -186,49 +176,42 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenAuthorityRoleUserOrAdminAuthRequiredAndNoUserThenRespondsWithUnauthorized() throws Exception {
this.spring.register(RoleUserOrRoleAdminAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenHasAnyRoleUserConfiguredAndRoleIsUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenHasAnyRoleUserConfiguredAndRoleIsAdminThenRespondsWithForbidden() throws Exception {
this.spring.register(RoleUserConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("ADMIN"))).andExpect(status().isForbidden());
}
@Test
public void getWhenRoleUserOrAdminConfiguredAndRoleIsUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserOrAdminConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenRoleUserOrAdminConfiguredAndRoleIsAdminThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserOrAdminConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("ADMIN"))).andExpect(status().isOk());
}
@Test
public void getWhenRoleUserOrAdminConfiguredAndRoleIsOtherThenRespondsWithForbidden() throws Exception {
this.spring.register(RoleUserOrAdminConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("OTHER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenHasIpAddressConfiguredAndIpAddressMatchesThenRespondsWithOk() throws Exception {
this.spring.register(HasIpAddressConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with((request) -> {
request.setRemoteAddr("192.168.1.0");
return request;
@ -238,7 +221,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenHasIpAddressConfiguredAndIpAddressDoesNotMatchThenRespondsWithUnauthorized() throws Exception {
this.spring.register(HasIpAddressConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with((request) -> {
request.setRemoteAddr("192.168.1.1");
return request;
@ -248,28 +230,24 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenAnonymousConfiguredAndAnonymousUserThenRespondsWithOk() throws Exception {
this.spring.register(AnonymousConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void getWhenAnonymousConfiguredAndLoggedInUserThenRespondsWithForbidden() throws Exception {
this.spring.register(AnonymousConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user"))).andExpect(status().isForbidden());
}
@Test
public void getWhenRememberMeConfiguredAndNoUserThenRespondsWithUnauthorized() throws Exception {
this.spring.register(RememberMeConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenRememberMeConfiguredAndRememberMeTokenThenRespondsWithOk() throws Exception {
this.spring.register(RememberMeConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(authentication(
new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))))
.andExpect(status().isOk());
@ -278,28 +256,24 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenDenyAllConfiguredAndNoUserThenRespondsWithUnauthorized() throws Exception {
this.spring.register(DenyAllConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWheDenyAllConfiguredAndUserLoggedInThenRespondsWithForbidden() throws Exception {
this.spring.register(DenyAllConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenNotDenyAllConfiguredAndNoUserThenRespondsWithOk() throws Exception {
this.spring.register(NotDenyAllConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void getWhenNotDenyAllConfiguredAndRememberMeTokenThenRespondsWithOk() throws Exception {
this.spring.register(NotDenyAllConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(authentication(
new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))))
.andExpect(status().isOk());
@ -308,7 +282,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenFullyAuthenticatedConfiguredAndRememberMeTokenThenRespondsWithUnauthorized() throws Exception {
this.spring.register(FullyAuthenticatedConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(authentication(
new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))))
.andExpect(status().isUnauthorized());
@ -317,35 +290,30 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenFullyAuthenticatedConfiguredAndUserThenRespondsWithOk() throws Exception {
this.spring.register(FullyAuthenticatedConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenAccessRoleUserOrGetRequestConfiguredThenRespondsWithOk() throws Exception {
this.spring.register(AccessConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void postWhenAccessRoleUserOrGetRequestConfiguredAndRoleUserThenRespondsWithOk() throws Exception {
this.spring.register(AccessConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/").with(csrf()).with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void postWhenAccessRoleUserOrGetRequestConfiguredThenRespondsWithUnauthorized() throws Exception {
this.spring.register(AccessConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/").with(csrf())).andExpect(status().isUnauthorized());
}
@Test
public void authorizeRequestsWhenInvokedTwiceThenUsesOriginalConfiguration() throws Exception {
this.spring.register(InvokeTwiceDoesNotResetConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/").with(csrf())).andExpect(status().isUnauthorized());
}
@ -358,58 +326,49 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenApplicationListenerInvokedOnAuthorizedEvent()
throws Exception {
this.spring.register(AuthorizedRequestsWithPostProcessorConfig.class).autowire();
this.mvc.perform(get("/"));
verify(AuthorizedRequestsWithPostProcessorConfig.AL).onApplicationEvent(any(AuthorizedEvent.class));
}
@Test
public void getWhenPermissionCheckAndRoleDoesNotMatchThenRespondsWithForbidden() throws Exception {
this.spring.register(UseBeansInExpressions.class, WildcardController.class).autowire();
this.mvc.perform(get("/admin").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenPermissionCheckAndRoleMatchesThenRespondsWithOk() throws Exception {
this.spring.register(UseBeansInExpressions.class, WildcardController.class).autowire();
this.mvc.perform(get("/user").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenPermissionCheckAndAuthenticationNameMatchesThenRespondsWithOk() throws Exception {
this.spring.register(UseBeansInExpressions.class, WildcardController.class).autowire();
this.mvc.perform(get("/allow").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenPermissionCheckAndAuthenticationNameDoesNotMatchThenRespondsWithForbidden() throws Exception {
this.spring.register(UseBeansInExpressions.class, WildcardController.class).autowire();
this.mvc.perform(get("/deny").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenCustomExpressionHandlerAndRoleDoesNotMatchThenRespondsWithForbidden() throws Exception {
this.spring.register(CustomExpressionRootConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/admin").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenCustomExpressionHandlerAndRoleMatchesThenRespondsWithOk() throws Exception {
this.spring.register(CustomExpressionRootConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/user").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenCustomExpressionHandlerAndAuthenticationNameMatchesThenRespondsWithOk() throws Exception {
this.spring.register(CustomExpressionRootConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/allow").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@ -417,7 +376,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenCustomExpressionHandlerAndAuthenticationNameDoesNotMatchThenRespondsWithForbidden()
throws Exception {
this.spring.register(CustomExpressionRootConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/deny").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@ -425,7 +383,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnAccessDecisionManager() {
this.spring.register(Sec3011Config.class).autowire();
verify(Sec3011Config.objectPostProcessor).postProcess(any(AccessDecisionManager.class));
}
@ -433,7 +390,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenRegisteringPermissionEvaluatorAndPermissionWithIdAndTypeMatchesThenRespondsWithOk()
throws Exception {
this.spring.register(PermissionEvaluatorConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/allow")).andExpect(status().isOk());
}
@ -441,7 +397,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenRegisteringPermissionEvaluatorAndPermissionWithIdAndTypeDoesNotMatchThenRespondsWithForbidden()
throws Exception {
this.spring.register(PermissionEvaluatorConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/deny")).andExpect(status().isForbidden());
}
@ -449,7 +404,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenRegisteringPermissionEvaluatorAndPermissionWithObjectMatchesThenRespondsWithOk()
throws Exception {
this.spring.register(PermissionEvaluatorConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/allowObject")).andExpect(status().isOk());
}
@ -457,21 +411,18 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenRegisteringPermissionEvaluatorAndPermissionWithObjectDoesNotMatchThenRespondsWithForbidden()
throws Exception {
this.spring.register(PermissionEvaluatorConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/denyObject")).andExpect(status().isForbidden());
}
@Test
public void getWhenRegisteringRoleHierarchyAndRelatedRoleAllowedThenRespondsWithOk() throws Exception {
this.spring.register(RoleHierarchyConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/allow").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenRegisteringRoleHierarchyAndNoRelatedRolesAllowedThenRespondsWithForbidden() throws Exception {
this.spring.register(RoleHierarchyConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/deny").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@ -939,7 +890,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Bean
PermissionEvaluator permissionEvaluator() {
return new PermissionEvaluator() {
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject,
Object permission) {
@ -951,7 +901,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
Object permission) {
return "ID".equals(targetId) && "TYPE".equals(targetType) && "PERMISSION".equals(permission);
}
};
}

View File

@ -69,29 +69,22 @@ public class FormLoginConfigurerTests {
@Test
public void requestCache() throws Exception {
this.spring.register(RequestCacheConfig.class, AuthenticationTestConfiguration.class).autowire();
RequestCacheConfig config = this.spring.getContext().getBean(RequestCacheConfig.class);
this.mockMvc.perform(formLogin()).andExpect(authenticated());
verify(config.requestCache).getRequest(any(), any());
}
@Test
public void requestCacheAsBean() throws Exception {
this.spring.register(RequestCacheBeanConfig.class, AuthenticationTestConfiguration.class).autowire();
RequestCache requestCache = this.spring.getContext().getBean(RequestCache.class);
this.mockMvc.perform(formLogin()).andExpect(authenticated());
verify(requestCache).getRequest(any(), any());
}
@Test
public void loginWhenFormLoginConfiguredThenHasDefaultUsernameAndPasswordParameterNames() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(formLogin().user("username", "user").password("password", "password"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@ -99,7 +92,6 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginConfiguredThenHasDefaultFailureUrl() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(formLogin().user("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?error"));
}
@ -107,28 +99,24 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginConfiguredThenHasDefaultSuccessUrl() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@Test
public void getLoginPageWhenFormLoginConfiguredThenNotSecured() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(get("/login")).andExpect(status().isFound());
}
@Test
public void loginWhenFormLoginConfiguredThenSecured() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(post("/login")).andExpect(status().isForbidden());
}
@Test
public void requestProtectedWhenFormLoginConfiguredThenRedirectsToLogin() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(get("/private")).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login"));
}
@ -136,7 +124,6 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginDefaultsInLambdaThenHasDefaultUsernameAndPasswordParameterNames() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(formLogin().user("username", "user").password("password", "password"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@ -144,7 +131,6 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginDefaultsInLambdaThenHasDefaultFailureUrl() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(formLogin().user("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?error"));
}
@ -152,28 +138,24 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginDefaultsInLambdaThenHasDefaultSuccessUrl() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@Test
public void getLoginPageWhenFormLoginDefaultsInLambdaThenNotSecured() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(get("/login")).andExpect(status().isOk());
}
@Test
public void loginWhenFormLoginDefaultsInLambdaThenSecured() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(post("/login")).andExpect(status().isForbidden());
}
@Test
public void requestProtectedWhenFormLoginDefaultsInLambdaThenRedirectsToLogin() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(get("/private")).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login"));
}
@ -181,21 +163,18 @@ public class FormLoginConfigurerTests {
@Test
public void getLoginPageWhenFormLoginPermitAllThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginConfigPermitAll.class).autowire();
this.mockMvc.perform(get("/login")).andExpect(status().isOk()).andExpect(redirectedUrl(null));
}
@Test
public void getLoginPageWithErrorQueryWhenFormLoginPermitAllThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginConfigPermitAll.class).autowire();
this.mockMvc.perform(get("/login?error")).andExpect(status().isOk()).andExpect(redirectedUrl(null));
}
@Test
public void loginWhenFormLoginPermitAllAndInvalidUserThenRedirectsToLoginPageWithError() throws Exception {
this.spring.register(FormLoginConfigPermitAll.class).autowire();
this.mockMvc.perform(formLogin().user("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?error"));
}
@ -203,21 +182,18 @@ public class FormLoginConfigurerTests {
@Test
public void getLoginPageWhenCustomLoginPageThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(get("/authenticate")).andExpect(redirectedUrl(null));
}
@Test
public void getLoginPageWithErrorQueryWhenCustomLoginPageThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(get("/authenticate?error")).andExpect(redirectedUrl(null));
}
@Test
public void loginWhenCustomLoginPageAndInvalidUserThenRedirectsToCustomLoginPageWithError() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(formLogin("/authenticate").user("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/authenticate?error"));
}
@ -225,35 +201,30 @@ public class FormLoginConfigurerTests {
@Test
public void logoutWhenCustomLoginPageThenRedirectsToCustomLoginPage() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(logout()).andExpect(redirectedUrl("/authenticate?logout"));
}
@Test
public void getLoginPageWithLogoutQueryWhenCustomLoginPageThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(get("/authenticate?logout")).andExpect(redirectedUrl(null));
}
@Test
public void getLoginPageWhenCustomLoginPageInLambdaThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginDefaultsInLambdaConfig.class).autowire();
this.mockMvc.perform(get("/authenticate")).andExpect(redirectedUrl(null));
}
@Test
public void loginWhenCustomLoginProcessingUrlThenRedirectsToHome() throws Exception {
this.spring.register(FormLoginLoginProcessingUrlConfig.class).autowire();
this.mockMvc.perform(formLogin("/loginCheck")).andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@Test
public void loginWhenCustomLoginProcessingUrlInLambdaThenRedirectsToHome() throws Exception {
this.spring.register(FormLoginLoginProcessingUrlInLambdaConfig.class).autowire();
this.mockMvc.perform(formLogin("/loginCheck")).andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@ -262,17 +233,14 @@ public class FormLoginConfigurerTests {
FormLoginUsesPortMapperConfig.PORT_MAPPER = mock(PortMapper.class);
given(FormLoginUsesPortMapperConfig.PORT_MAPPER.lookupHttpsPort(any())).willReturn(9443);
this.spring.register(FormLoginUsesPortMapperConfig.class).autowire();
this.mockMvc.perform(get("http://localhost:9090")).andExpect(status().isFound())
.andExpect(redirectedUrl("https://localhost:9443/login"));
verify(FormLoginUsesPortMapperConfig.PORT_MAPPER).lookupHttpsPort(any());
}
@Test
public void failureUrlWhenPermitAllAndFailureHandlerThenSecured() throws Exception {
this.spring.register(PermitAllIgnoresFailureHandlerConfig.class).autowire();
this.mockMvc.perform(get("/login?error")).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login"));
}
@ -280,21 +248,18 @@ public class FormLoginConfigurerTests {
@Test
public void formLoginWhenInvokedTwiceThenUsesOriginalUsernameParameter() throws Exception {
this.spring.register(DuplicateInvocationsDoesNotOverrideConfig.class).autowire();
this.mockMvc.perform(formLogin().user("custom-username", "user")).andExpect(authenticated());
}
@Test
public void loginWhenInvalidLoginAndFailureForwardUrlThenForwardsToFailureForwardUrl() throws Exception {
this.spring.register(FormLoginUserForwardAuthenticationSuccessAndFailureConfig.class).autowire();
this.mockMvc.perform(formLogin().user("invalid")).andExpect(forwardedUrl("/failure_forward_url"));
}
@Test
public void loginWhenSuccessForwardUrlThenForwardsToSuccessForwardUrl() throws Exception {
this.spring.register(FormLoginUserForwardAuthenticationSuccessAndFailureConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(forwardedUrl("/success_forward_url"));
}
@ -302,7 +267,6 @@ public class FormLoginConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnUsernamePasswordAuthenticationFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(UsernamePasswordAuthenticationFilter.class));
}
@ -311,7 +275,6 @@ public class FormLoginConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnLoginUrlAuthenticationEntryPoint() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(LoginUrlAuthenticationEntryPoint.class));
}
@ -319,7 +282,6 @@ public class FormLoginConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnExceptionTranslationFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ExceptionTranslationFilter.class));
}

View File

@ -48,7 +48,6 @@ public class HeadersConfigurerEagerHeadersTests {
@Test
public void requestWhenHeadersEagerlyConfiguredThenHeadersAreWritten() throws Exception {
this.spring.register(HeadersAtTheBeginningOfRequestConfig.class).autowire();
this.mvc.perform(get("/").secure(true)).andExpect(header().string("X-Content-Type-Options", "nosniff"))
.andExpect(header().string("X-Frame-Options", "DENY"))
.andExpect(header().string("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"))

View File

@ -62,7 +62,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHeadersConfiguredThenDefaultHeadersInResponse() throws Exception {
this.spring.register(HeadersConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
@ -80,7 +79,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHeadersConfiguredInLambdaThenDefaultHeadersInResponse() throws Exception {
this.spring.register(HeadersInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
@ -99,7 +97,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndContentTypeConfiguredThenOnlyContentTypeHeaderInResponse()
throws Exception {
this.spring.register(ContentTypeOptionsConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS);
@ -108,7 +105,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenOnlyContentTypeConfiguredInLambdaThenOnlyContentTypeHeaderInResponse() throws Exception {
this.spring.register(ContentTypeOptionsInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS);
@ -118,7 +114,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndFrameOptionsConfiguredThenOnlyFrameOptionsHeaderInResponse()
throws Exception {
this.spring.register(FrameOptionsConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name())).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_FRAME_OPTIONS);
@ -128,7 +123,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndHstsConfiguredThenOnlyStrictTransportSecurityHeaderInResponse()
throws Exception {
this.spring.register(HstsConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
@ -140,7 +134,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndCacheControlConfiguredThenCacheControlAndExpiresAndPragmaHeadersInResponse()
throws Exception {
this.spring.register(CacheControlConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
@ -153,7 +146,6 @@ public class HeadersConfigurerTests {
public void getWhenOnlyCacheControlConfiguredInLambdaThenCacheControlAndExpiresAndPragmaHeadersInResponse()
throws Exception {
this.spring.register(CacheControlInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
@ -166,7 +158,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndXssProtectionConfiguredThenOnlyXssProtectionHeaderInResponse()
throws Exception {
this.spring.register(XssProtectionConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
@ -175,7 +166,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenOnlyXssProtectionConfiguredInLambdaThenOnlyXssProtectionHeaderInResponse() throws Exception {
this.spring.register(XssProtectionInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
@ -184,7 +174,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenFrameOptionsSameOriginConfiguredThenFrameOptionsHeaderHasValueSameOrigin() throws Exception {
this.spring.register(HeadersCustomSameOriginConfig.class).autowire();
this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.SAMEORIGIN.name()))
.andReturn();
@ -194,7 +183,6 @@ public class HeadersConfigurerTests {
public void getWhenFrameOptionsSameOriginConfiguredInLambdaThenFrameOptionsHeaderHasValueSameOrigin()
throws Exception {
this.spring.register(HeadersCustomSameOriginInLambdaConfig.class).autowire();
this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.SAMEORIGIN.name()))
.andReturn();
@ -203,7 +191,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHeaderDefaultsDisabledAndPublicHpkpWithNoPinThenNoHeadersInResponse() throws Exception {
this.spring.register(HpkpConfigNoPins.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).isEmpty();
}
@ -211,7 +198,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenSecureRequestAndHpkpWithPinThenPublicKeyPinsReportOnlyHeaderInResponse() throws Exception {
this.spring.register(HpkpConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""))
@ -222,7 +208,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenInsecureRequestHeaderDefaultsDisabledAndHpkpWithPinThenNoHeadersInResponse() throws Exception {
this.spring.register(HpkpConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).isEmpty();
}
@ -231,7 +216,6 @@ public class HeadersConfigurerTests {
public void getWhenHpkpWithMultiplePinsThenPublicKeyPinsReportOnlyHeaderWithMultiplePinsInResponse()
throws Exception {
this.spring.register(HpkpConfigWithPins.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\""))
@ -242,7 +226,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHpkpWithCustomAgeThenPublicKeyPinsReportOnlyHeaderWithCustomAgeInResponse() throws Exception {
this.spring.register(HpkpConfigCustomAge.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=604800 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""))
@ -253,7 +236,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHpkpWithReportOnlyFalseThenPublicKeyPinsHeaderInResponse() throws Exception {
this.spring.register(HpkpConfigTerminateConnection.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.PUBLIC_KEY_PINS,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""))
@ -265,7 +247,6 @@ public class HeadersConfigurerTests {
public void getWhenHpkpIncludeSubdomainThenPublicKeyPinsReportOnlyHeaderWithIncludeSubDomainsInResponse()
throws Exception {
this.spring.register(HpkpConfigIncludeSubDomains.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; includeSubDomains"))
@ -276,7 +257,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHpkpWithReportUriThenPublicKeyPinsReportOnlyHeaderWithReportUriInResponse() throws Exception {
this.spring.register(HpkpConfigWithReportURI.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.net/pkp-report\""))
@ -288,7 +268,6 @@ public class HeadersConfigurerTests {
public void getWhenHpkpWithReportUriAsStringThenPublicKeyPinsReportOnlyHeaderWithReportUriInResponse()
throws Exception {
this.spring.register(HpkpConfigWithReportURIAsString.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.net/pkp-report\""))
@ -300,7 +279,6 @@ public class HeadersConfigurerTests {
public void getWhenHpkpWithReportUriInLambdaThenPublicKeyPinsReportOnlyHeaderWithReportUriInResponse()
throws Exception {
this.spring.register(HpkpWithReportUriInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.net/pkp-report\""))
@ -311,7 +289,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenContentSecurityPolicyConfiguredThenContentSecurityPolicyHeaderInResponse() throws Exception {
this.spring.register(ContentSecurityPolicyDefaultConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CONTENT_SECURITY_POLICY, "default-src 'self'")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CONTENT_SECURITY_POLICY);
@ -321,7 +298,6 @@ public class HeadersConfigurerTests {
public void getWhenContentSecurityPolicyWithReportOnlyThenContentSecurityPolicyReportOnlyHeaderInResponse()
throws Exception {
this.spring.register(ContentSecurityPolicyReportOnlyConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CONTENT_SECURITY_POLICY_REPORT_ONLY,
"default-src 'self'; script-src trustedscripts.example.com"))
@ -334,7 +310,6 @@ public class HeadersConfigurerTests {
public void getWhenContentSecurityPolicyWithReportOnlyInLambdaThenContentSecurityPolicyReportOnlyHeaderInResponse()
throws Exception {
this.spring.register(ContentSecurityPolicyReportOnlyInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CONTENT_SECURITY_POLICY_REPORT_ONLY,
"default-src 'self'; script-src trustedscripts.example.com"))
@ -358,7 +333,6 @@ public class HeadersConfigurerTests {
@Test
public void configureWhenContentSecurityPolicyNoPolicyDirectivesInLambdaThenDefaultHeaderValue() throws Exception {
this.spring.register(ContentSecurityPolicyNoDirectivesInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CONTENT_SECURITY_POLICY, "default-src 'self'")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CONTENT_SECURITY_POLICY);
@ -367,7 +341,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenReferrerPolicyConfiguredThenReferrerPolicyHeaderInResponse() throws Exception {
this.spring.register(ReferrerPolicyDefaultConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Referrer-Policy", ReferrerPolicy.NO_REFERRER.getPolicy())).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Referrer-Policy");
@ -376,7 +349,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenReferrerPolicyInLambdaThenReferrerPolicyHeaderInResponse() throws Exception {
this.spring.register(ReferrerPolicyDefaultInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Referrer-Policy", ReferrerPolicy.NO_REFERRER.getPolicy())).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Referrer-Policy");
@ -386,7 +358,6 @@ public class HeadersConfigurerTests {
public void getWhenReferrerPolicyConfiguredWithCustomValueThenReferrerPolicyHeaderWithCustomValueInResponse()
throws Exception {
this.spring.register(ReferrerPolicyCustomConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Referrer-Policy", ReferrerPolicy.SAME_ORIGIN.getPolicy())).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Referrer-Policy");
@ -395,7 +366,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenReferrerPolicyConfiguredWithCustomValueInLambdaThenCustomValueInResponse() throws Exception {
this.spring.register(ReferrerPolicyCustomInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Referrer-Policy", ReferrerPolicy.SAME_ORIGIN.getPolicy())).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Referrer-Policy");
@ -404,7 +374,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenFeaturePolicyConfiguredThenFeaturePolicyHeaderInResponse() throws Exception {
this.spring.register(FeaturePolicyConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Feature-Policy", "geolocation 'self'")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Feature-Policy");
@ -420,7 +389,6 @@ public class HeadersConfigurerTests {
public void getWhenHstsConfiguredWithPreloadThenStrictTransportSecurityHeaderWithPreloadInResponse()
throws Exception {
this.spring.register(HstsWithPreloadConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header()
.string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains ; preload"))
.andReturn();
@ -431,7 +399,6 @@ public class HeadersConfigurerTests {
public void getWhenHstsConfiguredWithPreloadInLambdaThenStrictTransportSecurityHeaderWithPreloadInResponse()
throws Exception {
this.spring.register(HstsWithPreloadInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header()
.string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains ; preload"))
.andReturn();
@ -659,7 +626,6 @@ public class HeadersConfigurerTests {
Map<String, String> pins = new LinkedHashMap<>();
pins.put("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "sha256");
pins.put("E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=", "sha256");
// @formatter:off
http
.headers()

View File

@ -67,14 +67,12 @@ public class HttpBasicConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnBasicAuthenticationFilter() {
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(BasicAuthenticationFilter.class));
}
@Test
public void httpBasicWhenUsingDefaultsInLambdaThenResponseIncludesBasicChallenge() throws Exception {
this.spring.register(DefaultsLambdaEntryPointConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized())
.andExpect(header().string("WWW-Authenticate", "Basic realm=\"Realm\""));
}
@ -83,7 +81,6 @@ public class HttpBasicConfigurerTests {
@Test
public void httpBasicWhenUsingDefaultsThenResponseIncludesBasicChallenge() throws Exception {
this.spring.register(DefaultsEntryPointConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized())
.andExpect(header().string("WWW-Authenticate", "Basic realm=\"Realm\""));
}
@ -91,9 +88,7 @@ public class HttpBasicConfigurerTests {
@Test
public void httpBasicWhenUsingCustomAuthenticationEntryPointThenResponseIncludesBasicChallenge() throws Exception {
this.spring.register(CustomAuthenticationEntryPointConfig.class).autowire();
this.mvc.perform(get("/"));
verify(CustomAuthenticationEntryPointConfig.ENTRY_POINT).commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
}
@ -101,9 +96,7 @@ public class HttpBasicConfigurerTests {
@Test
public void httpBasicWhenInvokedTwiceThenUsesOriginalEntryPoint() throws Exception {
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/"));
verify(DuplicateDoesNotOverrideConfig.ENTRY_POINT).commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
}
@ -112,7 +105,6 @@ public class HttpBasicConfigurerTests {
@Test
public void httpBasicWhenRememberMeConfiguredThenSetsRememberMeCookie() throws Exception {
this.spring.register(BasicUsesRememberMeConfig.class).autowire();
this.mvc.perform(get("/").with(httpBasic("user", "password")).param("remember-me", "true"))
.andExpect(cookie().exists("remember-me"));
}

View File

@ -73,9 +73,7 @@ public class HttpSecurityAntMatchersTests {
public void antMatchersMethodAndNoPatterns() throws Exception {
loadConfig(AntMatchersNoPatternsConfig.class);
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@ -84,9 +82,7 @@ public class HttpSecurityAntMatchersTests {
public void antMatchersMethodAndEmptyPatterns() throws Exception {
loadConfig(AntMatchersEmptyPatternsConfig.class);
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@ -94,7 +90,6 @@ public class HttpSecurityAntMatchersTests {
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configs);
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

View File

@ -73,17 +73,13 @@ public class HttpSecurityLogoutTests {
@Test
public void clearAuthenticationFalse() throws Exception {
loadConfig(ClearAuthenticationFalseConfig.class);
SecurityContext currentContext = SecurityContextHolder.createEmptyContext();
currentContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
currentContext);
this.request.setMethod("POST");
this.request.setServletPath("/logout");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(currentContext.getAuthentication()).isNotNull();
}
@ -91,7 +87,6 @@ public class HttpSecurityLogoutTests {
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configs);
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

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