Apply updated Code Style

Closes gh-13881
This commit is contained in:
Marcus Da Coregio 2023-09-29 11:44:32 -03:00
parent 650692964e
commit 64e2a2ff8b
1172 changed files with 10805 additions and 8768 deletions

View File

@ -49,7 +49,7 @@ import org.springframework.util.Assert;
public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy { public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
private final GrantedAuthority gaGeneralChanges; private final GrantedAuthority gaGeneralChanges;

View File

@ -110,9 +110,9 @@ public class EhCacheBasedAclCache implements AclCache {
if (this.aclAuthorizationStrategy == null) { if (this.aclAuthorizationStrategy == null) {
if (acl instanceof AclImpl) { if (acl instanceof AclImpl) {
this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils
.getProtectedFieldValue("aclAuthorizationStrategy", acl); .getProtectedFieldValue("aclAuthorizationStrategy", acl);
this.permissionGrantingStrategy = (PermissionGrantingStrategy) FieldUtils this.permissionGrantingStrategy = (PermissionGrantingStrategy) FieldUtils
.getProtectedFieldValue("permissionGrantingStrategy", acl); .getProtectedFieldValue("permissionGrantingStrategy", acl);
} }
} }
if ((acl.getParentAcl() != null) && (acl.getParentAcl() instanceof MutableAcl)) { if ((acl.getParentAcl() != null) && (acl.getParentAcl() instanceof MutableAcl)) {

View File

@ -54,7 +54,7 @@ public class SidRetrievalStrategyImpl implements SidRetrievalStrategy {
@Override @Override
public List<Sid> getSids(Authentication authentication) { public List<Sid> getSids(Authentication authentication) {
Collection<? extends GrantedAuthority> authorities = this.roleHierarchy Collection<? extends GrantedAuthority> authorities = this.roleHierarchy
.getReachableGrantedAuthorities(authentication.getAuthorities()); .getReachableGrantedAuthorities(authentication.getAuthorities());
List<Sid> sids = new ArrayList<>(authorities.size() + 1); List<Sid> sids = new ArrayList<>(authorities.size() + 1);
sids.add(new PrincipalSid(authentication)); sids.add(new PrincipalSid(authentication));
for (GrantedAuthority authority : authorities) { for (GrantedAuthority authority : authorities) {

View File

@ -579,7 +579,7 @@ public class BasicLookupStrategy implements LookupStrategy {
Serializable identifier = (Serializable) rs.getObject("object_id_identity"); Serializable identifier = (Serializable) rs.getObject("object_id_identity");
identifier = BasicLookupStrategy.this.aclClassIdUtils.identifierFrom(identifier, rs); identifier = BasicLookupStrategy.this.aclClassIdUtils.identifierFrom(identifier, rs);
ObjectIdentity objectIdentity = BasicLookupStrategy.this.objectIdentityGenerator ObjectIdentity objectIdentity = BasicLookupStrategy.this.objectIdentityGenerator
.createObjectIdentity(identifier, rs.getString("class")); .createObjectIdentity(identifier, rs.getString("class"));
Acl parentAcl = null; Acl parentAcl = null;
long parentAclId = rs.getLong("parent_object"); long parentAclId = rs.getLong("parent_object");

View File

@ -66,7 +66,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
private static final String DEFAULT_INSERT_INTO_ACL_CLASS_WITH_ID = "insert into acl_class (class, class_id_type) values (?, ?)"; private static final String DEFAULT_INSERT_INTO_ACL_CLASS_WITH_ID = "insert into acl_class (class, class_id_type) values (?, ?)";
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
private boolean foreignKeysInDatabase = true; private boolean foreignKeysInDatabase = true;

View File

@ -37,7 +37,7 @@ public class AclFormattingUtilsTests {
assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns(null, "SOME STRING")); assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns(null, "SOME STRING"));
assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", null)); assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", null));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING")); .isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING"));
assertThatNoException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH")); assertThatNoException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH"));
} }
@ -46,7 +46,7 @@ public class AclFormattingUtilsTests {
String original = "...........................A...R"; String original = "...........................A...R";
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("......");
} }
@ -56,7 +56,7 @@ public class AclFormattingUtilsTests {
assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns(null, "SOME STRING")); assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns(null, "SOME STRING"));
assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", null)); assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", null));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING")); .isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING"));
assertThatNoException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH")); assertThatNoException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH"));
} }
@ -73,9 +73,9 @@ public class AclFormattingUtilsTests {
public final void testBinaryPrints() { public final void testBinaryPrints() {
assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****"); assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****");
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_ON)); .isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_ON));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF)); .isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF));
assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx"); assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx");
} }

View File

@ -85,7 +85,8 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
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

@ -54,7 +54,7 @@ public class AclEntryAfterInvocationProviderTests {
@Test @Test
public void rejectsMissingPermissions() { public void rejectsMissingPermissions() {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new AclEntryAfterInvocationProvider(mock(AclService.class), null)); .isThrownBy(() -> new AclEntryAfterInvocationProvider(mock(AclService.class), null));
assertThatIllegalArgumentException().isThrownBy( assertThatIllegalArgumentException().isThrownBy(
() -> new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.<Permission>emptyList())); () -> new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.<Permission>emptyList()));
} }
@ -112,12 +112,12 @@ public class AclEntryAfterInvocationProviderTests {
provider.setProcessDomainObjectClass(Object.class); provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class)); provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
assertThatExceptionOfType(AccessDeniedException.class) assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), .isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object())); SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
// Second scenario with no acls found // Second scenario with no acls found
assertThatExceptionOfType(AccessDeniedException.class) assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), .isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object())); SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
} }
@Test @Test
@ -126,7 +126,8 @@ public class AclEntryAfterInvocationProviderTests {
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

@ -77,14 +77,14 @@ public class AccessControlImplEntryTests {
assertThat(ace).isNotNull(); assertThat(ace).isNotNull();
assertThat(ace).isNotEqualTo(100L); assertThat(ace).isNotEqualTo(100L);
assertThat(ace).isEqualTo(ace); assertThat(ace).isEqualTo(ace);
assertThat(ace).isEqualTo( assertThat(ace)
new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true)); .isEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true));
assertThat(ace).isNotEqualTo( assertThat(ace).isNotEqualTo(
new AccessControlEntryImpl(2L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true)); new AccessControlEntryImpl(2L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true));
assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, new PrincipalSid("scott"), assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, new PrincipalSid("scott"),
BasePermission.ADMINISTRATION, true, true, true)); BasePermission.ADMINISTRATION, true, true, true));
assertThat(ace) assertThat(ace)
.isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.WRITE, true, true, true)); .isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.WRITE, true, true, true));
assertThat(ace).isNotEqualTo( assertThat(ace).isNotEqualTo(
new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, false, true, true)); new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, false, true, true));
assertThat(ace).isNotEqualTo( assertThat(ace).isNotEqualTo(

View File

@ -103,7 +103,7 @@ public class AclImplTests {
assertThatIllegalArgumentException().isThrownBy( assertThatIllegalArgumentException().isThrownBy(
() -> new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe"))); () -> new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger)); .isThrownBy(() -> new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger));
} }
@Test @Test
@ -111,7 +111,7 @@ public class AclImplTests {
assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy, assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy,
this.pgs, null, null, true, new PrincipalSid("joe"))); this.pgs, null, null, true, new PrincipalSid("joe")));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger)); .isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger));
} }
@Test @Test
@ -120,7 +120,7 @@ public class AclImplTests {
new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null, null, true, new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null, null, true,
new PrincipalSid("joe"))); new PrincipalSid("joe")));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger)); .isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger));
} }
@Test @Test
@ -128,7 +128,7 @@ 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"));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true)); .isThrownBy(() -> acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true));
assertThatIllegalArgumentException().isThrownBy(() -> acl.insertAce(0, BasePermission.READ, null, true)); assertThatIllegalArgumentException().isThrownBy(() -> acl.insertAce(0, BasePermission.READ, null, true));
} }
@ -175,7 +175,7 @@ public class AclImplTests {
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);
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true)); .isThrownBy(() -> acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true));
} }
@Test @Test
@ -223,7 +223,7 @@ public class AclImplTests {
new PrincipalSid("joe")); new PrincipalSid("joe"));
Sid ben = new PrincipalSid("ben"); Sid ben = new PrincipalSid("ben");
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false)); .isThrownBy(() -> acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false));
assertThatIllegalArgumentException().isThrownBy(() -> acl.isGranted(READ, new ArrayList<>(0), false)); assertThatIllegalArgumentException().isThrownBy(() -> acl.isGranted(READ, new ArrayList<>(0), false));
} }
@ -246,12 +246,14 @@ public class AclImplTests {
List<Sid> sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST")); List<Sid> sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST"));
assertThat(rootAcl.isGranted(permissions, sids, false)).isFalse(); assertThat(rootAcl.isGranted(permissions, sids, false)).isFalse();
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> rootAcl.isGranted(permissions, SCOTT, false)); .isThrownBy(() -> rootAcl.isGranted(permissions, SCOTT, false));
assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue(); assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue();
assertThat(rootAcl.isGranted(WRITE, assertThat(rootAcl.isGranted(WRITE,
Arrays.asList(new PrincipalSid("rod"), new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false)).isFalse(); Arrays.asList(new PrincipalSid("rod"), new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false))
.isFalse();
assertThat(rootAcl.isGranted(WRITE, assertThat(rootAcl.isGranted(WRITE,
Arrays.asList(new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false)).isTrue(); Arrays.asList(new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false))
.isTrue();
// Change the type of the Sid and check the granting process // Change the type of the Sid and check the granting process
assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> rootAcl.isGranted(WRITE, assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> rootAcl.isGranted(WRITE,
Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false)); Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false));
@ -292,7 +294,7 @@ public class AclImplTests {
// 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))
.isTrue(); .isTrue();
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();
@ -303,13 +305,13 @@ public class AclImplTests {
// 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)
assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> childAcl2.isGranted(CREATE, SCOTT, false)); assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> childAcl2.isGranted(CREATE, SCOTT, false));
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false)); .isThrownBy(() -> childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false));
} }
@Test @Test
@ -396,20 +398,20 @@ public class AclImplTests {
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();
assertThat(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_IGNORED")))).isTrue(); assertThat(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_IGNORED")))).isTrue();
assertThat(acl.isSidLoaded(BEN)).isTrue(); assertThat(acl.isSidLoaded(BEN)).isTrue();
assertThat(acl.isSidLoaded(null)).isTrue(); assertThat(acl.isSidLoaded(null)).isTrue();
assertThat(acl.isSidLoaded(new ArrayList<>(0))).isTrue(); assertThat(acl.isSidLoaded(new ArrayList<>(0))).isTrue();
assertThat(acl.isSidLoaded( assertThat(acl.isSidLoaded(
Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_IGNORED")))) Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_IGNORED"))))
.isTrue(); .isTrue();
assertThat(acl.isSidLoaded( assertThat(acl.isSidLoaded(
Arrays.asList(new GrantedAuthoritySid("ROLE_GENERAL"), new GrantedAuthoritySid("ROLE_IGNORED")))) Arrays.asList(new GrantedAuthoritySid("ROLE_GENERAL"), new GrantedAuthoritySid("ROLE_IGNORED"))))
.isFalse(); .isFalse();
assertThat(acl.isSidLoaded( assertThat(acl.isSidLoaded(
Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_GENERAL")))) Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_GENERAL"))))
.isFalse(); .isFalse();
} }
@Test @Test
@ -417,7 +419,7 @@ public class AclImplTests {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true)); .isThrownBy(() -> acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true));
} }
@Test @Test
@ -435,7 +437,7 @@ public class AclImplTests {
acl.insertAce(0, mock(Permission.class), mock(Sid.class), true); acl.insertAce(0, mock(Permission.class), mock(Sid.class), true);
// Size is now 1 // Size is now 1
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> acl.insertAce(2, mock(Permission.class), mock(Sid.class), true)); .isThrownBy(() -> acl.insertAce(2, mock(Permission.class), mock(Sid.class), true));
} }
// SEC-1151 // SEC-1151
@ -466,7 +468,7 @@ public class AclImplTests {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, maskPgs, null, null, true, AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, maskPgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
Permission permission = this.permissionFactory Permission permission = this.permissionFactory
.buildFromMask(BasePermission.READ.getMask() | BasePermission.WRITE.getMask()); .buildFromMask(BasePermission.READ.getMask() | BasePermission.WRITE.getMask());
Sid sid = new PrincipalSid("ben"); Sid sid = new PrincipalSid("ben");
acl.insertAce(0, permission, sid, true); acl.insertAce(0, permission, sid, true);
service.updateAcl(acl); service.updateAcl(acl);

View File

@ -73,12 +73,12 @@ public class AclImplementationSecurityCheckTests {
new SimpleGrantedAuthority("ROLE_THREE")); new SimpleGrantedAuthority("ROLE_THREE"));
Acl acl2 = new AclImpl(identity, 1L, aclAuthorizationStrategy2, new ConsoleAuditLogger()); Acl acl2 = new AclImpl(identity, 1L, aclAuthorizationStrategy2, new ConsoleAuditLogger());
// Check access in case the principal has no authorization rights // Check access in case the principal has no authorization rights
assertThatExceptionOfType(NotFoundException.class).isThrownBy( assertThatExceptionOfType(NotFoundException.class)
() -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL)); .isThrownBy(() -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL));
assertThatExceptionOfType(NotFoundException.class).isThrownBy( assertThatExceptionOfType(NotFoundException.class)
() -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING)); .isThrownBy(() -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING));
assertThatExceptionOfType(NotFoundException.class).isThrownBy( assertThatExceptionOfType(NotFoundException.class)
() -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); .isThrownBy(() -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
} }
@Test @Test
@ -181,11 +181,11 @@ public class AclImplementationSecurityCheckTests {
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false,
new PrincipalSid(auth)); new PrincipalSid(auth));
assertThatNoException() assertThatNoException()
.isThrownBy(() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL)); .isThrownBy(() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL));
assertThatExceptionOfType(NotFoundException.class).isThrownBy( assertThatExceptionOfType(NotFoundException.class)
() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING)); .isThrownBy(() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING));
assertThatNoException().isThrownBy( assertThatNoException()
() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); .isThrownBy(() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
} }
} }

View File

@ -60,7 +60,7 @@ public class ObjectIdentityImplTests {
public void testGetIdMethodConstraints() { public void testGetIdMethodConstraints() {
// Check the getId() method is present // Check the getId() method is present
assertThatExceptionOfType(IdentityUnavailableException.class) assertThatExceptionOfType(IdentityUnavailableException.class)
.isThrownBy(() -> new ObjectIdentityImpl("A_STRING_OBJECT")); .isThrownBy(() -> new ObjectIdentityImpl("A_STRING_OBJECT"));
// getId() should return a non-null value // getId() should return a non-null value
MockIdDomainObject mockId = new MockIdDomainObject(); MockIdDomainObject mockId = new MockIdDomainObject();
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId)); assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId));

View File

@ -47,10 +47,12 @@ public class PermissionTests {
public void expectedIntegerValues() { public void expectedIntegerValues() {
assertThat(BasePermission.READ.getMask()).isEqualTo(1); assertThat(BasePermission.READ.getMask()).isEqualTo(1);
assertThat(BasePermission.ADMINISTRATION.getMask()).isEqualTo(16); assertThat(BasePermission.ADMINISTRATION.getMask()).isEqualTo(16);
assertThat(new CumulativePermission().set(BasePermission.READ).set(BasePermission.WRITE) assertThat(new CumulativePermission().set(BasePermission.READ)
.set(BasePermission.CREATE).getMask()).isEqualTo(7); .set(BasePermission.WRITE)
.set(BasePermission.CREATE)
.getMask()).isEqualTo(7);
assertThat(new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION).getMask()) assertThat(new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION).getMask())
.isEqualTo(17); .isEqualTo(17);
} }
@Test @Test
@ -64,20 +66,23 @@ public class PermissionTests {
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)
.clear(BasePermission.ADMINISTRATION).toString()) .set(BasePermission.READ)
.isEqualTo("CumulativePermission[...............................R=1]"); .clear(BasePermission.ADMINISTRATION)
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ) .toString()).isEqualTo("CumulativePermission[...............................R=1]");
.clear(BasePermission.ADMINISTRATION).clear(BasePermission.READ).toString()) assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION)
.isEqualTo("CumulativePermission[................................=0]"); .set(BasePermission.READ)
.clear(BasePermission.ADMINISTRATION)
.clear(BasePermission.READ)
.toString()).isEqualTo("CumulativePermission[................................=0]");
} }
} }

View File

@ -147,7 +147,7 @@ public abstract class AbstractBasicLookupStrategyTests {
// 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);
} }
@ -161,7 +161,7 @@ public abstract class AbstractBasicLookupStrategyTests {
// 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);
} }
@ -174,7 +174,7 @@ public abstract class AbstractBasicLookupStrategyTests {
// acls // acls
this.strategy.setBatchSize(1); this.strategy.setBatchSize(1);
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);
} }
@ -301,7 +301,7 @@ public abstract class AbstractBasicLookupStrategyTests {
getJdbcTemplate().execute(query); getJdbcTemplate().execute(query);
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 104L); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 104L);
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> this.strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID))); .isThrownBy(() -> this.strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)));
} }
@Test @Test

View File

@ -116,7 +116,7 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
public void testReadObjectIdentityUsingNonUuidInDatabase() { public void testReadObjectIdentityUsingNonUuidInDatabase() {
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_LONG_AS_UUID); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_LONG_AS_UUID);
assertThatExceptionOfType(ConversionFailedException.class) assertThatExceptionOfType(ConversionFailedException.class)
.isThrownBy(() -> this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID))); .isThrownBy(() -> this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)));
} }
} }

View File

