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) { catch (IllegalArgumentException expected) {
} }
try { try {
AclFormattingUtils.demergePatterns("SOME STRING", null); AclFormattingUtils.demergePatterns("SOME STRING", null);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING"); AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING");
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH"); AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH");
} }
@ -68,7 +65,6 @@ public class AclFormattingUtilsTests {
String removeBits = "...............................R"; String removeBits = "...............................R";
assertThat(AclFormattingUtils.demergePatterns(original, removeBits)) assertThat(AclFormattingUtils.demergePatterns(original, removeBits))
.isEqualTo("...........................A...."); .isEqualTo("...........................A....");
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF"); assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF");
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo("......"); assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo("......");
} }
@ -81,21 +77,18 @@ public class AclFormattingUtilsTests {
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
AclFormattingUtils.mergePatterns("SOME STRING", null); AclFormattingUtils.mergePatterns("SOME STRING", null);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING"); AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING");
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH"); AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH");
} }
@ -108,7 +101,6 @@ public class AclFormattingUtilsTests {
String original = "...............................R"; String original = "...............................R";
String extraBits = "...........................A...."; String extraBits = "...........................A....";
assertThat(AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo("...........................A...R"); assertThat(AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo("...........................A...R");
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF"); assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF");
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")).isEqualTo("GHIJKL"); assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")).isEqualTo("GHIJKL");
} }
@ -116,21 +108,18 @@ public class AclFormattingUtilsTests {
@Test @Test
public final void testBinaryPrints() { public final void testBinaryPrints() {
assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****"); assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****");
try { try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON); AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException notExpected) { catch (IllegalArgumentException notExpected) {
} }
try { try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF); AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException notExpected) { catch (IllegalArgumentException notExpected) {
} }
assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx"); 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") }; ObjectIdentity[] oids = { new ObjectIdentityImpl("A", "1"), new ObjectIdentityImpl("A", "2") };
given(oidStrat.getObjectIdentity(dos[0])).willReturn(oids[0]); given(oidStrat.getObjectIdentity(dos[0])).willReturn(oids[0]);
given(oidStrat.getObjectIdentity(dos[2])).willReturn(oids[1]); given(oidStrat.getObjectIdentity(dos[2])).willReturn(oids[1]);
pco.cachePermissionsFor(mock(Authentication.class), Arrays.asList(dos)); pco.cachePermissionsFor(mock(Authentication.class), Arrays.asList(dos));
// AclService should be invoked with the list of required Oids // AclService should be invoked with the list of required Oids
verify(service).readAclsById(eq(Arrays.asList(oids)), any(List.class)); verify(service).readAclsById(eq(Arrays.asList(oids)), any(List.class));
} }
@ -69,9 +67,7 @@ public class AclPermissionCacheOptimizerTests {
SidRetrievalStrategy sids = mock(SidRetrievalStrategy.class); SidRetrievalStrategy sids = mock(SidRetrievalStrategy.class);
pco.setObjectIdentityRetrievalStrategy(oids); pco.setObjectIdentityRetrievalStrategy(oids);
pco.setSidRetrievalStrategy(sids); pco.setSidRetrievalStrategy(sids);
pco.cachePermissionsFor(mock(Authentication.class), Collections.emptyList()); pco.cachePermissionsFor(mock(Authentication.class), Collections.emptyList());
verifyZeroInteractions(service, sids, oids); verifyZeroInteractions(service, sids, oids);
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -34,13 +34,11 @@ public class DataSourcePopulator implements InitializingBean {
@Override @Override
public void afterPropertiesSet() { public void afterPropertiesSet() {
Assert.notNull(this.template, "dataSource required"); Assert.notNull(this.template, "dataSource required");
this.template.execute( this.template.execute(
"CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(500) NOT NULL,ENABLED BOOLEAN NOT NULL);"); "CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(500) NOT NULL,ENABLED BOOLEAN NOT NULL);");
this.template.execute( 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));"); "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);"); 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 * 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 * password for rod is "koala" Encoded password for dianne is "emu" Encoded

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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