@ -101,7 +101,7 @@ public class JdbcAclServiceTests {
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"));
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.aclService.readAclById(objectIdentity, sids)); .isThrownBy(() -> this.aclService.readAclById(objectIdentity, sids));
} }
@Test @Test
@ -168,20 +168,20 @@ public class JdbcAclServiceTests {
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("costcenter"); assertThat(objectIdentities.get(0).getType()).isEqualTo("costcenter");
assertThat(objectIdentities.get(0).getIdentifier()) assertThat(objectIdentities.get(0).getIdentifier())
.isEqualTo(UUID.fromString("25d93b3f-c3aa-4814-9d5e-c7c96ced7762")); .isEqualTo(UUID.fromString("25d93b3f-c3aa-4814-9d5e-c7c96ced7762"));
} }
@Test @Test
public void setObjectIdentityGeneratorWhenNullThenThrowsIllegalArgumentException() { public void setObjectIdentityGeneratorWhenNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> this.aclServiceIntegration.setObjectIdentityGenerator(null)) .isThrownBy(() -> this.aclServiceIntegration.setObjectIdentityGenerator(null))
.withMessage("objectIdentityGenerator cannot be null"); .withMessage("objectIdentityGenerator cannot be null");
} }
@Test @Test
public void findChildrenWhenObjectIdentityGeneratorSetThenUsed() { public void findChildrenWhenObjectIdentityGeneratorSetThenUsed() {
this.aclServiceIntegration this.aclServiceIntegration
.setObjectIdentityGenerator((id, type) -> new ObjectIdentityImpl(type, "prefix:" + id)); .setObjectIdentityGenerator((id, type) -> new ObjectIdentityImpl(type, "prefix:" + id));
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US"); ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US");
this.aclServiceIntegration.setAclClassIdSupported(true); this.aclServiceIntegration.setAclClassIdSupported(true);

View File

@ -168,7 +168,7 @@ public class JdbcMutableAclServiceTests {
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);
// Get the retrieved versions // Get the retrieved versions
MutableAcl retrievedTopParent = (MutableAcl) map.get(getTopParentOid()); MutableAcl retrievedTopParent = (MutableAcl) map.get(getTopParentOid());
@ -196,7 +196,7 @@ public class JdbcMutableAclServiceTests {
assertThat(retrievedMiddleParent.isGranted(delete, pSid, false)).isTrue(); assertThat(retrievedMiddleParent.isGranted(delete, pSid, false)).isTrue();
assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse(); assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse();
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> retrievedChild.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false)); .isThrownBy(() -> retrievedChild.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false));
// 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(retrievedChild.isGranted(read, pSid, false)).isTrue(); assertThat(retrievedChild.isGranted(read, pSid, false)).isTrue();
assertThat(retrievedChild.isGranted(write, pSid, false)).isFalse(); assertThat(retrievedChild.isGranted(write, pSid, false)).isFalse();
@ -209,9 +209,9 @@ public class JdbcMutableAclServiceTests {
// Check the child permissions no longer inherit // Check the child permissions no longer inherit
assertThat(nonInheritingChild.isGranted(delete, pSid, true)).isFalse(); assertThat(nonInheritingChild.isGranted(delete, pSid, true)).isFalse();
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> nonInheritingChild.isGranted(read, pSid, true)); .isThrownBy(() -> nonInheritingChild.isGranted(read, pSid, true));
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> nonInheritingChild.isGranted(write, pSid, true)); .isThrownBy(() -> nonInheritingChild.isGranted(write, pSid, true));
// 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
nonInheritingChild.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true); nonInheritingChild.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true);
@ -266,9 +266,9 @@ public class JdbcMutableAclServiceTests {
// 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);
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.jdbcMutableAclService.readAclById(getMiddleParentOid())); .isThrownBy(() -> this.jdbcMutableAclService.readAclById(getMiddleParentOid()));
assertThatExceptionOfType(NotFoundException.class) assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.jdbcMutableAclService.readAclById(getChildOid())); .isThrownBy(() -> this.jdbcMutableAclService.readAclById(getChildOid()));
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());
@ -277,11 +277,11 @@ public class JdbcMutableAclServiceTests {
@Test @Test
public void constructorRejectsNullParameters() { public void constructorRejectsNullParameters() {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache)); .isThrownBy(() -> new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcMutableAclService(this.dataSource, null, this.aclCache)); .isThrownBy(() -> new JdbcMutableAclService(this.dataSource, null, this.aclCache));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null)); .isThrownBy(() -> new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null));
} }
@Test @Test
@ -297,7 +297,7 @@ public class JdbcMutableAclServiceTests {
this.jdbcMutableAclService.createAcl(duplicateOid); this.jdbcMutableAclService.createAcl(duplicateOid);
// Try to add the same object second time // Try to add the same object second time
assertThatExceptionOfType(AlreadyExistsException.class) assertThatExceptionOfType(AlreadyExistsException.class)
.isThrownBy(() -> this.jdbcMutableAclService.createAcl(duplicateOid)); .isThrownBy(() -> this.jdbcMutableAclService.createAcl(duplicateOid));
} }
@Test @Test
@ -320,7 +320,7 @@ public class JdbcMutableAclServiceTests {
try { try {
// checking in the class, not database // checking in the class, not database
assertThatExceptionOfType(ChildrenExistException.class) assertThatExceptionOfType(ChildrenExistException.class)
.isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false)); .isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false));
} }
finally { finally {
// restore to the default // restore to the default
@ -392,7 +392,7 @@ public class JdbcMutableAclServiceTests {
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);
assertThat(parent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben")); assertThat(parent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben"));
assertThat(parent.getEntries().get(1).getPermission().getMask()).isEqualTo(1); assertThat(parent.getEntries().get(1).getPermission().getMask()).isEqualTo(1);

View File

@ -79,7 +79,7 @@ public class JdbcMutableAclServiceTestsWithAclClassId extends JdbcMutableAclServ
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

@ -46,9 +46,9 @@ public class SidTests {
// Check one Authentication-argument constructor // Check one Authentication-argument constructor
assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((Authentication) null)); assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((Authentication) null));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken(null, "password"))); .isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken(null, "password")));
assertThatNoException() assertThatNoException()
.isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken("johndoe", "password"))); .isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken("johndoe", "password")));
} }
@Test @Test
@ -60,7 +60,7 @@ public class SidTests {
// Check one GrantedAuthority-argument constructor // Check one GrantedAuthority-argument constructor
assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((GrantedAuthority) null)); assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((GrantedAuthority) null));
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority(null))); .isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority(null)));
assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST"))); assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST")));
} }
@ -100,7 +100,7 @@ public class SidTests {
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());
assertThat(principalSid.hashCode()) assertThat(principalSid.hashCode())
.isNotEqualTo(new PrincipalSid(new TestingAuthenticationToken("scott", "password")).hashCode()); .isNotEqualTo(new PrincipalSid(new TestingAuthenticationToken("scott", "password")).hashCode());
} }
@Test @Test
@ -111,7 +111,7 @@ public class SidTests {
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());
assertThat(gaSid.hashCode()) assertThat(gaSid.hashCode())
.isNotEqualTo(new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST_2")).hashCode()); .isNotEqualTo(new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST_2")).hashCode());
} }
@Test @Test

View File

@ -101,7 +101,7 @@ public class AnnotationSecurityAspectTests {
@Test @Test
public void securedClassMethodDeniesUnauthenticatedAccess() { public void securedClassMethodDeniesUnauthenticatedAccess() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.secured.securedClassMethod()); .isThrownBy(() -> this.secured.securedClassMethod());
} }
@Test @Test

View File

@ -68,7 +68,7 @@ public class PostAuthorizeAspectTests {
@Test @Test
public void securedClassMethodDeniesUnauthenticatedAccess() { public void securedClassMethodDeniesUnauthenticatedAccess() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.secured.securedClassMethod()); .isThrownBy(() -> this.secured.securedClassMethod());
} }
@Test @Test

View File

@ -68,7 +68,7 @@ public class PreAuthorizeAspectTests {
@Test @Test
public void securedClassMethodDeniesUnauthenticatedAccess() { public void securedClassMethodDeniesUnauthenticatedAccess() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.secured.securedClassMethod()); .isThrownBy(() -> this.secured.securedClassMethod());
} }
@Test @Test

View File

@ -66,7 +66,7 @@ public class SecuredAspectTests {
@Test @Test
public void securedClassMethodDeniesUnauthenticatedAccess() { public void securedClassMethodDeniesUnauthenticatedAccess() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.secured.securedClassMethod()); .isThrownBy(() -> this.secured.securedClassMethod());
} }
@Test @Test

View File

@ -98,7 +98,7 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
if (authentication instanceof UsernamePasswordAuthenticationToken if (authentication instanceof UsernamePasswordAuthenticationToken
&& (!CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER.equals(authentication.getPrincipal().toString()) && (!CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER.equals(authentication.getPrincipal().toString())
&& !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER && !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER
.equals(authentication.getPrincipal().toString()))) { .equals(authentication.getPrincipal().toString()))) {
// UsernamePasswordAuthenticationToken not CAS related // UsernamePasswordAuthenticationToken not CAS related
return null; return null;
} }

View File

@ -88,7 +88,7 @@ public class CasAuthenticationProviderTests {
cap.setTicketValidator(new MockTicketValidator(true)); cap.setTicketValidator(new MockTicketValidator(true));
cap.afterPropertiesSet(); cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken
.unauthenticated(CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, "ST-123"); .unauthenticated(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
@ -121,7 +121,7 @@ public class CasAuthenticationProviderTests {
cap.setServiceProperties(makeServiceProperties()); cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet(); cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken
.unauthenticated(CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, "ST-456"); .unauthenticated(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
@ -158,7 +158,7 @@ public class CasAuthenticationProviderTests {
cap.afterPropertiesSet(); cap.afterPropertiesSet();
String ticket = "ST-456"; String ticket = "ST-456";
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken
.unauthenticated(CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, ticket); .unauthenticated(CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, ticket);
Authentication result = cap.authenticate(token); Authentication result = cap.authenticate(token);
} }
@ -179,7 +179,7 @@ public class CasAuthenticationProviderTests {
cap.afterPropertiesSet(); cap.afterPropertiesSet();
String ticket = "ST-456"; String ticket = "ST-456";
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken
.unauthenticated(CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, ticket); .unauthenticated(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);
@ -212,7 +212,7 @@ public class CasAuthenticationProviderTests {
cap.setServiceProperties(makeServiceProperties()); cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet(); cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken
.unauthenticated(CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, ""); .unauthenticated(CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, "");
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token)); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token));
} }
@ -315,7 +315,7 @@ public class CasAuthenticationProviderTests {
cap.setServiceProperties(makeServiceProperties()); cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet(); cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken
.authenticated("some_normal_user", "password", AuthorityUtils.createAuthorityList("ROLE_A")); .authenticated("some_normal_user", "password", AuthorityUtils.createAuthorityList("ROLE_A"));
assertThat(cap.authenticate(token)).isNull(); assertThat(cap.authenticate(token)).isNull();
} }

View File

@ -103,7 +103,7 @@ public class CasAuthenticationTokenTests {
@Test @Test
public void testNoArgConstructorDoesntExist() { public void testNoArgConstructorDoesntExist() {
assertThatExceptionOfType(NoSuchMethodException.class) assertThatExceptionOfType(NoSuchMethodException.class)
.isThrownBy(() -> CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null)); .isThrownBy(() -> CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null));
} }
@Test @Test

View File

@ -132,7 +132,7 @@ public class CasAuthenticationTokenMixinTests {
assertThat(token.getAssertion()).isNotNull().isInstanceOf(AssertionImpl.class); assertThat(token.getAssertion()).isNotNull().isInstanceOf(AssertionImpl.class);
assertThat(token.getKeyHash()).isEqualTo(KEY.hashCode()); assertThat(token.getKeyHash()).isEqualTo(KEY.hashCode());
assertThat(token.getUserDetails().getAuthorities()).extracting(GrantedAuthority::getAuthority) assertThat(token.getUserDetails().getAuthorities()).extracting(GrantedAuthority::getAuthority)
.containsOnly("ROLE_USER"); .containsOnly("ROLE_USER");
assertThat(token.getAssertion().getAuthenticationDate()).isEqualTo(START_DATE); assertThat(token.getAssertion().getAuthenticationDate()).isEqualTo(START_DATE);
assertThat(token.getAssertion().getValidFromDate()).isEqualTo(START_DATE); assertThat(token.getAssertion().getValidFromDate()).isEqualTo(START_DATE);
assertThat(token.getAssertion().getValidUntilDate()).isEqualTo(END_DATE); assertThat(token.getAssertion().getValidUntilDate()).isEqualTo(END_DATE);
@ -143,7 +143,7 @@ public class CasAuthenticationTokenMixinTests {
private CasAuthenticationToken createCasAuthenticationToken() { private CasAuthenticationToken createCasAuthenticationToken() {
User principal = new User("admin", "1234", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); User principal = new User("admin", "1234", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
Collection<? extends GrantedAuthority> authorities = Collections Collection<? extends GrantedAuthority> authorities = Collections
.singletonList(new SimpleGrantedAuthority("ROLE_USER")); .singletonList(new SimpleGrantedAuthority("ROLE_USER"));
Assertion assertion = new AssertionImpl(new AttributePrincipalImpl("assertName"), START_DATE, END_DATE, Assertion assertion = new AssertionImpl(new AttributePrincipalImpl("assertName"), START_DATE, END_DATE,
START_DATE, Collections.<String, Object>emptyMap()); START_DATE, Collections.<String, Object>emptyMap());
return new CasAuthenticationToken(KEY, principal, principal.getPassword(), authorities, return new CasAuthenticationToken(KEY, principal, principal.getPassword(), authorities,

View File

@ -39,7 +39,7 @@ public class CasAuthenticationEntryPointTests {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setServiceProperties(new ServiceProperties()); ep.setServiceProperties(new ServiceProperties());
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("loginUrl must be specified"); .withMessage("loginUrl must be specified");
} }
@Test @Test
@ -47,7 +47,7 @@ public class CasAuthenticationEntryPointTests {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login"); ep.setLoginUrl("https://cas/login");
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("serviceProperties must be specified"); .withMessage("serviceProperties must be specified");
} }
@Test @Test
@ -74,7 +74,7 @@ public class CasAuthenticationEntryPointTests {
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());
} }
@Test @Test
@ -92,7 +92,7 @@ public class CasAuthenticationEntryPointTests {
ep.commence(request, response, null); ep.commence(request, response, null);
assertThat("https://cas/login?service=" assertThat("https://cas/login?service="
+ URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", "UTF-8") + "&renew=true") + URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", "UTF-8") + "&renew=true")
.isEqualTo(response.getRedirectedUrl()); .isEqualTo(response.getRedirectedUrl());
} }
} }

View File

@ -132,13 +132,14 @@ public class CasAuthenticationFilterTests {
assertThat(filter.requiresAuthentication(request, response)).isFalse(); assertThat(filter.requiresAuthentication(request, response)).isFalse();
request.setParameter(properties.getArtifactParameter(), "value"); request.setParameter(properties.getArtifactParameter(), "value");
assertThat(filter.requiresAuthentication(request, response)).isTrue(); assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key", "principal", SecurityContextHolder.getContext()
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); .setAuthentication(new AnonymousAuthenticationToken("key", "principal",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
assertThat(filter.requiresAuthentication(request, response)).isTrue(); assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("un", "principal")); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("un", "principal"));
assertThat(filter.requiresAuthentication(request, response)).isTrue(); assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("un", "principal", "ROLE_ANONYMOUS")); .setAuthentication(new TestingAuthenticationToken("un", "principal", "ROLE_ANONYMOUS"));
assertThat(filter.requiresAuthentication(request, response)).isFalse(); assertThat(filter.requiresAuthentication(request, response)).isFalse();
} }
@ -174,7 +175,7 @@ public class CasAuthenticationFilterTests {
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);
verifyNoMoreInteractions(successHandler); verifyNoMoreInteractions(successHandler);
// validate for when the filterProcessUrl matches // validate for when the filterProcessUrl matches
@ -206,7 +207,7 @@ public class CasAuthenticationFilterTests {
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);
// validate for when the filterProcessUrl matches // validate for when the filterProcessUrl matches
filter.setFilterProcessesUrl(request.getServletPath()); filter.setFilterProcessesUrl(request.getServletPath());

View File

@ -54,7 +54,7 @@ public class DefaultServiceAuthenticationDetailsTests {
this.request.setServerPort(8443); this.request.setServerPort(8443);
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);
} }
@AfterEach @AfterEach

View File

@ -74,8 +74,8 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupRoleAttribute", "cn"); assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupRoleAttribute", "cn");
assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupSearchBase", ""); assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupSearchBase", "");
assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupSearchFilter", "(uniqueMember={0})"); assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupSearchFilter", "(uniqueMember={0})");
assertThat(authoritiesPopulator).extracting("searchControls").hasFieldOrPropertyWithValue("searchScope", assertThat(authoritiesPopulator).extracting("searchControls")
SearchControls.ONELEVEL_SCOPE); .hasFieldOrPropertyWithValue("searchScope", SearchControls.ONELEVEL_SCOPE);
assertThat(ReflectionTestUtils.getField(getAuthoritiesMapper(provider), "prefix")).isEqualTo("ROLE_"); assertThat(ReflectionTestUtils.getField(getAuthoritiesMapper(provider), "prefix")).isEqualTo("ROLE_");
} }
@ -85,7 +85,7 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
LdapAuthenticationProvider provider = ldapProvider(); LdapAuthenticationProvider provider = ldapProvider();
assertThat(ReflectionTestUtils.getField(getAuthoritiesPopulator(provider), "groupRoleAttribute")) assertThat(ReflectionTestUtils.getField(getAuthoritiesPopulator(provider), "groupRoleAttribute"))
.isEqualTo("group"); .isEqualTo("group");
} }
@Test @Test
@ -94,7 +94,7 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
LdapAuthenticationProvider provider = ldapProvider(); LdapAuthenticationProvider provider = ldapProvider();
assertThat(ReflectionTestUtils.getField(getAuthoritiesPopulator(provider), "groupSearchFilter")) assertThat(ReflectionTestUtils.getField(getAuthoritiesPopulator(provider), "groupSearchFilter"))
.isEqualTo("ou=groupName"); .isEqualTo("ou=groupName");
} }
@Test @Test
@ -103,7 +103,8 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
LdapAuthenticationProvider provider = ldapProvider(); LdapAuthenticationProvider provider = ldapProvider();
assertThat(ReflectionTestUtils.getField(getAuthoritiesPopulator(provider), "searchControls")) assertThat(ReflectionTestUtils.getField(getAuthoritiesPopulator(provider), "searchControls"))
.extracting("searchScope").isEqualTo(SearchControls.SUBTREE_SCOPE); .extracting("searchScope")
.isEqualTo(SearchControls.SUBTREE_SCOPE);
} }
@Test @Test
@ -119,8 +120,8 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
this.spring.register(BindAuthenticationConfig.class).autowire(); this.spring.register(BindAuthenticationConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
.andExpect(authenticated().withUsername("bob") .andExpect(authenticated().withUsername("bob")
.withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS")))); .withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS"))));
} }
// SEC-2472 // SEC-2472
@ -129,13 +130,14 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
this.spring.register(PasswordEncoderConfig.class).autowire(); this.spring.register(PasswordEncoderConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bcrypt").password("password")) this.mockMvc.perform(formLogin().user("bcrypt").password("password"))
.andExpect(authenticated().withUsername("bcrypt") .andExpect(authenticated().withUsername("bcrypt")
.withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS")))); .withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS"))));
} }
private LdapAuthenticationProvider ldapProvider() { private LdapAuthenticationProvider ldapProvider() {
return ((List<LdapAuthenticationProvider>) ReflectionTestUtils.getField(this.authenticationManager, return ((List<LdapAuthenticationProvider>) ReflectionTestUtils.getField(this.authenticationManager,
"providers")).get(0); "providers"))
.get(0);
} }
private LdapAuthoritiesPopulator getAuthoritiesPopulator(LdapAuthenticationProvider provider) { private LdapAuthoritiesPopulator getAuthoritiesPopulator(LdapAuthenticationProvider provider) {

View File

@ -51,7 +51,7 @@ public class LdapAuthenticationProviderConfigurerTests {
this.spring.register(MultiLdapAuthenticationProvidersConfig.class).autowire(); this.spring.register(MultiLdapAuthenticationProvidersConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
.andExpect(authenticated().withUsername("bob")); .andExpect(authenticated().withUsername("bob"));
} }
@Test @Test

View File

@ -122,7 +122,7 @@ public class JwtITests {
@Test @Test
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()));
// @formatter:off // @formatter:off
@ -137,8 +137,11 @@ public class JwtITests {
} }
private Jwt jwt() { private Jwt jwt() {
return TestJwts.jwt().claim(IdTokenClaimNames.ISS, "https://issuer.example.com") return TestJwts.jwt()
.claim(IdTokenClaimNames.SUB, "rob").claim(IdTokenClaimNames.AUD, Arrays.asList("client-id")).build(); .claim(IdTokenClaimNames.ISS, "https://issuer.example.com")
.claim(IdTokenClaimNames.SUB, "rob")
.claim(IdTokenClaimNames.AUD, Arrays.asList("client-id"))
.build();
} }
private RSocketRequester.Builder requester() { private RSocketRequester.Builder requester() {
@ -169,7 +172,7 @@ public class JwtITests {
@Bean @Bean
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) { PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
rsocket.authorizePayload((authorize) -> authorize.anyRequest().authenticated().anyExchange().permitAll()) rsocket.authorizePayload((authorize) -> authorize.anyRequest().authenticated().anyExchange().permitAll())
.jwt(Customizer.withDefaults()); .jwt(Customizer.withDefaults());
return rsocket.build(); return rsocket.build();
} }

View File

@ -195,7 +195,7 @@ public class RSocketMessageHandlerITests {
String data = "a"; String data = "a";
assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy( assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(
() -> this.requester.route("secure.hello").data(data).retrieveFlux(String.class).collectList().block()) () -> this.requester.route("secure.hello").data(data).retrieveFlux(String.class).collectList().block())
.withMessageContaining("Access Denied"); .withMessageContaining("Access Denied");
assertThat(this.controller.payloads).isEmpty(); assertThat(this.controller.payloads).isEmpty();
} }

View File

@ -117,7 +117,7 @@ public class SimpleAuthenticationITests {
@Test @Test
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");
// @formatter:off // @formatter:off
this.requester = RSocketRequester.builder() this.requester = RSocketRequester.builder()
@ -161,7 +161,7 @@ public class SimpleAuthenticationITests {
@Bean @Bean
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) { PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
rsocket.authorizePayload((authorize) -> authorize.anyRequest().authenticated().anyExchange().permitAll()) rsocket.authorizePayload((authorize) -> authorize.anyRequest().authenticated().anyExchange().permitAll())
.simpleAuthentication(Customizer.withDefaults()); .simpleAuthentication(Customizer.withDefaults());
return rsocket.build(); return rsocket.build();
} }

View File

@ -47,7 +47,7 @@ public class EmbeddedLdapServerContextSourceFactoryBeanITests {
this.spring.register(FromEmbeddedLdapServerConfig.class).autowire(); this.spring.register(FromEmbeddedLdapServerConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
.andExpect(authenticated().withUsername("bob")); .andExpect(authenticated().withUsername("bob"));
} }
@Test @Test
@ -55,7 +55,7 @@ public class EmbeddedLdapServerContextSourceFactoryBeanITests {
this.spring.register(PortZeroConfig.class).autowire(); this.spring.register(PortZeroConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
.andExpect(authenticated().withUsername("bob")); .andExpect(authenticated().withUsername("bob"));
} }
@Test @Test
@ -70,15 +70,15 @@ public class EmbeddedLdapServerContextSourceFactoryBeanITests {
this.spring.register(CustomManagerDnConfig.class).autowire(); this.spring.register(CustomManagerDnConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
.andExpect(authenticated().withUsername("bob")); .andExpect(authenticated().withUsername("bob"));
} }
@Test @Test
public void contextSourceFactoryBeanWhenManagerDnAndNoPasswordThenException() { public void contextSourceFactoryBeanWhenManagerDnAndNoPasswordThenException() {
assertThatExceptionOfType(UnsatisfiedDependencyException.class) assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(() -> this.spring.register(CustomManagerDnNoPasswordConfig.class).autowire()) .isThrownBy(() -> this.spring.register(CustomManagerDnNoPasswordConfig.class).autowire())
.withRootCauseInstanceOf(IllegalStateException.class) .withRootCauseInstanceOf(IllegalStateException.class)
.withMessageContaining("managerPassword is required if managerDn is supplied"); .withMessageContaining("managerPassword is required if managerDn is supplied");
} }
@EnableWebSecurity @EnableWebSecurity
@ -104,7 +104,7 @@ public class EmbeddedLdapServerContextSourceFactoryBeanITests {
@Bean @Bean
EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() { EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
EmbeddedLdapServerContextSourceFactoryBean factoryBean = EmbeddedLdapServerContextSourceFactoryBean EmbeddedLdapServerContextSourceFactoryBean factoryBean = EmbeddedLdapServerContextSourceFactoryBean
.fromEmbeddedLdapServer(); .fromEmbeddedLdapServer();
factoryBean.setPort(0); factoryBean.setPort(0);
return factoryBean; return factoryBean;
} }
@ -124,7 +124,7 @@ public class EmbeddedLdapServerContextSourceFactoryBeanITests {
@Bean @Bean
EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() { EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
EmbeddedLdapServerContextSourceFactoryBean factoryBean = EmbeddedLdapServerContextSourceFactoryBean EmbeddedLdapServerContextSourceFactoryBean factoryBean = EmbeddedLdapServerContextSourceFactoryBean
.fromEmbeddedLdapServer(); .fromEmbeddedLdapServer();
factoryBean.setLdif("classpath*:test-server2.xldif"); factoryBean.setLdif("classpath*:test-server2.xldif");
factoryBean.setRoot("dc=monkeymachine,dc=co,dc=uk"); factoryBean.setRoot("dc=monkeymachine,dc=co,dc=uk");
return factoryBean; return factoryBean;
@ -145,7 +145,7 @@ public class EmbeddedLdapServerContextSourceFactoryBeanITests {
@Bean @Bean
EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() { EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
EmbeddedLdapServerContextSourceFactoryBean factoryBean = EmbeddedLdapServerContextSourceFactoryBean EmbeddedLdapServerContextSourceFactoryBean factoryBean = EmbeddedLdapServerContextSourceFactoryBean
.fromEmbeddedLdapServer(); .fromEmbeddedLdapServer();
factoryBean.setManagerDn("uid=admin,ou=system"); factoryBean.setManagerDn("uid=admin,ou=system");
factoryBean.setManagerPassword("secret"); factoryBean.setManagerPassword("secret");
return factoryBean; return factoryBean;
@ -167,7 +167,7 @@ public class EmbeddedLdapServerContextSourceFactoryBeanITests {
@Bean @Bean
EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() { EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
EmbeddedLdapServerContextSourceFactoryBean factoryBean = EmbeddedLdapServerContextSourceFactoryBean EmbeddedLdapServerContextSourceFactoryBean factoryBean = EmbeddedLdapServerContextSourceFactoryBean
.fromEmbeddedLdapServer(); .fromEmbeddedLdapServer();
factoryBean.setManagerDn("uid=admin,ou=system"); factoryBean.setManagerDn("uid=admin,ou=system");
return factoryBean; return factoryBean;
} }

View File

@ -65,7 +65,7 @@ public class LdapBindAuthenticationManagerFactoryITests {
this.spring.register(FromContextSourceConfig.class).autowire(); this.spring.register(FromContextSourceConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
.andExpect(authenticated().withUsername("bob")); .andExpect(authenticated().withUsername("bob"));
} }
@Test @Test
@ -80,19 +80,21 @@ public class LdapBindAuthenticationManagerFactoryITests {
this.spring.register(CustomAuthoritiesPopulatorConfig.class).autowire(); this.spring.register(CustomAuthoritiesPopulatorConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")).andExpect( this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
authenticated().withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_EXTRA")))); .andExpect(
authenticated().withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_EXTRA"))));
} }
@Test @Test
public void authenticationManagerFactoryWhenCustomAuthoritiesMapperThenUsed() throws Exception { public void authenticationManagerFactoryWhenCustomAuthoritiesMapperThenUsed() throws Exception {
CustomAuthoritiesMapperConfig.AUTHORITIES_MAPPER = ((authorities) -> AuthorityUtils CustomAuthoritiesMapperConfig.AUTHORITIES_MAPPER = ((authorities) -> AuthorityUtils
.createAuthorityList("ROLE_CUSTOM")); .createAuthorityList("ROLE_CUSTOM"));
this.spring.register(CustomAuthoritiesMapperConfig.class).autowire(); this.spring.register(CustomAuthoritiesMapperConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")).andExpect( this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
authenticated().withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_CUSTOM")))); .andExpect(
authenticated().withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_CUSTOM"))));
} }
@Test @Test
@ -112,7 +114,7 @@ public class LdapBindAuthenticationManagerFactoryITests {
this.spring.register(CustomUserDetailsContextMapperConfig.class).autowire(); this.spring.register(CustomUserDetailsContextMapperConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
.andExpect(authenticated().withUsername("other")); .andExpect(authenticated().withUsername("other"));
} }
@Test @Test
@ -120,7 +122,7 @@ public class LdapBindAuthenticationManagerFactoryITests {
this.spring.register(CustomUserDnPatternsConfig.class).autowire(); this.spring.register(CustomUserDnPatternsConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
.andExpect(authenticated().withUsername("bob")); .andExpect(authenticated().withUsername("bob"));
} }
@Test @Test
@ -128,7 +130,7 @@ public class LdapBindAuthenticationManagerFactoryITests {
this.spring.register(CustomUserSearchConfig.class).autowire(); this.spring.register(CustomUserSearchConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) this.mockMvc.perform(formLogin().user("bob").password("bobspassword"))
.andExpect(authenticated().withUsername("bob")); .andExpect(authenticated().withUsername("bob"));
} }
@EnableWebSecurity @EnableWebSecurity

View File

@ -49,7 +49,7 @@ public class LdapPasswordComparisonAuthenticationManagerFactoryITests {
this.spring.register(CustomPasswordEncoderConfig.class).autowire(); this.spring.register(CustomPasswordEncoderConfig.class).autowire();
this.mockMvc.perform(formLogin().user("bcrypt").password("password")) this.mockMvc.perform(formLogin().user("bcrypt").password("password"))
.andExpect(authenticated().withUsername("bcrypt")); .andExpect(authenticated().withUsername("bcrypt"));
} }
@Test @Test

View File

@ -56,7 +56,7 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword"));
UserDetails ben = (UserDetails) auth.getPrincipal(); UserDetails ben = (UserDetails) auth.getPrincipal();
assertThat(ben.getAuthorities()).hasSize(3); assertThat(ben.getAuthorities()).hasSize(3);
} }
@ -71,7 +71,7 @@ public class LdapProviderBeanDefinitionParserTests {
ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class); ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class);
assertThat(providerManager.getProviders()).hasSize(2); assertThat(providerManager.getProviders()).hasSize(2);
assertThat(providerManager.getProviders()).extracting("authoritiesPopulator.groupSearchFilter") assertThat(providerManager.getProviders()).extracting("authoritiesPopulator.groupSearchFilter")
.containsExactly("member={0}", "uniqueMember={0}"); .containsExactly("member={0}", "uniqueMember={0}");
} }
@Test @Test
@ -89,7 +89,7 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "benspassword"));
assertThat(auth).isNotNull(); assertThat(auth).isNotNull();
} }
@ -105,7 +105,7 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "ben")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("ben", "ben"));
assertThat(auth).isNotNull(); assertThat(auth).isNotNull();
} }
@ -122,7 +122,7 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bcrypt", "password")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("bcrypt", "password"));
assertThat(auth).isNotNull(); assertThat(auth).isNotNull();
} }
@ -137,8 +137,8 @@ public class LdapProviderBeanDefinitionParserTests {
ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class); ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class);
assertThat(providerManager.getProviders()).hasSize(1); assertThat(providerManager.getProviders()).hasSize(1);
assertThat(providerManager.getProviders()).extracting("userDetailsContextMapper").allSatisfy( assertThat(providerManager.getProviders()).extracting("userDetailsContextMapper")
(contextMapper) -> assertThat(contextMapper).isInstanceOf(InetOrgPersonContextMapper.class)); .allSatisfy((contextMapper) -> assertThat(contextMapper).isInstanceOf(InetOrgPersonContextMapper.class));
} }
@Test @Test
@ -155,10 +155,10 @@ public class LdapProviderBeanDefinitionParserTests {
AuthenticationProvider authenticationProvider = providerManager.getProviders().get(0); AuthenticationProvider authenticationProvider = providerManager.getProviders().get(0);
assertThat(authenticationProvider).extracting("authenticator.userDnFormat") assertThat(authenticationProvider).extracting("authenticator.userDnFormat")
.satisfies((messageFormats) -> assertThat(messageFormats) .satisfies((messageFormats) -> assertThat(messageFormats)
.isEqualTo(new MessageFormat[] { new MessageFormat("uid={0},ou=people") })); .isEqualTo(new MessageFormat[] { new MessageFormat("uid={0},ou=people") }));
assertThat(authenticationProvider).extracting("authoritiesPopulator.groupSearchFilter") assertThat(authenticationProvider).extracting("authoritiesPopulator.groupSearchFilter")
.satisfies((searchFilter) -> assertThat(searchFilter).isEqualTo("member={0}")); .satisfies((searchFilter) -> assertThat(searchFilter).isEqualTo("member={0}"));
} }
} }

View File

@ -52,7 +52,7 @@ public class LdapServerBeanDefinitionParserTests {
this.appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>"); this.appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>");
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx
.getBean(BeanIds.CONTEXT_SOURCE); .getBean(BeanIds.CONTEXT_SOURCE);
// Check data is loaded // Check data is loaded
LdapTemplate template = new LdapTemplate(contextSource); LdapTemplate template = new LdapTemplate(contextSource);
@ -71,7 +71,7 @@ public class LdapServerBeanDefinitionParserTests {
this.appCtx.getBean(BeanIds.CONTEXT_SOURCE); this.appCtx.getBean(BeanIds.CONTEXT_SOURCE);
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx
.getBean("blah"); .getBean("blah");
// Check data is loaded as before // Check data is loaded as before
LdapTemplate template = new LdapTemplate(contextSource); LdapTemplate template = new LdapTemplate(contextSource);
@ -83,7 +83,7 @@ public class LdapServerBeanDefinitionParserTests {
this.appCtx = new InMemoryXmlApplicationContext( this.appCtx = new InMemoryXmlApplicationContext(
"<ldap-server ldif='classpath*:test-server2.xldif' root='dc=monkeymachine,dc=co,dc=uk' port='0'/>"); "<ldap-server ldif='classpath*:test-server2.xldif' root='dc=monkeymachine,dc=co,dc=uk' port='0'/>");
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx
.getBean(BeanIds.CONTEXT_SOURCE); .getBean(BeanIds.CONTEXT_SOURCE);
LdapTemplate template = new LdapTemplate(contextSource); LdapTemplate template = new LdapTemplate(contextSource);
template.lookup("uid=pg,ou=gorillas"); template.lookup("uid=pg,ou=gorillas");

View File

@ -58,17 +58,17 @@ public class LdapUserServiceBeanDefinitionParserTests {
@Test @Test
public void beanClassNamesAreCorrect() { public void beanClassNamesAreCorrect() {
assertThat(FilterBasedLdapUserSearch.class.getName()) assertThat(FilterBasedLdapUserSearch.class.getName())
.isEqualTo(LdapUserServiceBeanDefinitionParser.LDAP_SEARCH_CLASS); .isEqualTo(LdapUserServiceBeanDefinitionParser.LDAP_SEARCH_CLASS);
assertThat(PersonContextMapper.class.getName()) assertThat(PersonContextMapper.class.getName())
.isEqualTo(LdapUserServiceBeanDefinitionParser.PERSON_MAPPER_CLASS); .isEqualTo(LdapUserServiceBeanDefinitionParser.PERSON_MAPPER_CLASS);
assertThat(InetOrgPersonContextMapper.class.getName()) assertThat(InetOrgPersonContextMapper.class.getName())
.isEqualTo(LdapUserServiceBeanDefinitionParser.INET_ORG_PERSON_MAPPER_CLASS); .isEqualTo(LdapUserServiceBeanDefinitionParser.INET_ORG_PERSON_MAPPER_CLASS);
assertThat(LdapUserDetailsMapper.class.getName()) assertThat(LdapUserDetailsMapper.class.getName())
.isEqualTo(LdapUserServiceBeanDefinitionParser.LDAP_USER_MAPPER_CLASS); .isEqualTo(LdapUserServiceBeanDefinitionParser.LDAP_USER_MAPPER_CLASS);
assertThat(DefaultLdapAuthoritiesPopulator.class.getName()) assertThat(DefaultLdapAuthoritiesPopulator.class.getName())
.isEqualTo(LdapUserServiceBeanDefinitionParser.LDAP_AUTHORITIES_POPULATOR_CLASS); .isEqualTo(LdapUserServiceBeanDefinitionParser.LDAP_AUTHORITIES_POPULATOR_CLASS);
assertThat(new LdapUserServiceBeanDefinitionParser().getBeanClassName(mock(Element.class))) assertThat(new LdapUserServiceBeanDefinitionParser().getBeanClassName(mock(Element.class)))
.isEqualTo(LdapUserDetailsService.class.getName()); .isEqualTo(LdapUserDetailsService.class.getName());
} }
@Test @Test

View File

@ -85,17 +85,19 @@ public final class SecurityNamespaceHandler implements NamespaceHandler {
String version = pkg.getImplementationVersion(); String version = pkg.getImplementationVersion();
this.logger.info("Spring Security 'config' module version is " + version); this.logger.info("Spring Security 'config' module version is " + version);
if (version.compareTo(coreVersion) != 0) { if (version.compareTo(coreVersion) != 0) {
this.logger.error( this.logger
"You are running with different versions of the Spring Security 'core' and 'config' modules"); .error("You are running with different versions of the Spring Security 'core' and 'config' modules");
} }
} }
@Override @Override
public BeanDefinition parse(Element element, ParserContext pc) { public BeanDefinition parse(Element element, ParserContext pc) {
if (!namespaceMatchesVersion(element)) { if (!namespaceMatchesVersion(element)) {
pc.getReaderContext().fatal("You cannot use a spring-security-2.0.xsd or spring-security-3.0.xsd or " pc.getReaderContext()
+ "spring-security-3.1.xsd schema or spring-security-3.2.xsd schema or spring-security-4.0.xsd schema " .fatal("You cannot use a spring-security-2.0.xsd or spring-security-3.0.xsd or "
+ "with Spring Security 5.8. Please update your schema declarations to the 5.8 schema.", element); + "spring-security-3.1.xsd schema or spring-security-3.2.xsd schema or spring-security-4.0.xsd schema "
+ "with Spring Security 5.8. Please update your schema declarations to the 5.8 schema.",
element);
} }
String name = pc.getDelegate().getLocalName(element); String name = pc.getDelegate().getLocalName(element);
BeanDefinitionParser parser = this.parsers.get(name); BeanDefinitionParser parser = this.parsers.get(name);
@ -140,8 +142,9 @@ public final class SecurityNamespaceHandler implements NamespaceHandler {
} }
private void reportUnsupportedNodeType(String name, ParserContext pc, Node node) { private void reportUnsupportedNodeType(String name, ParserContext pc, Node node) {
pc.getReaderContext().fatal("Security namespace does not support decoration of " pc.getReaderContext()
+ ((node instanceof Element) ? "element" : "attribute") + " [" + name + "]", node); .fatal("Security namespace does not support decoration of "
+ ((node instanceof Element) ? "element" : "attribute") + " [" + name + "]", node);
} }
private void reportMissingWebClasses(String nodeName, ParserContext pc, Node node) { private void reportMissingWebClasses(String nodeName, ParserContext pc, Node node) {

View File

@ -176,7 +176,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
private <C extends SecurityConfigurer<O, B>> void add(C configurer) { private <C extends SecurityConfigurer<O, B>> void add(C configurer) {
Assert.notNull(configurer, "configurer cannot be null"); Assert.notNull(configurer, "configurer cannot be null");
Class<? extends SecurityConfigurer<O, B>> clazz = (Class<? extends SecurityConfigurer<O, B>>) configurer Class<? extends SecurityConfigurer<O, B>> clazz = (Class<? extends SecurityConfigurer<O, B>>) configurer
.getClass(); .getClass();
synchronized (this.configurers) { synchronized (this.configurers) {
if (this.buildState.isConfigured()) { if (this.buildState.isConfigured()) {
throw new IllegalStateException("Cannot apply " + configurer + " to already built object"); throw new IllegalStateException("Cannot apply " + configurer + " to already built object");

View File

@ -184,8 +184,9 @@ public class AuthenticationConfiguration {
return Collections.emptyList(); return Collections.emptyList();
} }
for (String beanName : beanNamesForType) { for (String beanName : beanNamesForType) {
if (((ConfigurableApplicationContext) this.applicationContext).getBeanFactory().getBeanDefinition(beanName) if (((ConfigurableApplicationContext) this.applicationContext).getBeanFactory()
.isPrimary()) { .getBeanDefinition(beanName)
.isPrimary()) {
list.add(beanName); list.add(beanName);
} }
} }
@ -218,7 +219,7 @@ public class AuthenticationConfiguration {
@Override @Override
public void init(AuthenticationManagerBuilder auth) { public void init(AuthenticationManagerBuilder auth) {
Map<String, Object> beansWithAnnotation = this.context Map<String, Object> beansWithAnnotation = this.context
.getBeansWithAnnotation(EnableGlobalAuthentication.class); .getBeansWithAnnotation(EnableGlobalAuthentication.class);
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format("Eagerly initializing %s", beansWithAnnotation)); logger.trace(LogMessage.format("Eagerly initializing %s", beansWithAnnotation));
} }

View File

@ -98,7 +98,6 @@ import org.springframework.security.config.annotation.web.servlet.configuration.
* @see EnableWebMvcSecurity * @see EnableWebMvcSecurity
* @see EnableWebSecurity * @see EnableWebSecurity
* @see EnableGlobalMethodSecurity * @see EnableGlobalMethodSecurity
*
* @author Rob Winch * @author Rob Winch
* *
*/ */

View File

@ -67,7 +67,7 @@ class InitializeAuthenticationProviderBeanManagerConfigurer extends GlobalAuthen
*/ */
private <T> T getBeanOrNull(Class<T> type) { private <T> T getBeanOrNull(Class<T> type) {
String[] beanNames = InitializeAuthenticationProviderBeanManagerConfigurer.this.context String[] beanNames = InitializeAuthenticationProviderBeanManagerConfigurer.this.context
.getBeanNamesForType(type); .getBeanNamesForType(type);
if (beanNames.length != 1) { if (beanNames.length != 1) {
return null; return null;
} }

View File

@ -387,7 +387,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
*/ */
public PasswordCompareConfigurer passwordCompare() { public PasswordCompareConfigurer passwordCompare() {
return new PasswordCompareConfigurer().passwordAttribute("password") return new PasswordCompareConfigurer().passwordAttribute("password")
.passwordEncoder(NoOpPasswordEncoder.getInstance()); .passwordEncoder(NoOpPasswordEncoder.getInstance());
} }
/** /**

View File

@ -33,6 +33,7 @@ import org.springframework.security.access.prepost.PreFilter;
/** /**
* Enables Spring Security Method Security. * Enables Spring Security Method Security.
*
* @author Evgeniy Cheban * @author Evgeniy Cheban
* @author Josh Cummings * @author Josh Cummings
* @since 5.6 * @since 5.6

View File

@ -29,7 +29,6 @@ import org.springframework.core.Ordered;
import org.springframework.security.authorization.ReactiveAuthorizationManager; import org.springframework.security.authorization.ReactiveAuthorizationManager;
/** /**
*
* @author Rob Winch * @author Rob Winch
* @since 5.0 * @since 5.0
*/ */

View File

@ -108,7 +108,7 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
}; };
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
private DefaultMethodSecurityExpressionHandler defaultMethodExpressionHandler = new DefaultMethodSecurityExpressionHandler(); private DefaultMethodSecurityExpressionHandler defaultMethodExpressionHandler = new DefaultMethodSecurityExpressionHandler();
@ -320,7 +320,7 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
protected AuthenticationManager authenticationManager() throws Exception { protected AuthenticationManager authenticationManager() throws Exception {
if (this.authenticationManager == null) { if (this.authenticationManager == null) {
DefaultAuthenticationEventPublisher eventPublisher = this.objectPostProcessor DefaultAuthenticationEventPublisher eventPublisher = this.objectPostProcessor
.postProcess(new DefaultAuthenticationEventPublisher()); .postProcess(new DefaultAuthenticationEventPublisher());
this.auth = new AuthenticationManagerBuilder(this.objectPostProcessor); this.auth = new AuthenticationManagerBuilder(this.objectPostProcessor);
this.auth.authenticationEventPublisher(eventPublisher); this.auth.authenticationEventPublisher(eventPublisher);
configure(this.auth); configure(this.auth);
@ -375,7 +375,7 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
if (isJsr250Enabled) { if (isJsr250Enabled) {
GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull(GrantedAuthorityDefaults.class); GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull(GrantedAuthorityDefaults.class);
Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource = this.context Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource = this.context
.getBean(Jsr250MethodSecurityMetadataSource.class); .getBean(Jsr250MethodSecurityMetadataSource.class);
if (grantedAuthorityDefaults != null) { if (grantedAuthorityDefaults != null) {
jsr250MethodSecurityMetadataSource.setDefaultRolePrefix(grantedAuthorityDefaults.getRolePrefix()); jsr250MethodSecurityMetadataSource.setDefaultRolePrefix(grantedAuthorityDefaults.getRolePrefix());
} }
@ -403,7 +403,7 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
@Override @Override
public final void setImportMetadata(AnnotationMetadata importMetadata) { public final void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> annotationAttributes = importMetadata Map<String, Object> annotationAttributes = importMetadata
.getAnnotationAttributes(EnableGlobalMethodSecurity.class.getName()); .getAnnotationAttributes(EnableGlobalMethodSecurity.class.getName());
this.enableMethodSecurity = AnnotationAttributes.fromMap(annotationAttributes); this.enableMethodSecurity = AnnotationAttributes.fromMap(annotationAttributes);
} }

View File

@ -51,7 +51,7 @@ final class GlobalMethodSecuritySelector implements ImportSelector {
Class<?> importingClass = ClassUtils.resolveClassName(importingClassMetadata.getClassName(), Class<?> importingClass = ClassUtils.resolveClassName(importingClassMetadata.getClassName(),
ClassUtils.getDefaultClassLoader()); ClassUtils.getDefaultClassLoader());
boolean skipMethodSecurityConfiguration = GlobalMethodSecurityConfiguration.class boolean skipMethodSecurityConfiguration = GlobalMethodSecurityConfiguration.class
.isAssignableFrom(importingClass); .isAssignableFrom(importingClass);
AdviceMode mode = attributes.getEnum("mode"); AdviceMode mode = attributes.getEnum("mode");
boolean isProxy = AdviceMode.PROXY == mode; boolean isProxy = AdviceMode.PROXY == mode;
String autoProxyClassName = isProxy ? AutoProxyRegistrar.class.getName() String autoProxyClassName = isProxy ? AutoProxyRegistrar.class.getName()

View File

@ -44,13 +44,13 @@ final class Jsr250MethodSecurityConfiguration {
private final Jsr250AuthorizationManager jsr250AuthorizationManager = new Jsr250AuthorizationManager(); private final Jsr250AuthorizationManager jsr250AuthorizationManager = new Jsr250AuthorizationManager();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
@Bean @Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
MethodInterceptor jsr250AuthorizationMethodInterceptor() { MethodInterceptor jsr250AuthorizationMethodInterceptor() {
AuthorizationManagerBeforeMethodInterceptor interceptor = AuthorizationManagerBeforeMethodInterceptor AuthorizationManagerBeforeMethodInterceptor interceptor = AuthorizationManagerBeforeMethodInterceptor
.jsr250(this.jsr250AuthorizationManager); .jsr250(this.jsr250AuthorizationManager);
interceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); interceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
return interceptor; return interceptor;
} }

View File

@ -45,13 +45,13 @@ class MethodSecurityMetadataSourceAdvisorRegistrar implements ImportBeanDefiniti
@Override @Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
BeanDefinitionBuilder advisor = BeanDefinitionBuilder BeanDefinitionBuilder advisor = BeanDefinitionBuilder
.rootBeanDefinition(MethodSecurityMetadataSourceAdvisor.class); .rootBeanDefinition(MethodSecurityMetadataSourceAdvisor.class);
advisor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); advisor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
advisor.addConstructorArgValue("methodSecurityInterceptor"); advisor.addConstructorArgValue("methodSecurityInterceptor");
advisor.addConstructorArgReference("methodSecurityMetadataSource"); advisor.addConstructorArgReference("methodSecurityMetadataSource");
advisor.addConstructorArgValue("methodSecurityMetadataSource"); advisor.addConstructorArgValue("methodSecurityMetadataSource");
MultiValueMap<String, Object> attributes = importingClassMetadata MultiValueMap<String, Object> attributes = importingClassMetadata
.getAllAnnotationAttributes(EnableGlobalMethodSecurity.class.getName()); .getAllAnnotationAttributes(EnableGlobalMethodSecurity.class.getName());
Integer order = (Integer) attributes.getFirst("order"); Integer order = (Integer) attributes.getFirst("order");
if (order != null) { if (order != null) {
advisor.addPropertyValue("order", order); advisor.addPropertyValue("order", order);

View File

@ -68,10 +68,10 @@ final class PrePostMethodSecurityConfiguration {
PrePostMethodSecurityConfiguration(ApplicationContext context) { PrePostMethodSecurityConfiguration(ApplicationContext context) {
this.preAuthorizeAuthorizationManager.setExpressionHandler(this.expressionHandler); this.preAuthorizeAuthorizationManager.setExpressionHandler(this.expressionHandler);
this.preAuthorizeAuthorizationMethodInterceptor = AuthorizationManagerBeforeMethodInterceptor this.preAuthorizeAuthorizationMethodInterceptor = AuthorizationManagerBeforeMethodInterceptor
.preAuthorize(this.preAuthorizeAuthorizationManager); .preAuthorize(this.preAuthorizeAuthorizationManager);
this.postAuthorizeAuthorizationManager.setExpressionHandler(this.expressionHandler); this.postAuthorizeAuthorizationManager.setExpressionHandler(this.expressionHandler);
this.postAuthorizeAuthorizaitonMethodInterceptor = AuthorizationManagerAfterMethodInterceptor this.postAuthorizeAuthorizaitonMethodInterceptor = AuthorizationManagerAfterMethodInterceptor
.postAuthorize(this.postAuthorizeAuthorizationManager); .postAuthorize(this.postAuthorizeAuthorizationManager);
this.preFilterAuthorizationMethodInterceptor.setExpressionHandler(this.expressionHandler); this.preFilterAuthorizationMethodInterceptor.setExpressionHandler(this.expressionHandler);
this.postFilterAuthorizationMethodInterceptor.setExpressionHandler(this.expressionHandler); this.postFilterAuthorizationMethodInterceptor.setExpressionHandler(this.expressionHandler);
this.expressionHandler.setApplicationContext(context); this.expressionHandler.setApplicationContext(context);

View File

@ -91,7 +91,7 @@ class ReactiveMethodSecurityConfiguration implements ImportAware {
@Override @Override
public void setImportMetadata(AnnotationMetadata importMetadata) { public void setImportMetadata(AnnotationMetadata importMetadata) {
this.advisorOrder = (int) importMetadata.getAnnotationAttributes(EnableReactiveMethodSecurity.class.getName()) this.advisorOrder = (int) importMetadata.getAnnotationAttributes(EnableReactiveMethodSecurity.class.getName())
.get("order"); .get("order");
} }
@Autowired(required = false) @Autowired(required = false)

View File

@ -42,7 +42,8 @@ class ReactiveMethodSecuritySelector implements ImportSelector {
return new String[0]; return new String[0];
} }
EnableReactiveMethodSecurity annotation = importMetadata.getAnnotations() EnableReactiveMethodSecurity annotation = importMetadata.getAnnotations()
.get(EnableReactiveMethodSecurity.class).synthesize(); .get(EnableReactiveMethodSecurity.class)
.synthesize();
List<String> imports = new ArrayList<>(Arrays.asList(this.autoProxy.selectImports(importMetadata))); List<String> imports = new ArrayList<>(Arrays.asList(this.autoProxy.selectImports(importMetadata)));
if (annotation.useAuthorizationManager()) { if (annotation.useAuthorizationManager()) {
imports.add(ReactiveAuthorizationManagerMethodSecurityConfiguration.class.getName()); imports.add(ReactiveAuthorizationManagerMethodSecurityConfiguration.class.getName());

View File

@ -41,7 +41,7 @@ import org.springframework.security.core.context.SecurityContextHolderStrategy;
final class SecuredMethodSecurityConfiguration { final class SecuredMethodSecurityConfiguration {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
@Bean @Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Role(BeanDefinition.ROLE_INFRASTRUCTURE)

View File

@ -351,7 +351,7 @@ public class RSocketSecurity {
public class AuthorizePayloadsSpec { public class AuthorizePayloadsSpec {
private PayloadExchangeMatcherReactiveAuthorizationManager.Builder authzBuilder = PayloadExchangeMatcherReactiveAuthorizationManager private PayloadExchangeMatcherReactiveAuthorizationManager.Builder authzBuilder = PayloadExchangeMatcherReactiveAuthorizationManager
.builder(); .builder();
public Access setup() { public Access setup() {
return matcher(PayloadExchangeMatchers.setup()); return matcher(PayloadExchangeMatchers.setup());
@ -427,7 +427,7 @@ public class RSocketSecurity {
public AuthorizePayloadsSpec access( public AuthorizePayloadsSpec access(
ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> authorization) { ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> authorization) {
AuthorizePayloadsSpec.this.authzBuilder AuthorizePayloadsSpec.this.authzBuilder
.add(new PayloadExchangeMatcherEntry<>(this.matcher, authorization)); .add(new PayloadExchangeMatcherEntry<>(this.matcher, authorization));
return AuthorizePayloadsSpec.this; return AuthorizePayloadsSpec.this;
} }

View File

@ -37,7 +37,7 @@ class SecuritySocketAcceptorInterceptorConfiguration {
ObjectProvider<PayloadSocketAcceptorInterceptor> rsocketInterceptor, ObjectProvider<PayloadSocketAcceptorInterceptor> rsocketInterceptor,
ObjectProvider<RSocketSecurity> rsocketSecurity) { ObjectProvider<RSocketSecurity> rsocketSecurity) {
PayloadSocketAcceptorInterceptor delegate = rsocketInterceptor PayloadSocketAcceptorInterceptor delegate = rsocketInterceptor
.getIfAvailable(() -> defaultInterceptor(rsocketSecurity)); .getIfAvailable(() -> defaultInterceptor(rsocketSecurity));
return new SecuritySocketAcceptorInterceptor(delegate); return new SecuritySocketAcceptorInterceptor(delegate);
} }

View File

@ -331,7 +331,7 @@ public abstract class AbstractRequestMatcherRegistry<C> {
private Map<String, ? extends ServletRegistration> mappableServletRegistrations(ServletContext servletContext) { private Map<String, ? extends ServletRegistration> mappableServletRegistrations(ServletContext servletContext) {
Map<String, ServletRegistration> mappable = new LinkedHashMap<>(); Map<String, ServletRegistration> mappable = new LinkedHashMap<>();
for (Map.Entry<String, ? extends ServletRegistration> entry : servletContext.getServletRegistrations() for (Map.Entry<String, ? extends ServletRegistration> entry : servletContext.getServletRegistrations()
.entrySet()) { .entrySet()) {
if (!entry.getValue().getMappings().isEmpty()) { if (!entry.getValue().getMappings().isEmpty()) {
mappable.put(entry.getKey(), entry.getValue()); mappable.put(entry.getKey(), entry.getValue());
} }

View File

@ -1418,7 +1418,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
throws Exception { throws Exception {
ApplicationContext context = getContext(); ApplicationContext context = getContext();
authorizeRequestsCustomizer authorizeRequestsCustomizer
.customize(getOrApply(new ExpressionUrlAuthorizationConfigurer<>(context)).getRegistry()); .customize(getOrApply(new ExpressionUrlAuthorizationConfigurer<>(context)).getRegistry());
return HttpSecurity.this; return HttpSecurity.this;
} }
@ -1647,7 +1647,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
throws Exception { throws Exception {
ApplicationContext context = getContext(); ApplicationContext context = getContext();
authorizeHttpRequestsCustomizer authorizeHttpRequestsCustomizer
.customize(getOrApply(new AuthorizeHttpRequestsConfigurer<>(context)).getRegistry()); .customize(getOrApply(new AuthorizeHttpRequestsConfigurer<>(context)).getRegistry());
return HttpSecurity.this; return HttpSecurity.this;
} }

View File

@ -307,13 +307,13 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter,
SecurityFilterChain securityFilterChain = new DefaultSecurityFilterChain(ignoredRequest); SecurityFilterChain securityFilterChain = new DefaultSecurityFilterChain(ignoredRequest);
securityFilterChains.add(securityFilterChain); securityFilterChains.add(securityFilterChain);
requestMatcherPrivilegeEvaluatorsEntries requestMatcherPrivilegeEvaluatorsEntries
.add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain)); .add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain));
} }
for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : this.securityFilterChainBuilders) { for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : this.securityFilterChainBuilders) {
SecurityFilterChain securityFilterChain = securityFilterChainBuilder.build(); SecurityFilterChain securityFilterChain = securityFilterChainBuilder.build();
securityFilterChains.add(securityFilterChain); securityFilterChains.add(securityFilterChain);
requestMatcherPrivilegeEvaluatorsEntries requestMatcherPrivilegeEvaluatorsEntries
.add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain)); .add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain));
} }
if (this.privilegeEvaluator == null) { if (this.privilegeEvaluator == null) {
this.privilegeEvaluator = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator( this.privilegeEvaluator = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(
@ -354,7 +354,7 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter,
} }
if (filter instanceof AuthorizationFilter) { if (filter instanceof AuthorizationFilter) {
AuthorizationManager<HttpServletRequest> authorizationManager = ((AuthorizationFilter) filter) AuthorizationManager<HttpServletRequest> authorizationManager = ((AuthorizationFilter) filter)
.getAuthorizationManager(); .getAuthorizationManager();
AuthorizationManagerWebInvocationPrivilegeEvaluator evaluator = new AuthorizationManagerWebInvocationPrivilegeEvaluator( AuthorizationManagerWebInvocationPrivilegeEvaluator evaluator = new AuthorizationManagerWebInvocationPrivilegeEvaluator(
authorizationManager); authorizationManager);
evaluator.setServletContext(this.servletContext); evaluator.setServletContext(this.servletContext);
@ -374,7 +374,7 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter,
} }
try { try {
this.defaultWebSecurityExpressionHandler this.defaultWebSecurityExpressionHandler
.setPermissionEvaluator(applicationContext.getBean(PermissionEvaluator.class)); .setPermissionEvaluator(applicationContext.getBean(PermissionEvaluator.class));
} }
catch (NoSuchBeanDefinitionException ex) { catch (NoSuchBeanDefinitionException ex) {
} }

View File

@ -76,7 +76,6 @@ import org.springframework.security.web.SecurityFilterChain;
* </pre> * </pre>
* *
* @see WebSecurityConfigurer * @see WebSecurityConfigurer
*
* @author Rob Winch * @author Rob Winch
* @since 3.2 * @since 3.2
*/ */

View File

@ -65,7 +65,7 @@ class HttpSecurityConfiguration {
private ApplicationContext context; private ApplicationContext context;
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
private ContentNegotiationStrategy contentNegotiationStrategy = new HeaderContentNegotiationStrategy(); private ContentNegotiationStrategy contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
@ -143,7 +143,7 @@ class HttpSecurityConfiguration {
private void applyDefaultConfigurers(HttpSecurity http) throws Exception { private void applyDefaultConfigurers(HttpSecurity http) throws Exception {
ClassLoader classLoader = this.context.getClassLoader(); ClassLoader classLoader = this.context.getClassLoader();
List<AbstractHttpConfigurer> defaultHttpConfigurers = SpringFactoriesLoader List<AbstractHttpConfigurer> defaultHttpConfigurers = SpringFactoriesLoader
.loadFactories(AbstractHttpConfigurer.class, classLoader); .loadFactories(AbstractHttpConfigurer.class, classLoader);
for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) { for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
http.apply(configurer); http.apply(configurer);
} }

View File

@ -48,11 +48,11 @@ final class OAuth2ImportSelector implements ImportSelector {
Set<String> imports = new LinkedHashSet<>(); Set<String> imports = new LinkedHashSet<>();
ClassLoader classLoader = getClass().getClassLoader(); ClassLoader classLoader = getClass().getClassLoader();
boolean oauth2ClientPresent = ClassUtils boolean oauth2ClientPresent = ClassUtils
.isPresent("org.springframework.security.oauth2.client.registration.ClientRegistration", classLoader); .isPresent("org.springframework.security.oauth2.client.registration.ClientRegistration", classLoader);
boolean webfluxPresent = ClassUtils boolean webfluxPresent = ClassUtils
.isPresent("org.springframework.web.reactive.function.client.ExchangeFilterFunction", classLoader); .isPresent("org.springframework.web.reactive.function.client.ExchangeFilterFunction", classLoader);
boolean oauth2ResourceServerPresent = ClassUtils boolean oauth2ResourceServerPresent = ClassUtils
.isPresent("org.springframework.security.oauth2.server.resource.BearerTokenError", classLoader); .isPresent("org.springframework.security.oauth2.server.resource.BearerTokenError", classLoader);
if (oauth2ClientPresent) { if (oauth2ClientPresent) {
imports.add("org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration"); imports.add("org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration");
} }

View File

@ -66,7 +66,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
class SecurityReactorContextConfiguration { class SecurityReactorContextConfiguration {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
@Bean @Bean
SecurityReactorContextSubscriberRegistrar securityReactorContextSubscriberRegistrar() { SecurityReactorContextSubscriberRegistrar securityReactorContextSubscriberRegistrar() {
@ -88,7 +88,7 @@ class SecurityReactorContextConfiguration {
private final Map<Object, Supplier<Object>> CONTEXT_ATTRIBUTE_VALUE_LOADERS = new HashMap<>(); private final Map<Object, Supplier<Object>> CONTEXT_ATTRIBUTE_VALUE_LOADERS = new HashMap<>();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
SecurityReactorContextSubscriberRegistrar() { SecurityReactorContextSubscriberRegistrar() {
this.CONTEXT_ATTRIBUTE_VALUE_LOADERS.put(HttpServletRequest.class, this.CONTEXT_ATTRIBUTE_VALUE_LOADERS.put(HttpServletRequest.class,
@ -101,7 +101,7 @@ class SecurityReactorContextConfiguration {
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
Function<? super Publisher<Object>, ? extends Publisher<Object>> lifter = Operators Function<? super Publisher<Object>, ? extends Publisher<Object>> lifter = Operators
.liftPublisher((pub, sub) -> createSubscriberIfNecessary(sub)); .liftPublisher((pub, sub) -> createSubscriberIfNecessary(sub));
Hooks.onLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY, lifter::apply); Hooks.onLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY, lifter::apply);
} }

View File

@ -39,8 +39,8 @@ import org.springframework.web.servlet.support.RequestDataValueProcessor;
* Used to add a {@link RequestDataValueProcessor} for Spring MVC and Spring Security CSRF * Used to add a {@link RequestDataValueProcessor} for Spring MVC and Spring Security CSRF
* integration. This configuration is added whenever {@link EnableWebMvc} is added by * integration. This configuration is added whenever {@link EnableWebMvc} is added by
* <a href=" * <a href="
* {@docRoot}/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.html">SpringWebMvcImportSelector</a> * {@docRoot}/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.html">SpringWebMvcImportSelector</a> and
* and the DispatcherServlet is present on the classpath. It also adds the * the DispatcherServlet is present on the classpath. It also adds the
* {@link AuthenticationPrincipalArgumentResolver} as a * {@link AuthenticationPrincipalArgumentResolver} as a
* {@link HandlerMethodArgumentResolver}. * {@link HandlerMethodArgumentResolver}.
* *
@ -53,7 +53,7 @@ class WebMvcSecurityConfiguration implements WebMvcConfigurer, ApplicationContex
private BeanResolver beanResolver; private BeanResolver beanResolver;
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -63,7 +63,7 @@ class WebMvcSecurityConfiguration implements WebMvcConfigurer, ApplicationContex
authenticationPrincipalResolver.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); authenticationPrincipalResolver.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
argumentResolvers.add(authenticationPrincipalResolver); argumentResolvers.add(authenticationPrincipalResolver);
argumentResolvers argumentResolvers
.add(new org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver()); .add(new org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver());
CurrentSecurityContextArgumentResolver currentSecurityContextArgumentResolver = new CurrentSecurityContextArgumentResolver(); CurrentSecurityContextArgumentResolver currentSecurityContextArgumentResolver = new CurrentSecurityContextArgumentResolver();
currentSecurityContextArgumentResolver.setBeanResolver(this.beanResolver); currentSecurityContextArgumentResolver.setBeanResolver(this.beanResolver);
currentSecurityContextArgumentResolver.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); currentSecurityContextArgumentResolver.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);

View File

@ -106,8 +106,8 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
"Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one."); "Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.");
if (!hasConfigurers && !hasFilterChain) { if (!hasConfigurers && !hasFilterChain) {
WebSecurityConfigurerAdapter adapter = this.objectObjectPostProcessor WebSecurityConfigurerAdapter adapter = this.objectObjectPostProcessor
.postProcess(new WebSecurityConfigurerAdapter() { .postProcess(new WebSecurityConfigurerAdapter() {
}); });
this.webSecurity.apply(adapter); this.webSecurity.apply(adapter);
} }
for (SecurityFilterChain securityFilterChain : this.securityFilterChains) { for (SecurityFilterChain securityFilterChain : this.securityFilterChains) {
@ -154,7 +154,8 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
this.webSecurity.debug(this.debugEnabled); this.webSecurity.debug(this.debugEnabled);
} }
List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers = new AutowiredWebSecurityConfigurersIgnoreParents( List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers = new AutowiredWebSecurityConfigurersIgnoreParents(
beanFactory).getWebSecurityConfigurers(); beanFactory)
.getWebSecurityConfigurers();
webSecurityConfigurers.sort(AnnotationAwareOrderComparator.INSTANCE); webSecurityConfigurers.sort(AnnotationAwareOrderComparator.INSTANCE);
Integer previousOrder = null; Integer previousOrder = null;
Object previousConfig = null; Object previousConfig = null;
@ -191,7 +192,7 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
@Override @Override
public void setImportMetadata(AnnotationMetadata importMetadata) { public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> enableWebSecurityAttrMap = importMetadata Map<String, Object> enableWebSecurityAttrMap = importMetadata
.getAnnotationAttributes(EnableWebSecurity.class.getName()); .getAnnotationAttributes(EnableWebSecurity.class.getName());
AnnotationAttributes enableWebSecurityAttrs = AnnotationAttributes.fromMap(enableWebSecurityAttrMap); AnnotationAttributes enableWebSecurityAttrs = AnnotationAttributes.fromMap(enableWebSecurityAttrMap);
this.debugEnabled = enableWebSecurityAttrs.getBoolean("debug"); this.debugEnabled = enableWebSecurityAttrs.getBoolean("debug");
if (this.webSecurity != null) { if (this.webSecurity != null) {

View File

@ -230,7 +230,7 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
applyDefaultConfiguration(this.http); applyDefaultConfiguration(this.http);
ClassLoader classLoader = this.context.getClassLoader(); ClassLoader classLoader = this.context.getClassLoader();
List<AbstractHttpConfigurer> defaultHttpConfigurers = SpringFactoriesLoader List<AbstractHttpConfigurer> defaultHttpConfigurers = SpringFactoriesLoader
.loadFactories(AbstractHttpConfigurer.class, classLoader); .loadFactories(AbstractHttpConfigurer.class, classLoader);
for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) { for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
this.http.apply(configurer); this.http.apply(configurer);
} }

View File

@ -285,7 +285,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
this.authFilter.setAuthenticationDetailsSource(this.authenticationDetailsSource); this.authFilter.setAuthenticationDetailsSource(this.authenticationDetailsSource);
} }
SessionAuthenticationStrategy sessionAuthenticationStrategy = http SessionAuthenticationStrategy sessionAuthenticationStrategy = http
.getSharedObject(SessionAuthenticationStrategy.class); .getSharedObject(SessionAuthenticationStrategy.class);
if (sessionAuthenticationStrategy != null) { if (sessionAuthenticationStrategy != null) {
this.authFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy); this.authFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy);
} }
@ -296,7 +296,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
SecurityContextConfigurer securityContextConfigurer = http.getConfigurer(SecurityContextConfigurer.class); SecurityContextConfigurer securityContextConfigurer = http.getConfigurer(SecurityContextConfigurer.class);
if (securityContextConfigurer != null && securityContextConfigurer.isRequireExplicitSave()) { if (securityContextConfigurer != null && securityContextConfigurer.isRequireExplicitSave()) {
SecurityContextRepository securityContextRepository = securityContextConfigurer SecurityContextRepository securityContextRepository = securityContextConfigurer
.getSecurityContextRepository(); .getSecurityContextRepository();
this.authFilter.setSecurityContextRepository(securityContextRepository); this.authFilter.setSecurityContextRepository(securityContextRepository);
} }
this.authFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); this.authFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());

View File

@ -113,7 +113,7 @@ public final class AuthorizeHttpRequestsConfigurer<H extends HttpSecurityBuilder
extends AbstractRequestMatcherRegistry<AuthorizedUrl> { extends AbstractRequestMatcherRegistry<AuthorizedUrl> {
private final RequestMatcherDelegatingAuthorizationManager.Builder managerBuilder = RequestMatcherDelegatingAuthorizationManager private final RequestMatcherDelegatingAuthorizationManager.Builder managerBuilder = RequestMatcherDelegatingAuthorizationManager
.builder(); .builder();
private List<RequestMatcher> unmappedMatchers; private List<RequestMatcher> unmappedMatchers;

View File

@ -176,7 +176,7 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class); String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class);
if (grantedAuthorityDefaultsBeanNames.length == 1) { if (grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = context GrantedAuthorityDefaults grantedAuthorityDefaults = context
.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class); .getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
defaultHandler.setDefaultRolePrefix(grantedAuthorityDefaults.getRolePrefix()); defaultHandler.setDefaultRolePrefix(grantedAuthorityDefaults.getRolePrefix());
} }
String[] permissionEvaluatorBeanNames = context.getBeanNamesForType(PermissionEvaluator.class); String[] permissionEvaluatorBeanNames = context.getBeanNamesForType(PermissionEvaluator.class);
@ -339,7 +339,7 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
*/ */
public ExpressionInterceptUrlRegistry hasRole(String role) { public ExpressionInterceptUrlRegistry hasRole(String role) {
return access(ExpressionUrlAuthorizationConfigurer return access(ExpressionUrlAuthorizationConfigurer
.hasRole(ExpressionUrlAuthorizationConfigurer.this.rolePrefix, role)); .hasRole(ExpressionUrlAuthorizationConfigurer.this.rolePrefix, role));
} }
/** /**
@ -353,7 +353,7 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
*/ */
public ExpressionInterceptUrlRegistry hasAnyRole(String... roles) { public ExpressionInterceptUrlRegistry hasAnyRole(String... roles) {
return access(ExpressionUrlAuthorizationConfigurer return access(ExpressionUrlAuthorizationConfigurer
.hasAnyRole(ExpressionUrlAuthorizationConfigurer.this.rolePrefix, roles)); .hasAnyRole(ExpressionUrlAuthorizationConfigurer.this.rolePrefix, roles));
} }
/** /**

View File

@ -260,7 +260,7 @@ public final class FormLoginConfigurer<H extends HttpSecurityBuilder<H>> extends
*/ */
private void initDefaultLoginFilter(H http) { private void initDefaultLoginFilter(H http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class); .getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null && !isCustomLoginPage()) { if (loginPageGeneratingFilter != null && !isCustomLoginPage()) {
loginPageGeneratingFilter.setFormLoginEnabled(true); loginPageGeneratingFilter.setFormLoginEnabled(true);
loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter()); loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter());

View File

@ -192,8 +192,8 @@ public final class JeeConfigurer<H extends HttpSecurityBuilder<H>> extends Abstr
PreAuthenticatedAuthenticationProvider authenticationProvider = new PreAuthenticatedAuthenticationProvider(); PreAuthenticatedAuthenticationProvider authenticationProvider = new PreAuthenticatedAuthenticationProvider();
authenticationProvider.setPreAuthenticatedUserDetailsService(getUserDetailsService()); authenticationProvider.setPreAuthenticatedUserDetailsService(getUserDetailsService());
authenticationProvider = postProcess(authenticationProvider); authenticationProvider = postProcess(authenticationProvider);
http.authenticationProvider(authenticationProvider).setSharedObject(AuthenticationEntryPoint.class, http.authenticationProvider(authenticationProvider)
new Http403ForbiddenEntryPoint()); .setSharedObject(AuthenticationEntryPoint.class, new Http403ForbiddenEntryPoint());
} }
@Override @Override
@ -214,9 +214,9 @@ public final class JeeConfigurer<H extends HttpSecurityBuilder<H>> extends Abstr
this.j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter(); this.j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter();
this.j2eePreAuthenticatedProcessingFilter.setAuthenticationManager(authenticationManager); this.j2eePreAuthenticatedProcessingFilter.setAuthenticationManager(authenticationManager);
this.j2eePreAuthenticatedProcessingFilter this.j2eePreAuthenticatedProcessingFilter
.setAuthenticationDetailsSource(createWebAuthenticationDetailsSource()); .setAuthenticationDetailsSource(createWebAuthenticationDetailsSource());
this.j2eePreAuthenticatedProcessingFilter this.j2eePreAuthenticatedProcessingFilter
.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); .setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());
this.j2eePreAuthenticatedProcessingFilter = postProcess(this.j2eePreAuthenticatedProcessingFilter); this.j2eePreAuthenticatedProcessingFilter = postProcess(this.j2eePreAuthenticatedProcessingFilter);
} }

View File

@ -280,7 +280,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
PermitAllSupport.permitAll(http, this.getLogoutRequestMatcher(http)); PermitAllSupport.permitAll(http, this.getLogoutRequestMatcher(http));
} }
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class); .getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null && !isCustomLogoutSuccess()) { if (loginPageGeneratingFilter != null && !isCustomLogoutSuccess()) {
loginPageGeneratingFilter.setLogoutSuccessUrl(getLogoutSuccessUrl()); loginPageGeneratingFilter.setLogoutSuccessUrl(getLogoutSuccessUrl());
} }

View File

@ -47,7 +47,7 @@ final class PermitAllSupport {
static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http,
RequestMatcher... requestMatchers) { RequestMatcher... requestMatchers) {
ExpressionUrlAuthorizationConfigurer<?> configurer = http ExpressionUrlAuthorizationConfigurer<?> configurer = http
.getConfigurer(ExpressionUrlAuthorizationConfigurer.class); .getConfigurer(ExpressionUrlAuthorizationConfigurer.class);
AuthorizeHttpRequestsConfigurer<?> httpConfigurer = http.getConfigurer(AuthorizeHttpRequestsConfigurer.class); AuthorizeHttpRequestsConfigurer<?> httpConfigurer = http.getConfigurer(AuthorizeHttpRequestsConfigurer.class);
boolean oneConfigurerPresent = configurer == null ^ httpConfigurer == null; boolean oneConfigurerPresent = configurer == null ^ httpConfigurer == null;
@ -58,8 +58,9 @@ final class PermitAllSupport {
for (RequestMatcher matcher : requestMatchers) { for (RequestMatcher matcher : requestMatchers) {
if (matcher != null) { if (matcher != null) {
if (configurer != null) { if (configurer != null) {
configurer.getRegistry().addMapping(0, new UrlMapping(matcher, configurer.getRegistry()
SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll))); .addMapping(0, new UrlMapping(matcher,
SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll)));
} }
else { else {
httpConfigurer.addFirst(matcher, AuthorizeHttpRequestsConfigurer.permitAllAuthorizationManager); httpConfigurer.addFirst(matcher, AuthorizeHttpRequestsConfigurer.permitAllAuthorizationManager);

View File

@ -292,7 +292,7 @@ public final class RememberMeConfigurer<H extends HttpSecurityBuilder<H>>
SecurityContextConfigurer<?> securityContextConfigurer = http.getConfigurer(SecurityContextConfigurer.class); SecurityContextConfigurer<?> securityContextConfigurer = http.getConfigurer(SecurityContextConfigurer.class);
if (securityContextConfigurer != null && securityContextConfigurer.isRequireExplicitSave()) { if (securityContextConfigurer != null && securityContextConfigurer.isRequireExplicitSave()) {
SecurityContextRepository securityContextRepository = securityContextConfigurer SecurityContextRepository securityContextRepository = securityContextConfigurer
.getSecurityContextRepository(); .getSecurityContextRepository();
rememberMeFilter.setSecurityContextRepository(securityContextRepository); rememberMeFilter.setSecurityContextRepository(securityContextRepository);
} }
rememberMeFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); rememberMeFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());
@ -325,7 +325,7 @@ public final class RememberMeConfigurer<H extends HttpSecurityBuilder<H>>
*/ */
private void initDefaultLoginFilter(H http) { private void initDefaultLoginFilter(H http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class); .getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null) { if (loginPageGeneratingFilter != null) {
loginPageGeneratingFilter.setRememberMeParameter(getRememberMeParameter()); loginPageGeneratingFilter.setRememberMeParameter(getRememberMeParameter());
} }

View File

@ -94,7 +94,7 @@ public final class SecurityContextConfigurer<H extends HttpSecurityBuilder<H>>
SecurityContextRepository getSecurityContextRepository() { SecurityContextRepository getSecurityContextRepository() {
SecurityContextRepository securityContextRepository = getBuilder() SecurityContextRepository securityContextRepository = getBuilder()
.getSharedObject(SecurityContextRepository.class); .getSharedObject(SecurityContextRepository.class);
if (securityContextRepository == null) { if (securityContextRepository == null) {
securityContextRepository = new HttpSessionSecurityContextRepository(); securityContextRepository = new HttpSessionSecurityContextRepository();
} }

View File

@ -95,7 +95,7 @@ public final class ServletApiConfigurer<H extends HttpSecurityBuilder<H>>
String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class); String[] grantedAuthorityDefaultsBeanNames = context.getBeanNamesForType(GrantedAuthorityDefaults.class);
if (grantedAuthorityDefaultsBeanNames.length == 1) { if (grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = context GrantedAuthorityDefaults grantedAuthorityDefaults = context
.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class); .getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
this.securityContextRequestFilter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix()); this.securityContextRequestFilter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix());
} }
this.securityContextRequestFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); this.securityContextRequestFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());

View File

@ -172,8 +172,8 @@ public final class X509Configurer<H extends HttpSecurityBuilder<H>>
public void init(H http) { public void init(H http) {
PreAuthenticatedAuthenticationProvider authenticationProvider = new PreAuthenticatedAuthenticationProvider(); PreAuthenticatedAuthenticationProvider authenticationProvider = new PreAuthenticatedAuthenticationProvider();
authenticationProvider.setPreAuthenticatedUserDetailsService(getAuthenticationUserDetailsService(http)); authenticationProvider.setPreAuthenticatedUserDetailsService(getAuthenticationUserDetailsService(http));
http.authenticationProvider(authenticationProvider).setSharedObject(AuthenticationEntryPoint.class, http.authenticationProvider(authenticationProvider)
new Http403ForbiddenEntryPoint()); .setSharedObject(AuthenticationEntryPoint.class, new Http403ForbiddenEntryPoint());
} }
@Override @Override

View File

@ -259,7 +259,7 @@ public final class OAuth2ClientConfigurer<B extends HttpSecurityBuilder<B>>
resolver); resolver);
if (this.authorizationRequestRepository != null) { if (this.authorizationRequestRepository != null) {
authorizationRequestRedirectFilter authorizationRequestRedirectFilter
.setAuthorizationRequestRepository(this.authorizationRequestRepository); .setAuthorizationRequestRepository(this.authorizationRequestRepository);
} }
if (this.authorizationRedirectStrategy != null) { if (this.authorizationRedirectStrategy != null) {
authorizationRequestRedirectFilter.setAuthorizationRedirectStrategy(this.authorizationRedirectStrategy); authorizationRequestRedirectFilter.setAuthorizationRedirectStrategy(this.authorizationRedirectStrategy);
@ -276,7 +276,7 @@ public final class OAuth2ClientConfigurer<B extends HttpSecurityBuilder<B>>
return this.authorizationRequestResolver; return this.authorizationRequestResolver;
} }
ClientRegistrationRepository clientRegistrationRepository = OAuth2ClientConfigurerUtils ClientRegistrationRepository clientRegistrationRepository = OAuth2ClientConfigurerUtils
.getClientRegistrationRepository(getBuilder()); .getClientRegistrationRepository(getBuilder());
return new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository, return new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository,
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI); OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
} }

View File

@ -43,7 +43,7 @@ final class OAuth2ClientConfigurerUtils {
static <B extends HttpSecurityBuilder<B>> ClientRegistrationRepository getClientRegistrationRepository(B builder) { static <B extends HttpSecurityBuilder<B>> ClientRegistrationRepository getClientRegistrationRepository(B builder) {
ClientRegistrationRepository clientRegistrationRepository = builder ClientRegistrationRepository clientRegistrationRepository = builder
.getSharedObject(ClientRegistrationRepository.class); .getSharedObject(ClientRegistrationRepository.class);
if (clientRegistrationRepository == null) { if (clientRegistrationRepository == null) {
clientRegistrationRepository = getClientRegistrationRepositoryBean(builder); clientRegistrationRepository = getClientRegistrationRepositoryBean(builder);
builder.setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository); builder.setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
@ -59,7 +59,7 @@ final class OAuth2ClientConfigurerUtils {
static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientRepository getAuthorizedClientRepository( static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientRepository getAuthorizedClientRepository(
B builder) { B builder) {
OAuth2AuthorizedClientRepository authorizedClientRepository = builder OAuth2AuthorizedClientRepository authorizedClientRepository = builder
.getSharedObject(OAuth2AuthorizedClientRepository.class); .getSharedObject(OAuth2AuthorizedClientRepository.class);
if (authorizedClientRepository == null) { if (authorizedClientRepository == null) {
authorizedClientRepository = getAuthorizedClientRepositoryBean(builder); authorizedClientRepository = getAuthorizedClientRepositoryBean(builder);
if (authorizedClientRepository == null) { if (authorizedClientRepository == null) {
@ -74,8 +74,8 @@ final class OAuth2ClientConfigurerUtils {
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientRepository getAuthorizedClientRepositoryBean( private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientRepository getAuthorizedClientRepositoryBean(
B builder) { B builder) {
Map<String, OAuth2AuthorizedClientRepository> authorizedClientRepositoryMap = BeanFactoryUtils Map<String, OAuth2AuthorizedClientRepository> authorizedClientRepositoryMap = BeanFactoryUtils
.beansOfTypeIncludingAncestors(builder.getSharedObject(ApplicationContext.class), .beansOfTypeIncludingAncestors(builder.getSharedObject(ApplicationContext.class),
OAuth2AuthorizedClientRepository.class); OAuth2AuthorizedClientRepository.class);
if (authorizedClientRepositoryMap.size() > 1) { if (authorizedClientRepositoryMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientRepository.class, throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientRepository.class,
authorizedClientRepositoryMap.size(), authorizedClientRepositoryMap.size(),
@ -100,8 +100,8 @@ final class OAuth2ClientConfigurerUtils {
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientServiceBean( private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientServiceBean(
B builder) { B builder) {
Map<String, OAuth2AuthorizedClientService> authorizedClientServiceMap = BeanFactoryUtils Map<String, OAuth2AuthorizedClientService> authorizedClientServiceMap = BeanFactoryUtils
.beansOfTypeIncludingAncestors(builder.getSharedObject(ApplicationContext.class), .beansOfTypeIncludingAncestors(builder.getSharedObject(ApplicationContext.class),
OAuth2AuthorizedClientService.class); OAuth2AuthorizedClientService.class);
if (authorizedClientServiceMap.size() > 1) { if (authorizedClientServiceMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientService.class, throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientService.class,
authorizedClientServiceMap.size(), authorizedClientServiceMap.size(),

View File

@ -329,7 +329,7 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
} }
http.authenticationProvider(this.postProcess(oauth2LoginAuthenticationProvider)); http.authenticationProvider(this.postProcess(oauth2LoginAuthenticationProvider));
boolean oidcAuthenticationProviderEnabled = ClassUtils boolean oidcAuthenticationProviderEnabled = ClassUtils
.isPresent("org.springframework.security.oauth2.jwt.JwtDecoder", this.getClass().getClassLoader()); .isPresent("org.springframework.security.oauth2.jwt.JwtDecoder", this.getClass().getClassLoader());
if (oidcAuthenticationProviderEnabled) { if (oidcAuthenticationProviderEnabled) {
OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService = getOidcUserService(); OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService = getOidcUserService();
OidcAuthorizationCodeAuthenticationProvider oidcAuthorizationCodeAuthenticationProvider = new OidcAuthorizationCodeAuthenticationProvider( OidcAuthorizationCodeAuthenticationProvider oidcAuthorizationCodeAuthenticationProvider = new OidcAuthorizationCodeAuthenticationProvider(
@ -367,11 +367,11 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
} }
if (this.authorizationEndpointConfig.authorizationRequestRepository != null) { if (this.authorizationEndpointConfig.authorizationRequestRepository != null) {
authorizationRequestFilter authorizationRequestFilter
.setAuthorizationRequestRepository(this.authorizationEndpointConfig.authorizationRequestRepository); .setAuthorizationRequestRepository(this.authorizationEndpointConfig.authorizationRequestRepository);
} }
if (this.authorizationEndpointConfig.authorizationRedirectStrategy != null) { if (this.authorizationEndpointConfig.authorizationRedirectStrategy != null) {
authorizationRequestFilter authorizationRequestFilter
.setAuthorizationRedirectStrategy(this.authorizationEndpointConfig.authorizationRedirectStrategy); .setAuthorizationRedirectStrategy(this.authorizationEndpointConfig.authorizationRedirectStrategy);
} }
RequestCache requestCache = http.getSharedObject(RequestCache.class); RequestCache requestCache = http.getSharedObject(RequestCache.class);
if (requestCache != null) { if (requestCache != null) {
@ -384,7 +384,7 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
} }
if (this.authorizationEndpointConfig.authorizationRequestRepository != null) { if (this.authorizationEndpointConfig.authorizationRequestRepository != null) {
authenticationFilter authenticationFilter
.setAuthorizationRequestRepository(this.authorizationEndpointConfig.authorizationRequestRepository); .setAuthorizationRequestRepository(this.authorizationEndpointConfig.authorizationRequestRepository);
} }
super.configure(http); super.configure(http);
} }
@ -402,15 +402,16 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
throw new NoUniqueBeanDefinitionException(type, names); throw new NoUniqueBeanDefinitionException(type, names);
} }
if (names.length == 1) { if (names.length == 1) {
return (JwtDecoderFactory<ClientRegistration>) this.getBuilder().getSharedObject(ApplicationContext.class) return (JwtDecoderFactory<ClientRegistration>) this.getBuilder()
.getBean(names[0]); .getSharedObject(ApplicationContext.class)
.getBean(names[0]);
} }
return null; return null;
} }
private GrantedAuthoritiesMapper getGrantedAuthoritiesMapper() { private GrantedAuthoritiesMapper getGrantedAuthoritiesMapper() {
GrantedAuthoritiesMapper grantedAuthoritiesMapper = this.getBuilder() GrantedAuthoritiesMapper grantedAuthoritiesMapper = this.getBuilder()
.getSharedObject(GrantedAuthoritiesMapper.class); .getSharedObject(GrantedAuthoritiesMapper.class);
if (grantedAuthoritiesMapper == null) { if (grantedAuthoritiesMapper == null) {
grantedAuthoritiesMapper = this.getGrantedAuthoritiesMapperBean(); grantedAuthoritiesMapper = this.getGrantedAuthoritiesMapperBean();
if (grantedAuthoritiesMapper != null) { if (grantedAuthoritiesMapper != null) {
@ -422,8 +423,8 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
private GrantedAuthoritiesMapper getGrantedAuthoritiesMapperBean() { private GrantedAuthoritiesMapper getGrantedAuthoritiesMapperBean() {
Map<String, GrantedAuthoritiesMapper> grantedAuthoritiesMapperMap = BeanFactoryUtils Map<String, GrantedAuthoritiesMapper> grantedAuthoritiesMapperMap = BeanFactoryUtils
.beansOfTypeIncludingAncestors(this.getBuilder().getSharedObject(ApplicationContext.class), .beansOfTypeIncludingAncestors(this.getBuilder().getSharedObject(ApplicationContext.class),
GrantedAuthoritiesMapper.class); GrantedAuthoritiesMapper.class);
return (!grantedAuthoritiesMapperMap.isEmpty() ? grantedAuthoritiesMapperMap.values().iterator().next() : null); return (!grantedAuthoritiesMapperMap.isEmpty() ? grantedAuthoritiesMapperMap.values().iterator().next() : null);
} }
@ -469,7 +470,7 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
private void initDefaultLoginFilter(B http) { private void initDefaultLoginFilter(B http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class); .getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter == null || this.isCustomLoginPage()) { if (loginPageGeneratingFilter == null || this.isCustomLoginPage()) {
return; return;
} }
@ -483,7 +484,7 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
private Map<String, String> getLoginLinks() { private Map<String, String> getLoginLinks() {
Iterable<ClientRegistration> clientRegistrations = null; Iterable<ClientRegistration> clientRegistrations = null;
ClientRegistrationRepository clientRegistrationRepository = OAuth2ClientConfigurerUtils ClientRegistrationRepository clientRegistrationRepository = OAuth2ClientConfigurerUtils
.getClientRegistrationRepository(this.getBuilder()); .getClientRegistrationRepository(this.getBuilder());
ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class); ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class);
if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) { if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository; clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
@ -523,13 +524,13 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
private RequestMatcher getFormLoginNotEnabledRequestMatcher(B http) { private RequestMatcher getFormLoginNotEnabledRequestMatcher(B http) {
DefaultLoginPageGeneratingFilter defaultLoginPageGeneratingFilter = http DefaultLoginPageGeneratingFilter defaultLoginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class); .getSharedObject(DefaultLoginPageGeneratingFilter.class);
Field formLoginEnabledField = (defaultLoginPageGeneratingFilter != null) Field formLoginEnabledField = (defaultLoginPageGeneratingFilter != null)
? ReflectionUtils.findField(DefaultLoginPageGeneratingFilter.class, "formLoginEnabled") : null; ? ReflectionUtils.findField(DefaultLoginPageGeneratingFilter.class, "formLoginEnabled") : null;
if (formLoginEnabledField != null) { if (formLoginEnabledField != null) {
ReflectionUtils.makeAccessible(formLoginEnabledField); ReflectionUtils.makeAccessible(formLoginEnabledField);
return (request) -> Boolean.FALSE return (request) -> Boolean.FALSE
.equals(ReflectionUtils.getField(formLoginEnabledField, defaultLoginPageGeneratingFilter)); .equals(ReflectionUtils.getField(formLoginEnabledField, defaultLoginPageGeneratingFilter));
} }
return AnyRequestMatcher.INSTANCE; return AnyRequestMatcher.INSTANCE;
} }
@ -742,8 +743,8 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
*/ */
public UserInfoEndpointConfig userAuthoritiesMapper(GrantedAuthoritiesMapper userAuthoritiesMapper) { public UserInfoEndpointConfig userAuthoritiesMapper(GrantedAuthoritiesMapper userAuthoritiesMapper) {
Assert.notNull(userAuthoritiesMapper, "userAuthoritiesMapper cannot be null"); Assert.notNull(userAuthoritiesMapper, "userAuthoritiesMapper cannot be null");
OAuth2LoginConfigurer.this.getBuilder().setSharedObject(GrantedAuthoritiesMapper.class, OAuth2LoginConfigurer.this.getBuilder()
userAuthoritiesMapper); .setSharedObject(GrantedAuthoritiesMapper.class, userAuthoritiesMapper);
return this; return this;
} }
@ -763,7 +764,7 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication; OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication;
OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange() OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationRequest(); .getAuthorizationRequest();
if (authorizationRequest.getScopes().contains(OidcScopes.OPENID)) { if (authorizationRequest.getScopes().contains(OidcScopes.OPENID)) {
// Section 3.1.2.1 Authentication Request - // Section 3.1.2.1 Authentication Request -
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest scope // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest scope

View File

@ -305,7 +305,7 @@ public final class OAuth2ResourceServerConfigurer<H extends HttpSecurityBuilder<
ExceptionHandlingConfigurer<H> exceptionHandling = http.getConfigurer(ExceptionHandlingConfigurer.class); ExceptionHandlingConfigurer<H> exceptionHandling = http.getConfigurer(ExceptionHandlingConfigurer.class);
if (exceptionHandling != null) { if (exceptionHandling != null) {
ContentNegotiationStrategy contentNegotiationStrategy = http ContentNegotiationStrategy contentNegotiationStrategy = http
.getSharedObject(ContentNegotiationStrategy.class); .getSharedObject(ContentNegotiationStrategy.class);
if (contentNegotiationStrategy == null) { if (contentNegotiationStrategy == null) {
contentNegotiationStrategy = new HeaderContentNegotiationStrategy(); contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
} }

View File

@ -357,7 +357,7 @@ public final class OpenIDLoginConfigurer<H extends HttpSecurityBuilder<H>>
*/ */
private void initDefaultLoginFilter(H http) { private void initDefaultLoginFilter(H http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class); .getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null && !isCustomLoginPage()) { if (loginPageGeneratingFilter != null && !isCustomLoginPage()) {
loginPageGeneratingFilter.setOpenIdEnabled(true); loginPageGeneratingFilter.setOpenIdEnabled(true);
loginPageGeneratingFilter.setOpenIDauthenticationUrl(getLoginProcessingUrl()); loginPageGeneratingFilter.setOpenIDauthenticationUrl(getLoginProcessingUrl());
@ -367,7 +367,7 @@ public final class OpenIDLoginConfigurer<H extends HttpSecurityBuilder<H>>
loginPageGeneratingFilter.setFailureUrl(getFailureUrl()); loginPageGeneratingFilter.setFailureUrl(getFailureUrl());
} }
loginPageGeneratingFilter loginPageGeneratingFilter
.setOpenIDusernameParameter(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD); .setOpenIDusernameParameter(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD);
} }
} }

View File

@ -394,7 +394,7 @@ public final class Saml2LoginConfigurer<B extends HttpSecurityBuilder<B>>
private void initDefaultLoginFilter(B http) { private void initDefaultLoginFilter(B http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class); .getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter == null || this.isCustomLoginPage()) { if (loginPageGeneratingFilter == null || this.isCustomLoginPage()) {
return; return;
} }
@ -433,7 +433,7 @@ public final class Saml2LoginConfigurer<B extends HttpSecurityBuilder<B>>
return version; return version;
} }
boolean openSaml4ClassPresent = ClassUtils boolean openSaml4ClassPresent = ClassUtils
.isPresent("org.opensaml.core.xml.persist.impl.PassthroughSourceStrategy", null); .isPresent("org.opensaml.core.xml.persist.impl.PassthroughSourceStrategy", null);
if (openSaml4ClassPresent) { if (openSaml4ClassPresent) {
return OPEN_SAML_4_VERSION; return OPEN_SAML_4_VERSION;
} }
@ -475,7 +475,7 @@ public final class Saml2LoginConfigurer<B extends HttpSecurityBuilder<B>>
"org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationRequestFactory", "org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationRequestFactory",
OpenSaml4LoginSupportFactory.class.getClassLoader()); OpenSaml4LoginSupportFactory.class.getClassLoader());
return (Saml2AuthenticationRequestFactory) authenticationRequestFactory.getDeclaredConstructor() return (Saml2AuthenticationRequestFactory) authenticationRequestFactory.getDeclaredConstructor()
.newInstance(); .newInstance();
} }
catch (ReflectiveOperationException ex) { catch (ReflectiveOperationException ex) {
throw new IllegalStateException("Could not instantiate OpenSaml4AuthenticationRequestFactory", ex); throw new IllegalStateException("Could not instantiate OpenSaml4AuthenticationRequestFactory", ex);

View File

@ -299,7 +299,7 @@ public final class Saml2LogoutConfigurer<H extends HttpSecurityBuilder<H>>
private Saml2RelyingPartyInitiatedLogoutSuccessHandler createSaml2LogoutRequestSuccessHandler( private Saml2RelyingPartyInitiatedLogoutSuccessHandler createSaml2LogoutRequestSuccessHandler(
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) {
Saml2LogoutRequestResolver logoutRequestResolver = this.logoutRequestConfigurer Saml2LogoutRequestResolver logoutRequestResolver = this.logoutRequestConfigurer
.logoutRequestResolver(relyingPartyRegistrationResolver); .logoutRequestResolver(relyingPartyRegistrationResolver);
return new Saml2RelyingPartyInitiatedLogoutSuccessHandler(logoutRequestResolver); return new Saml2RelyingPartyInitiatedLogoutSuccessHandler(logoutRequestResolver);
} }
@ -314,7 +314,7 @@ public final class Saml2LogoutConfigurer<H extends HttpSecurityBuilder<H>>
return version; return version;
} }
boolean openSaml4ClassPresent = ClassUtils boolean openSaml4ClassPresent = ClassUtils
.isPresent("org.opensaml.core.xml.persist.impl.PassthroughSourceStrategy", null); .isPresent("org.opensaml.core.xml.persist.impl.PassthroughSourceStrategy", null);
if (openSaml4ClassPresent) { if (openSaml4ClassPresent) {
return OPEN_SAML_4_VERSION; return OPEN_SAML_4_VERSION;
} }
@ -543,8 +543,8 @@ public final class Saml2LogoutConfigurer<H extends HttpSecurityBuilder<H>>
"org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutResponseResolver", "org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutResponseResolver",
OpenSaml4LogoutSupportFactory.class.getClassLoader()); OpenSaml4LogoutSupportFactory.class.getClassLoader());
return (Saml2LogoutResponseResolver) logoutResponseResolver return (Saml2LogoutResponseResolver) logoutResponseResolver
.getDeclaredConstructor(RelyingPartyRegistrationResolver.class) .getDeclaredConstructor(RelyingPartyRegistrationResolver.class)
.newInstance(relyingPartyRegistrationResolver); .newInstance(relyingPartyRegistrationResolver);
} }
catch (ReflectiveOperationException ex) { catch (ReflectiveOperationException ex) {
throw new IllegalStateException("Could not instantiate OpenSaml4LogoutResponseResolver", ex); throw new IllegalStateException("Could not instantiate OpenSaml4LogoutResponseResolver", ex);
@ -558,8 +558,8 @@ public final class Saml2LogoutConfigurer<H extends HttpSecurityBuilder<H>>
"org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutRequestResolver", "org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutRequestResolver",
OpenSaml4LogoutSupportFactory.class.getClassLoader()); OpenSaml4LogoutSupportFactory.class.getClassLoader());
return (Saml2LogoutRequestResolver) logoutRequestResolver return (Saml2LogoutRequestResolver) logoutRequestResolver
.getDeclaredConstructor(RelyingPartyRegistrationResolver.class) .getDeclaredConstructor(RelyingPartyRegistrationResolver.class)
.newInstance(relyingPartyRegistrationResolver); .newInstance(relyingPartyRegistrationResolver);
} }
catch (ReflectiveOperationException ex) { catch (ReflectiveOperationException ex) {
throw new IllegalStateException("Could not instantiate OpenSaml4LogoutRequestResolver", ex); throw new IllegalStateException("Could not instantiate OpenSaml4LogoutRequestResolver", ex);

View File

@ -235,7 +235,7 @@ public class MessageSecurityMetadataSourceRegistry {
matcherToExpression.put(entry.getKey().build(), entry.getValue()); matcherToExpression.put(entry.getKey().build(), entry.getValue());
} }
return ExpressionBasedMessageSecurityMetadataSourceFactory return ExpressionBasedMessageSecurityMetadataSourceFactory
.createExpressionMessageMetadataSource(matcherToExpression, this.expressionHandler); .createExpressionMessageMetadataSource(matcherToExpression, this.expressionHandler);
} }
/** /**

View File

@ -117,7 +117,12 @@ final class ReactiveOAuth2ClientImportSelector implements ImportSelector {
ReactiveOAuth2AuthorizedClientManager authorizedClientManager = null; ReactiveOAuth2AuthorizedClientManager authorizedClientManager = null;
if (this.authorizedClientRepository != null && this.clientRegistrationRepository != null) { if (this.authorizedClientRepository != null && this.clientRegistrationRepository != null) {
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder().authorizationCode().refreshToken().clientCredentials().password().build(); .builder()
.authorizationCode()
.refreshToken()
.clientCredentials()
.password()
.build();
DefaultReactiveOAuth2AuthorizedClientManager defaultReactiveOAuth2AuthorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager( DefaultReactiveOAuth2AuthorizedClientManager defaultReactiveOAuth2AuthorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, getAuthorizedClientRepository()); this.clientRegistrationRepository, getAuthorizedClientRepository());
defaultReactiveOAuth2AuthorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); defaultReactiveOAuth2AuthorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

View File

@ -120,7 +120,7 @@ class WebFluxSecurityConfiguration {
static boolean shouldConfigure(ApplicationContext context) { static boolean shouldConfigure(ApplicationContext context) {
ClassLoader loader = context.getClassLoader(); ClassLoader loader = context.getClassLoader();
Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils
.resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader); .resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader);
return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1; return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1;
} }

View File

@ -29,6 +29,7 @@ import org.springframework.security.config.annotation.authentication.configurati
/** /**
* Add this annotation to an {@code @Configuration} class to have the Spring Security * Add this annotation to an {@code @Configuration} class to have the Spring Security
* configuration integrate with Spring MVC. * configuration integrate with Spring MVC.
*
* @deprecated Use EnableWebSecurity instead which will automatically add the Spring MVC * @deprecated Use EnableWebSecurity instead which will automatically add the Spring MVC
* related Security items. * related Security items.
* @author Rob Winch * @author Rob Winch

View File

@ -32,8 +32,8 @@ import org.springframework.web.servlet.support.RequestDataValueProcessor;
* Used to add a {@link RequestDataValueProcessor} for Spring MVC and Spring Security CSRF * Used to add a {@link RequestDataValueProcessor} for Spring MVC and Spring Security CSRF
* integration. This configuration is added whenever {@link EnableWebMvc} is added by * integration. This configuration is added whenever {@link EnableWebMvc} is added by
* <a href=" * <a href="
* {@docRoot}/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.html">SpringWebMvcImportSelector</a> * {@docRoot}/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.html">SpringWebMvcImportSelector</a> and
* and the DispatcherServlet is present on the classpath. It also adds the * the DispatcherServlet is present on the classpath. It also adds the
* {@link AuthenticationPrincipalArgumentResolver} as a * {@link AuthenticationPrincipalArgumentResolver} as a
* {@link HandlerMethodArgumentResolver}. * {@link HandlerMethodArgumentResolver}.
* *
@ -51,7 +51,7 @@ public class WebMvcSecurityConfiguration implements WebMvcConfigurer {
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new AuthenticationPrincipalArgumentResolver()); argumentResolvers.add(new AuthenticationPrincipalArgumentResolver());
argumentResolvers argumentResolvers
.add(new org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver()); .add(new org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver());
} }
@Bean @Bean

View File

@ -29,10 +29,11 @@ final class MessageMatcherAuthorizationManagerConfiguration {
@Scope("prototype") @Scope("prototype")
MessageMatcherDelegatingAuthorizationManager.Builder messageAuthorizationManagerBuilder( MessageMatcherDelegatingAuthorizationManager.Builder messageAuthorizationManagerBuilder(
ApplicationContext context) { ApplicationContext context) {
return MessageMatcherDelegatingAuthorizationManager.builder().simpDestPathMatcher( return MessageMatcherDelegatingAuthorizationManager.builder()
() -> (context.getBeanNamesForType(SimpAnnotationMethodMessageHandler.class).length > 0) .simpDestPathMatcher(
? context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher() () -> (context.getBeanNamesForType(SimpAnnotationMethodMessageHandler.class).length > 0)
: new AntPathMatcher()); ? context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher()
: new AntPathMatcher());
} }
} }

View File

@ -61,10 +61,13 @@ final class WebSocketMessageBrokerSecurityConfiguration
private MessageMatcherDelegatingAuthorizationManager b; private MessageMatcherDelegatingAuthorizationManager b;
private static final AuthorizationManager<Message<?>> ANY_MESSAGE_AUTHENTICATED = MessageMatcherDelegatingAuthorizationManager private static final AuthorizationManager<Message<?>> ANY_MESSAGE_AUTHENTICATED = MessageMatcherDelegatingAuthorizationManager
.builder().anyMessage().authenticated().build(); .builder()
.anyMessage()
.authenticated()
.build();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy(); .getContextHolderStrategy();
private final SecurityContextChannelInterceptor securityContextChannelInterceptor = new SecurityContextChannelInterceptor(); private final SecurityContextChannelInterceptor securityContextChannelInterceptor = new SecurityContextChannelInterceptor();
@ -95,7 +98,7 @@ final class WebSocketMessageBrokerSecurityConfiguration
} }
this.authorizationChannelInterceptor this.authorizationChannelInterceptor
.setAuthorizationEventPublisher(new SpringAuthorizationEventPublisher(this.context)); .setAuthorizationEventPublisher(new SpringAuthorizationEventPublisher(this.context));
this.authorizationChannelInterceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); this.authorizationChannelInterceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
this.securityContextChannelInterceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); this.securityContextChannelInterceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
registration.interceptors(this.securityContextChannelInterceptor, this.csrfChannelInterceptor, registration.interceptors(this.securityContextChannelInterceptor, this.csrfChannelInterceptor,

View File

@ -55,12 +55,12 @@ public abstract class AbstractUserDetailsServiceBeanDefinitionParser implements
// Register a caching version of the user service if there's a cache-ref // Register a caching version of the user service if there's a cache-ref
if (StringUtils.hasText(cacheRef)) { if (StringUtils.hasText(cacheRef)) {
BeanDefinitionBuilder cachingUSBuilder = BeanDefinitionBuilder BeanDefinitionBuilder cachingUSBuilder = BeanDefinitionBuilder
.rootBeanDefinition(CachingUserDetailsService.class); .rootBeanDefinition(CachingUserDetailsService.class);
cachingUSBuilder.addConstructorArgReference(beanId); cachingUSBuilder.addConstructorArgReference(beanId);
cachingUSBuilder.addPropertyValue("userCache", new RuntimeBeanReference(cacheRef)); cachingUSBuilder.addPropertyValue("userCache", new RuntimeBeanReference(cacheRef));
BeanDefinition cachingUserService = cachingUSBuilder.getBeanDefinition(); BeanDefinition cachingUserService = cachingUSBuilder.getBeanDefinition();
parserContext parserContext
.registerBeanComponent(new BeanComponentDefinition(cachingUserService, beanId + CACHING_SUFFIX)); .registerBeanComponent(new BeanComponentDefinition(cachingUserService, beanId + CACHING_SUFFIX));
} }
return null; return null;
} }

View File

@ -64,8 +64,8 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition
String id = element.getAttribute("id"); String id = element.getAttribute("id");
if (!StringUtils.hasText(id)) { if (!StringUtils.hasText(id)) {
if (pc.getRegistry().containsBeanDefinition(BeanIds.AUTHENTICATION_MANAGER)) { if (pc.getRegistry().containsBeanDefinition(BeanIds.AUTHENTICATION_MANAGER)) {
pc.getReaderContext().warning("Overriding globally registered AuthenticationManager", pc.getReaderContext()
pc.extractSource(element)); .warning("Overriding globally registered AuthenticationManager", pc.extractSource(element));
} }
id = BeanIds.AUTHENTICATION_MANAGER; id = BeanIds.AUTHENTICATION_MANAGER;
} }
@ -124,14 +124,16 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition
return new RuntimeBeanReference(providerId); return new RuntimeBeanReference(providerId);
} }
if (providerElement.getAttributes().getLength() > 1) { if (providerElement.getAttributes().getLength() > 1) {
pc.getReaderContext().error("authentication-provider element cannot be used with other attributes " pc.getReaderContext()
+ "when using 'ref' attribute", pc.extractSource(element)); .error("authentication-provider element cannot be used with other attributes "
+ "when using 'ref' attribute", pc.extractSource(element));
} }
NodeList providerChildren = providerElement.getChildNodes(); NodeList providerChildren = providerElement.getChildNodes();
for (int i = 0; i < providerChildren.getLength(); i++) { for (int i = 0; i < providerChildren.getLength(); i++) {
if (providerChildren.item(i) instanceof Element) { if (providerChildren.item(i) instanceof Element) {
pc.getReaderContext().error("authentication-provider element cannot have child elements when used " pc.getReaderContext()
+ "with 'ref' attribute", pc.extractSource(element)); .error("authentication-provider element cannot have child elements when used "
+ "with 'ref' attribute", pc.extractSource(element));
} }
} }
return new RuntimeBeanReference(ref); return new RuntimeBeanReference(ref);

View File

@ -60,9 +60,9 @@ public class AuthenticationProviderBeanDefinitionParser implements BeanDefinitio
if (StringUtils.hasText(ref)) { if (StringUtils.hasText(ref)) {
if (userServiceElt != null) { if (userServiceElt != null) {
pc.getReaderContext() pc.getReaderContext()
.error("The " + ATT_USER_DETAILS_REF + " attribute cannot be used in combination with child" .error("The " + ATT_USER_DETAILS_REF + " attribute cannot be used in combination with child"
+ "elements '" + Elements.USER_SERVICE + "', '" + Elements.JDBC_USER_SERVICE + "' or '" + "elements '" + Elements.USER_SERVICE + "', '" + Elements.JDBC_USER_SERVICE + "' or '"
+ Elements.LDAP_USER_SERVICE + "'", element); + Elements.LDAP_USER_SERVICE + "'", element);
} }
authProvider.getPropertyValues().add("userDetailsService", new RuntimeBeanReference(ref)); authProvider.getPropertyValues().add("userDetailsService", new RuntimeBeanReference(ref));
} }

View File

@ -46,8 +46,9 @@ public class JdbcUserServiceBeanDefinitionParser extends AbstractUserDetailsServ
builder.addPropertyReference("dataSource", dataSource); builder.addPropertyReference("dataSource", dataSource);
} }
else { else {
parserContext.getReaderContext().error(ATT_DATA_SOURCE + " is required for " + Elements.JDBC_USER_SERVICE, parserContext.getReaderContext()
parserContext.extractSource(element)); .error(ATT_DATA_SOURCE + " is required for " + Elements.JDBC_USER_SERVICE,
parserContext.extractSource(element));
} }
String usersQuery = element.getAttribute(ATT_USERS_BY_USERNAME_QUERY); String usersQuery = element.getAttribute(ATT_USERS_BY_USERNAME_QUERY);
String authoritiesQuery = element.getAttribute(ATT_AUTHORITIES_BY_USERNAME_QUERY); String authoritiesQuery = element.getAttribute(ATT_AUTHORITIES_BY_USERNAME_QUERY);

View File

@ -315,11 +315,12 @@ final class AuthenticationConfigBuilder {
formFilter.getPropertyValues().addPropertyValue("allowSessionCreation", this.allowSessionCreation); formFilter.getPropertyValues().addPropertyValue("allowSessionCreation", this.allowSessionCreation);
formFilter.getPropertyValues().addPropertyValue("authenticationManager", authManager); formFilter.getPropertyValues().addPropertyValue("authenticationManager", authManager);
if (authenticationFilterSecurityContextRepositoryRef != null) { if (authenticationFilterSecurityContextRepositoryRef != null) {
formFilter.getPropertyValues().addPropertyValue("securityContextRepository", formFilter.getPropertyValues()
authenticationFilterSecurityContextRepositoryRef); .addPropertyValue("securityContextRepository", authenticationFilterSecurityContextRepositoryRef);
} }
formFilter.getPropertyValues().addPropertyValue("securityContextHolderStrategy", formFilter.getPropertyValues()
authenticationFilterSecurityContextHolderStrategyRef); .addPropertyValue("securityContextHolderStrategy",
authenticationFilterSecurityContextHolderStrategyRef);
// Id is required by login page filter // Id is required by login page filter
this.formFilterId = this.pc.getReaderContext().generateBeanName(formFilter); this.formFilterId = this.pc.getReaderContext().generateBeanName(formFilter);
this.pc.registerBeanComponent(new BeanComponentDefinition(formFilter, this.formFilterId)); this.pc.registerBeanComponent(new BeanComponentDefinition(formFilter, this.formFilterId));
@ -353,8 +354,8 @@ final class AuthenticationConfigBuilder {
registerDefaultAuthorizedClientRepositoryIfNecessary(defaultAuthorizedClientRepository); registerDefaultAuthorizedClientRepositoryIfNecessary(defaultAuthorizedClientRepository);
oauth2LoginFilterBean.getPropertyValues().addPropertyValue("authenticationManager", authManager); oauth2LoginFilterBean.getPropertyValues().addPropertyValue("authenticationManager", authManager);
if (authenticationFilterSecurityContextRepositoryRef != null) { if (authenticationFilterSecurityContextRepositoryRef != null) {
oauth2LoginFilterBean.getPropertyValues().addPropertyValue("securityContextRepository", oauth2LoginFilterBean.getPropertyValues()
authenticationFilterSecurityContextRepositoryRef); .addPropertyValue("securityContextRepository", authenticationFilterSecurityContextRepositoryRef);
} }
// retrieve the other bean result // retrieve the other bean result
@ -366,7 +367,7 @@ final class AuthenticationConfigBuilder {
String oauth2LoginAuthProviderId = this.pc.getReaderContext().generateBeanName(oauth2LoginAuthProvider); String oauth2LoginAuthProviderId = this.pc.getReaderContext().generateBeanName(oauth2LoginAuthProvider);
this.oauth2LoginFilterId = this.pc.getReaderContext().generateBeanName(oauth2LoginFilterBean); this.oauth2LoginFilterId = this.pc.getReaderContext().generateBeanName(oauth2LoginFilterBean);
String oauth2AuthorizationRequestRedirectFilterId = this.pc.getReaderContext() String oauth2AuthorizationRequestRedirectFilterId = this.pc.getReaderContext()
.generateBeanName(this.oauth2AuthorizationRequestRedirectFilter); .generateBeanName(this.oauth2AuthorizationRequestRedirectFilter);
this.oauth2LoginLinks = parser.getOAuth2LoginLinks(); this.oauth2LoginLinks = parser.getOAuth2LoginLinks();
// register the component // register the component
@ -401,17 +402,17 @@ final class AuthenticationConfigBuilder {
registerDefaultAuthorizedClientRepositoryIfNecessary(defaultAuthorizedClientRepository); registerDefaultAuthorizedClientRepositoryIfNecessary(defaultAuthorizedClientRepository);
this.authorizationRequestRedirectFilter = parser.getAuthorizationRequestRedirectFilter(); this.authorizationRequestRedirectFilter = parser.getAuthorizationRequestRedirectFilter();
String authorizationRequestRedirectFilterId = this.pc.getReaderContext() String authorizationRequestRedirectFilterId = this.pc.getReaderContext()
.generateBeanName(this.authorizationRequestRedirectFilter); .generateBeanName(this.authorizationRequestRedirectFilter);
this.pc.registerBeanComponent(new BeanComponentDefinition(this.authorizationRequestRedirectFilter, this.pc.registerBeanComponent(new BeanComponentDefinition(this.authorizationRequestRedirectFilter,
authorizationRequestRedirectFilterId)); authorizationRequestRedirectFilterId));
this.authorizationCodeGrantFilter = parser.getAuthorizationCodeGrantFilter(); this.authorizationCodeGrantFilter = parser.getAuthorizationCodeGrantFilter();
String authorizationCodeGrantFilterId = this.pc.getReaderContext() String authorizationCodeGrantFilterId = this.pc.getReaderContext()
.generateBeanName(this.authorizationCodeGrantFilter); .generateBeanName(this.authorizationCodeGrantFilter);
this.pc.registerBeanComponent( this.pc.registerBeanComponent(
new BeanComponentDefinition(this.authorizationCodeGrantFilter, authorizationCodeGrantFilterId)); new BeanComponentDefinition(this.authorizationCodeGrantFilter, authorizationCodeGrantFilterId));
BeanDefinition authorizationCodeAuthenticationProvider = parser.getAuthorizationCodeAuthenticationProvider(); BeanDefinition authorizationCodeAuthenticationProvider = parser.getAuthorizationCodeAuthenticationProvider();
String authorizationCodeAuthenticationProviderId = this.pc.getReaderContext() String authorizationCodeAuthenticationProviderId = this.pc.getReaderContext()
.generateBeanName(authorizationCodeAuthenticationProvider); .generateBeanName(authorizationCodeAuthenticationProvider);
this.pc.registerBeanComponent(new BeanComponentDefinition(authorizationCodeAuthenticationProvider, this.pc.registerBeanComponent(new BeanComponentDefinition(authorizationCodeAuthenticationProvider,
authorizationCodeAuthenticationProviderId)); authorizationCodeAuthenticationProviderId));
this.authorizationCodeAuthenticationProviderRef = new RuntimeBeanReference( this.authorizationCodeAuthenticationProviderRef = new RuntimeBeanReference(
@ -421,7 +422,7 @@ final class AuthenticationConfigBuilder {
void registerDefaultAuthorizedClientRepositoryIfNecessary(BeanDefinition defaultAuthorizedClientRepository) { void registerDefaultAuthorizedClientRepositoryIfNecessary(BeanDefinition defaultAuthorizedClientRepository) {
if (!this.defaultAuthorizedClientRepositoryRegistered && defaultAuthorizedClientRepository != null) { if (!this.defaultAuthorizedClientRepositoryRegistered && defaultAuthorizedClientRepository != null) {
String authorizedClientRepositoryId = this.pc.getReaderContext() String authorizedClientRepositoryId = this.pc.getReaderContext()
.generateBeanName(defaultAuthorizedClientRepository); .generateBeanName(defaultAuthorizedClientRepository);
this.pc.registerBeanComponent( this.pc.registerBeanComponent(
new BeanComponentDefinition(defaultAuthorizedClientRepository, authorizedClientRepositoryId)); new BeanComponentDefinition(defaultAuthorizedClientRepository, authorizedClientRepositoryId));
this.defaultAuthorizedClientRepositoryRegistered = true; this.defaultAuthorizedClientRepositoryRegistered = true;
@ -436,7 +437,7 @@ final class AuthenticationConfigBuilder {
getClass().getClassLoader()); getClass().getClassLoader());
if (webmvcPresent) { if (webmvcPresent) {
this.pc.getReaderContext() this.pc.getReaderContext()
.registerWithGeneratedName(new RootBeanDefinition(OAuth2ClientWebMvcSecurityPostProcessor.class)); .registerWithGeneratedName(new RootBeanDefinition(OAuth2ClientWebMvcSecurityPostProcessor.class));
} }
} }
@ -451,8 +452,8 @@ final class AuthenticationConfigBuilder {
openIDFilter.getPropertyValues().addPropertyValue("allowSessionCreation", this.allowSessionCreation); openIDFilter.getPropertyValues().addPropertyValue("allowSessionCreation", this.allowSessionCreation);
openIDFilter.getPropertyValues().addPropertyValue("authenticationManager", authManager); openIDFilter.getPropertyValues().addPropertyValue("authenticationManager", authManager);
if (authenticationFilterSecurityContextRepositoryRef != null) { if (authenticationFilterSecurityContextRepositoryRef != null) {
openIDFilter.getPropertyValues().addPropertyValue("securityContextRepository", openIDFilter.getPropertyValues()
authenticationFilterSecurityContextRepositoryRef); .addPropertyValue("securityContextRepository", authenticationFilterSecurityContextRepositoryRef);
} }
// Required by login page filter // Required by login page filter
this.openIDFilterId = this.pc.getReaderContext().generateBeanName(openIDFilter); this.openIDFilterId = this.pc.getReaderContext().generateBeanName(openIDFilter);
@ -477,7 +478,7 @@ final class AuthenticationConfigBuilder {
this.saml2AuthenticationFilterId = this.pc.getReaderContext().generateBeanName(saml2WebSsoAuthenticationFilter); this.saml2AuthenticationFilterId = this.pc.getReaderContext().generateBeanName(saml2WebSsoAuthenticationFilter);
this.saml2AuthenticationRequestFilterId = this.pc.getReaderContext() this.saml2AuthenticationRequestFilterId = this.pc.getReaderContext()
.generateBeanName(this.saml2AuthorizationRequestFilter); .generateBeanName(this.saml2AuthorizationRequestFilter);
this.saml2AuthenticationUrlToProviderName = parser.getSaml2AuthenticationUrlToProviderName(); this.saml2AuthenticationUrlToProviderName = parser.getSaml2AuthenticationUrlToProviderName();
// register the component // register the component
@ -520,8 +521,9 @@ final class AuthenticationConfigBuilder {
String identifierMatch = attrExElt.getAttribute("identifier-match"); String identifierMatch = attrExElt.getAttribute("identifier-match");
if (!StringUtils.hasText(identifierMatch)) { if (!StringUtils.hasText(identifierMatch)) {
if (attrExElts.size() > 1) { if (attrExElts.size() > 1) {
this.pc.getReaderContext().error("You must supply an identifier-match attribute if using more" this.pc.getReaderContext()
+ " than one " + Elements.OPENID_ATTRIBUTE_EXCHANGE + " element", attrExElt); .error("You must supply an identifier-match attribute if using more" + " than one "
+ Elements.OPENID_ATTRIBUTE_EXCHANGE + " element", attrExElt);
} }
// Match anything // Match anything
identifierMatch = ".*"; identifierMatch = ".*";
@ -559,7 +561,7 @@ final class AuthenticationConfigBuilder {
private void createOpenIDProvider() { private void createOpenIDProvider() {
Element openIDLoginElt = DomUtils.getChildElementByTagName(this.httpElt, Elements.OPENID_LOGIN); Element openIDLoginElt = DomUtils.getChildElementByTagName(this.httpElt, Elements.OPENID_LOGIN);
BeanDefinitionBuilder openIDProviderBuilder = BeanDefinitionBuilder BeanDefinitionBuilder openIDProviderBuilder = BeanDefinitionBuilder
.rootBeanDefinition(OPEN_ID_AUTHENTICATION_PROVIDER_CLASS); .rootBeanDefinition(OPEN_ID_AUTHENTICATION_PROVIDER_CLASS);
RootBeanDefinition uds = new RootBeanDefinition(); RootBeanDefinition uds = new RootBeanDefinition();
uds.setFactoryBeanName(BeanIds.USER_DETAILS_SERVICE_FACTORY); uds.setFactoryBeanName(BeanIds.USER_DETAILS_SERVICE_FACTORY);
uds.setFactoryMethodName("authenticationUserDetailsService"); uds.setFactoryMethodName("authenticationUserDetailsService");
@ -572,8 +574,8 @@ final class AuthenticationConfigBuilder {
private void injectRememberMeServicesRef(RootBeanDefinition bean, String rememberMeServicesId) { private void injectRememberMeServicesRef(RootBeanDefinition bean, String rememberMeServicesId) {
if (rememberMeServicesId != null) { if (rememberMeServicesId != null) {
bean.getPropertyValues().addPropertyValue("rememberMeServices", bean.getPropertyValues()
new RuntimeBeanReference(rememberMeServicesId)); .addPropertyValue("rememberMeServices", new RuntimeBeanReference(rememberMeServicesId));
} }
} }
@ -631,7 +633,7 @@ final class AuthenticationConfigBuilder {
RootBeanDefinition filter = null; RootBeanDefinition filter = null;
if (x509Elt != null) { if (x509Elt != null) {
BeanDefinitionBuilder filterBuilder = BeanDefinitionBuilder BeanDefinitionBuilder filterBuilder = BeanDefinitionBuilder
.rootBeanDefinition(X509AuthenticationFilter.class); .rootBeanDefinition(X509AuthenticationFilter.class);
filterBuilder.getRawBeanDefinition().setSource(this.pc.extractSource(x509Elt)); filterBuilder.getRawBeanDefinition().setSource(this.pc.extractSource(x509Elt));
filterBuilder.addPropertyValue("authenticationManager", authManager); filterBuilder.addPropertyValue("authenticationManager", authManager);
filterBuilder.addPropertyValue("securityContextHolderStrategy", filterBuilder.addPropertyValue("securityContextHolderStrategy",
@ -639,7 +641,7 @@ final class AuthenticationConfigBuilder {
String regex = x509Elt.getAttribute("subject-principal-regex"); String regex = x509Elt.getAttribute("subject-principal-regex");
if (StringUtils.hasText(regex)) { if (StringUtils.hasText(regex)) {
BeanDefinitionBuilder extractor = BeanDefinitionBuilder BeanDefinitionBuilder extractor = BeanDefinitionBuilder
.rootBeanDefinition(SubjectDnX509PrincipalExtractor.class); .rootBeanDefinition(SubjectDnX509PrincipalExtractor.class);
extractor.addPropertyValue("subjectDnRegex", regex); extractor.addPropertyValue("subjectDnRegex", regex);
filterBuilder.addPropertyValue("principalExtractor", extractor.getBeanDefinition()); filterBuilder.addPropertyValue("principalExtractor", extractor.getBeanDefinition());
} }
@ -682,13 +684,13 @@ final class AuthenticationConfigBuilder {
RootBeanDefinition filter = null; RootBeanDefinition filter = null;
if (jeeElt != null) { if (jeeElt != null) {
BeanDefinitionBuilder filterBuilder = BeanDefinitionBuilder BeanDefinitionBuilder filterBuilder = BeanDefinitionBuilder
.rootBeanDefinition(J2eePreAuthenticatedProcessingFilter.class); .rootBeanDefinition(J2eePreAuthenticatedProcessingFilter.class);
filterBuilder.getRawBeanDefinition().setSource(this.pc.extractSource(jeeElt)); filterBuilder.getRawBeanDefinition().setSource(this.pc.extractSource(jeeElt));
filterBuilder.addPropertyValue("authenticationManager", authManager); filterBuilder.addPropertyValue("authenticationManager", authManager);
filterBuilder.addPropertyValue("securityContextHolderStrategy", filterBuilder.addPropertyValue("securityContextHolderStrategy",
authenticationFilterSecurityContextHolderStrategyRef); authenticationFilterSecurityContextHolderStrategyRef);
BeanDefinitionBuilder adsBldr = BeanDefinitionBuilder BeanDefinitionBuilder adsBldr = BeanDefinitionBuilder
.rootBeanDefinition(J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.class); .rootBeanDefinition(J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.class);
adsBldr.addPropertyValue("userRoles2GrantedAuthoritiesMapper", adsBldr.addPropertyValue("userRoles2GrantedAuthoritiesMapper",
new RootBeanDefinition(SimpleAttributes2GrantedAuthoritiesMapper.class)); new RootBeanDefinition(SimpleAttributes2GrantedAuthoritiesMapper.class));
String roles = jeeElt.getAttribute(ATT_MAPPABLE_ROLES); String roles = jeeElt.getAttribute(ATT_MAPPABLE_ROLES);
@ -697,8 +699,8 @@ final class AuthenticationConfigBuilder {
rolesBuilder.addConstructorArgValue(roles); rolesBuilder.addConstructorArgValue(roles);
rolesBuilder.setFactoryMethod("commaDelimitedListToSet"); rolesBuilder.setFactoryMethod("commaDelimitedListToSet");
RootBeanDefinition mappableRolesRetriever = new RootBeanDefinition(SimpleMappableAttributesRetriever.class); RootBeanDefinition mappableRolesRetriever = new RootBeanDefinition(SimpleMappableAttributesRetriever.class);
mappableRolesRetriever.getPropertyValues().addPropertyValue("mappableAttributes", mappableRolesRetriever.getPropertyValues()
rolesBuilder.getBeanDefinition()); .addPropertyValue("mappableAttributes", rolesBuilder.getBeanDefinition());
adsBldr.addPropertyValue("mappableRolesRetriever", mappableRolesRetriever); adsBldr.addPropertyValue("mappableRolesRetriever", mappableRolesRetriever);
filterBuilder.addPropertyValue("authenticationDetailsSource", adsBldr.getBeanDefinition()); filterBuilder.addPropertyValue("authenticationDetailsSource", adsBldr.getBeanDefinition());
filter = (RootBeanDefinition) filterBuilder.getBeanDefinition(); filter = (RootBeanDefinition) filterBuilder.getBeanDefinition();
@ -733,11 +735,11 @@ final class AuthenticationConfigBuilder {
this.logger.info("No login page configured. The default internal one will be used. Use the '" this.logger.info("No login page configured. The default internal one will be used. Use the '"
+ FormLoginBeanDefinitionParser.ATT_LOGIN_PAGE + "' attribute to set the URL of the login page."); + FormLoginBeanDefinitionParser.ATT_LOGIN_PAGE + "' attribute to set the URL of the login page.");
BeanDefinitionBuilder loginPageFilter = BeanDefinitionBuilder BeanDefinitionBuilder loginPageFilter = BeanDefinitionBuilder
.rootBeanDefinition(DefaultLoginPageGeneratingFilter.class); .rootBeanDefinition(DefaultLoginPageGeneratingFilter.class);
loginPageFilter.addPropertyValue("resolveHiddenInputs", new CsrfTokenHiddenInputFunction()); loginPageFilter.addPropertyValue("resolveHiddenInputs", new CsrfTokenHiddenInputFunction());
BeanDefinitionBuilder logoutPageFilter = BeanDefinitionBuilder BeanDefinitionBuilder logoutPageFilter = BeanDefinitionBuilder
.rootBeanDefinition(DefaultLogoutPageGeneratingFilter.class); .rootBeanDefinition(DefaultLogoutPageGeneratingFilter.class);
logoutPageFilter.addPropertyValue("resolveHiddenInputs", new CsrfTokenHiddenInputFunction()); logoutPageFilter.addPropertyValue("resolveHiddenInputs", new CsrfTokenHiddenInputFunction());
if (this.formFilterId != null) { if (this.formFilterId != null) {
loginPageFilter.addConstructorArgReference(this.formFilterId); loginPageFilter.addConstructorArgReference(this.formFilterId);
@ -856,10 +858,10 @@ final class AuthenticationConfigBuilder {
this.anonymousFilter = new RootBeanDefinition(AnonymousAuthenticationFilter.class); this.anonymousFilter = new RootBeanDefinition(AnonymousAuthenticationFilter.class);
this.anonymousFilter.getConstructorArgumentValues().addIndexedArgumentValue(0, key); this.anonymousFilter.getConstructorArgumentValues().addIndexedArgumentValue(0, key);
this.anonymousFilter.getConstructorArgumentValues().addIndexedArgumentValue(1, username); this.anonymousFilter.getConstructorArgumentValues().addIndexedArgumentValue(1, username);
this.anonymousFilter.getConstructorArgumentValues().addIndexedArgumentValue(2, this.anonymousFilter.getConstructorArgumentValues()
AuthorityUtils.commaSeparatedStringToAuthorityList(grantedAuthority)); .addIndexedArgumentValue(2, AuthorityUtils.commaSeparatedStringToAuthorityList(grantedAuthority));
this.anonymousFilter.getPropertyValues().addPropertyValue("securityContextHolderStrategy", this.anonymousFilter.getPropertyValues()
authenticationFilterSecurityContextHolderStrategyRef); .addPropertyValue("securityContextHolderStrategy", authenticationFilterSecurityContextHolderStrategyRef);
this.anonymousFilter.setSource(source); this.anonymousFilter.setSource(source);
RootBeanDefinition anonymousProviderBean = new RootBeanDefinition(AnonymousAuthenticationProvider.class); RootBeanDefinition anonymousProviderBean = new RootBeanDefinition(AnonymousAuthenticationProvider.class);
anonymousProviderBean.getConstructorArgumentValues().addIndexedArgumentValue(0, key); anonymousProviderBean.getConstructorArgumentValues().addIndexedArgumentValue(0, key);
@ -890,16 +892,16 @@ final class AuthenticationConfigBuilder {
private BeanMetadataElement createAccessDeniedHandler(Element element, ParserContext pc) { private BeanMetadataElement createAccessDeniedHandler(Element element, ParserContext pc) {
Element accessDeniedElt = DomUtils.getChildElementByTagName(element, Elements.ACCESS_DENIED_HANDLER); Element accessDeniedElt = DomUtils.getChildElementByTagName(element, Elements.ACCESS_DENIED_HANDLER);
BeanDefinitionBuilder accessDeniedHandler = BeanDefinitionBuilder BeanDefinitionBuilder accessDeniedHandler = BeanDefinitionBuilder
.rootBeanDefinition(AccessDeniedHandlerImpl.class); .rootBeanDefinition(AccessDeniedHandlerImpl.class);
if (accessDeniedElt != null) { if (accessDeniedElt != null) {
String errorPage = accessDeniedElt.getAttribute("error-page"); String errorPage = accessDeniedElt.getAttribute("error-page");
String ref = accessDeniedElt.getAttribute("ref"); String ref = accessDeniedElt.getAttribute("ref");
if (StringUtils.hasText(errorPage)) { if (StringUtils.hasText(errorPage)) {
if (StringUtils.hasText(ref)) { if (StringUtils.hasText(ref)) {
pc.getReaderContext() pc.getReaderContext()
.error("The attribute " + ATT_ACCESS_DENIED_ERROR_PAGE .error("The attribute " + ATT_ACCESS_DENIED_ERROR_PAGE
+ " cannot be used together with the 'ref' attribute within <" + " cannot be used together with the 'ref' attribute within <"
+ Elements.ACCESS_DENIED_HANDLER + ">", pc.extractSource(accessDeniedElt)); + Elements.ACCESS_DENIED_HANDLER + ">", pc.extractSource(accessDeniedElt));
} }
accessDeniedHandler.addPropertyValue("errorPage", errorPage); accessDeniedHandler.addPropertyValue("errorPage", errorPage);
@ -916,10 +918,10 @@ final class AuthenticationConfigBuilder {
return this.defaultDeniedHandlerMappings.values().iterator().next(); return this.defaultDeniedHandlerMappings.values().iterator().next();
} }
accessDeniedHandler = BeanDefinitionBuilder accessDeniedHandler = BeanDefinitionBuilder
.rootBeanDefinition(RequestMatcherDelegatingAccessDeniedHandler.class); .rootBeanDefinition(RequestMatcherDelegatingAccessDeniedHandler.class);
accessDeniedHandler.addConstructorArgValue(this.defaultDeniedHandlerMappings); accessDeniedHandler.addConstructorArgValue(this.defaultDeniedHandlerMappings);
accessDeniedHandler accessDeniedHandler
.addConstructorArgValue(BeanDefinitionBuilder.rootBeanDefinition(AccessDeniedHandlerImpl.class)); .addConstructorArgValue(BeanDefinitionBuilder.rootBeanDefinition(AccessDeniedHandlerImpl.class));
return accessDeniedHandler.getBeanDefinition(); return accessDeniedHandler.getBeanDefinition();
} }
@ -935,7 +937,7 @@ final class AuthenticationConfigBuilder {
return this.defaultEntryPointMappings.values().iterator().next(); return this.defaultEntryPointMappings.values().iterator().next();
} }
BeanDefinitionBuilder delegatingEntryPoint = BeanDefinitionBuilder BeanDefinitionBuilder delegatingEntryPoint = BeanDefinitionBuilder
.rootBeanDefinition(DelegatingAuthenticationEntryPoint.class); .rootBeanDefinition(DelegatingAuthenticationEntryPoint.class);
delegatingEntryPoint.addConstructorArgValue(this.defaultEntryPointMappings); delegatingEntryPoint.addConstructorArgValue(this.defaultEntryPointMappings);
return delegatingEntryPoint.getBeanDefinition(); return delegatingEntryPoint.getBeanDefinition();
} }
@ -951,9 +953,9 @@ final class AuthenticationConfigBuilder {
// is used if no openID login page // is used if no openID login page
// has been set. // has been set.
if (this.formLoginPage != null && this.openIDLoginPage != null) { if (this.formLoginPage != null && this.openIDLoginPage != null) {
this.pc.getReaderContext().error( this.pc.getReaderContext()
"Only one login-page can be defined, either for OpenID or form-login, " + "but not both.", .error("Only one login-page can be defined, either for OpenID or form-login, " + "but not both.",
this.pc.extractSource(openIDLoginElt)); this.pc.extractSource(openIDLoginElt));
} }
if (this.formFilterId != null && this.openIDLoginPage == null) { if (this.formFilterId != null && this.openIDLoginPage == null) {
// If form login was enabled through element and Oauth2 login was enabled from // If form login was enabled through element and Oauth2 login was enabled from
@ -980,10 +982,11 @@ final class AuthenticationConfigBuilder {
if (this.oauth2LoginEntryPoint != null) { if (this.oauth2LoginEntryPoint != null) {
return this.oauth2LoginEntryPoint; return this.oauth2LoginEntryPoint;
} }
this.pc.getReaderContext().error("No AuthenticationEntryPoint could be established. Please " this.pc.getReaderContext()
+ "make sure you have a login mechanism configured through the namespace (such as form-login) or " .error("No AuthenticationEntryPoint could be established. Please "
+ "specify a custom AuthenticationEntryPoint with the '" + ATT_ENTRY_POINT_REF + "' attribute ", + "make sure you have a login mechanism configured through the namespace (such as form-login) or "
this.pc.extractSource(this.httpElt)); + "specify a custom AuthenticationEntryPoint with the '" + ATT_ENTRY_POINT_REF + "' attribute ",
this.pc.extractSource(this.httpElt));
return null; return null;
} }
@ -1025,8 +1028,8 @@ final class AuthenticationConfigBuilder {
SecurityFilters.OAUTH2_AUTHORIZATION_REQUEST_FILTER)); SecurityFilters.OAUTH2_AUTHORIZATION_REQUEST_FILTER));
} }
if (this.openIDFilterId != null) { if (this.openIDFilterId != null) {
filters.add( filters
new OrderDecorator(new RuntimeBeanReference(this.openIDFilterId), SecurityFilters.OPENID_FILTER)); .add(new OrderDecorator(new RuntimeBeanReference(this.openIDFilterId), SecurityFilters.OPENID_FILTER));
} }
if (this.loginPageGenerationFilter != null) { if (this.loginPageGenerationFilter != null) {
filters.add(new OrderDecorator(this.loginPageGenerationFilter, SecurityFilters.LOGIN_PAGE_FILTER)); filters.add(new OrderDecorator(this.loginPageGenerationFilter, SecurityFilters.LOGIN_PAGE_FILTER));

View File

@ -73,13 +73,14 @@ class AuthorizationFilterParser implements BeanDefinitionParser {
@Override @Override
public BeanDefinition parse(Element element, ParserContext parserContext) { public BeanDefinition parse(Element element, ParserContext parserContext) {
if (!isUseExpressions(element)) { if (!isUseExpressions(element)) {
parserContext.getReaderContext().error("AuthorizationManager must be used with `use-expressions=\"true\"", parserContext.getReaderContext()
element); .error("AuthorizationManager must be used with `use-expressions=\"true\"", element);
return null; return null;
} }
if (StringUtils.hasText(element.getAttribute(ATT_ACCESS_DECISION_MANAGER_REF))) { if (StringUtils.hasText(element.getAttribute(ATT_ACCESS_DECISION_MANAGER_REF))) {
parserContext.getReaderContext().error( parserContext.getReaderContext()
"AuthorizationManager cannot be used in conjunction with `access-decision-manager-ref`", element); .error("AuthorizationManager cannot be used in conjunction with `access-decision-manager-ref`",
element);
return null; return null;
} }
this.authorizationManagerRef = createAuthorizationManager(element, parserContext); this.authorizationManagerRef = createAuthorizationManager(element, parserContext);
@ -90,8 +91,8 @@ class AuthorizationFilterParser implements BeanDefinitionParser {
filterBuilder.addPropertyValue("shouldFilterAllDispatcherTypes", Boolean.TRUE); filterBuilder.addPropertyValue("shouldFilterAllDispatcherTypes", Boolean.TRUE);
} }
BeanDefinition filter = filterBuilder BeanDefinition filter = filterBuilder
.addPropertyValue("securityContextHolderStrategy", this.securityContextHolderStrategy) .addPropertyValue("securityContextHolderStrategy", this.securityContextHolderStrategy)
.getBeanDefinition(); .getBeanDefinition();
String id = element.getAttribute(AbstractBeanDefinitionParser.ID_ATTRIBUTE); String id = element.getAttribute(AbstractBeanDefinitionParser.ID_ATTRIBUTE);
if (StringUtils.hasText(id)) { if (StringUtils.hasText(id)) {
parserContext.registerComponent(new BeanComponentDefinition(filter, id)); parserContext.registerComponent(new BeanComponentDefinition(filter, id));
@ -121,14 +122,14 @@ class AuthorizationFilterParser implements BeanDefinitionParser {
for (Element interceptMessage : interceptMessages) { for (Element interceptMessage : interceptMessages) {
String accessExpression = interceptMessage.getAttribute(ATT_ACCESS); String accessExpression = interceptMessage.getAttribute(ATT_ACCESS);
BeanDefinitionBuilder authorizationManager = BeanDefinitionBuilder BeanDefinitionBuilder authorizationManager = BeanDefinitionBuilder
.rootBeanDefinition(WebExpressionAuthorizationManager.class); .rootBeanDefinition(WebExpressionAuthorizationManager.class);
authorizationManager.addPropertyReference("expressionHandler", expressionHandlerRef); authorizationManager.addPropertyReference("expressionHandler", expressionHandlerRef);
authorizationManager.addConstructorArgValue(accessExpression); authorizationManager.addConstructorArgValue(accessExpression);
BeanMetadataElement matcher = createMatcher(matcherType, interceptMessage, parserContext); BeanMetadataElement matcher = createMatcher(matcherType, interceptMessage, parserContext);
matcherToExpression.put(matcher, authorizationManager.getBeanDefinition()); matcherToExpression.put(matcher, authorizationManager.getBeanDefinition());
} }
BeanDefinitionBuilder mds = BeanDefinitionBuilder BeanDefinitionBuilder mds = BeanDefinitionBuilder
.rootBeanDefinition(RequestMatcherDelegatingAuthorizationManagerFactory.class); .rootBeanDefinition(RequestMatcherDelegatingAuthorizationManagerFactory.class);
mds.setFactoryMethod("createRequestMatcherDelegatingAuthorizationManager"); mds.setFactoryMethod("createRequestMatcherDelegatingAuthorizationManager");
mds.addConstructorArgValue(matcherToExpression); mds.addConstructorArgValue(matcherToExpression);
return context.registerWithGeneratedName(mds.getBeanDefinition()); return context.registerWithGeneratedName(mds.getBeanDefinition());
@ -150,8 +151,9 @@ class AuthorizationFilterParser implements BeanDefinitionParser {
servletPath = null; servletPath = null;
} }
else if (!MatcherType.mvc.equals(matcherType)) { else if (!MatcherType.mvc.equals(matcherType)) {
parserContext.getReaderContext().error( parserContext.getReaderContext()
ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'", urlElt); .error(ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'",
urlElt);
} }
return hasMatcherRef ? new RuntimeBeanReference(matcherRef) return hasMatcherRef ? new RuntimeBeanReference(matcherRef)
: matcherType.createMatcher(parserContext, path, method, servletPath); : matcherType.createMatcher(parserContext, path, method, servletPath);
@ -175,9 +177,9 @@ class AuthorizationFilterParser implements BeanDefinitionParser {
private static AuthorizationManager<HttpServletRequest> createRequestMatcherDelegatingAuthorizationManager( private static AuthorizationManager<HttpServletRequest> createRequestMatcherDelegatingAuthorizationManager(
Map<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> beans) { Map<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> beans) {
RequestMatcherDelegatingAuthorizationManager.Builder builder = RequestMatcherDelegatingAuthorizationManager RequestMatcherDelegatingAuthorizationManager.Builder builder = RequestMatcherDelegatingAuthorizationManager
.builder(); .builder();
for (Map.Entry<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> entry : beans for (Map.Entry<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> entry : beans
.entrySet()) { .entrySet()) {
builder.add(entry.getKey(), entry.getValue()); builder.add(entry.getKey(), entry.getValue());
} }
return builder.add(AnyRequestMatcher.INSTANCE, AuthenticatedAuthorizationManager.authenticated()).build(); return builder.add(AnyRequestMatcher.INSTANCE, AuthenticatedAuthorizationManager.authenticated()).build();

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