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

@ -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

@ -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,8 +77,8 @@ 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"),

View File

@ -249,9 +249,11 @@ public class AclImplTests {
.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));

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
@ -182,10 +182,10 @@ public class AclImplementationSecurityCheckTests {
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

@ -47,8 +47,10 @@ 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);
} }
@ -72,12 +74,15 @@ public class PermissionTests {
.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

@ -132,7 +132,8 @@ 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()
.setAuthentication(new AnonymousAuthenticationToken("key", "principal",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); 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"));

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_");
} }
@ -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
@ -135,7 +136,8 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
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

@ -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() {

View File

@ -80,7 +80,8 @@ 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"))
.andExpect(
authenticated().withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_EXTRA")))); authenticated().withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_EXTRA"))));
} }
@ -91,7 +92,8 @@ public class LdapBindAuthenticationManagerFactoryITests {
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"))
.andExpect(
authenticated().withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_CUSTOM")))); authenticated().withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_CUSTOM"))));
} }

View File

@ -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

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()
.fatal("You cannot use a spring-security-2.0.xsd or spring-security-3.0.xsd or "
+ "spring-security-3.1.xsd schema or spring-security-3.2.xsd schema or spring-security-4.0.xsd schema " + "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); + "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,7 +142,8 @@ 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()
.fatal("Security namespace does not support decoration of "
+ ((node instanceof Element) ? "element" : "attribute") + " [" + name + "]", node); + ((node instanceof Element) ? "element" : "attribute") + " [" + name + "]", node);
} }

View File

@ -184,7 +184,8 @@ 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()
.getBeanDefinition(beanName)
.isPrimary()) { .isPrimary()) {
list.add(beanName); list.add(beanName);
} }

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

@ -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

@ -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

@ -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

@ -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}.
* *

View File

@ -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;

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

View File

@ -58,7 +58,8 @@ 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()
.addMapping(0, new UrlMapping(matcher,
SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll))); SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll)));
} }
else { else {

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

@ -402,7 +402,8 @@ 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()
.getSharedObject(ApplicationContext.class)
.getBean(names[0]); .getBean(names[0]);
} }
return null; return null;
@ -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;
} }

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

@ -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}.
* *

View File

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

View File

@ -61,7 +61,10 @@ 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();

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,13 +124,15 @@ 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()
.error("authentication-provider element cannot be used with other attributes "
+ "when using 'ref' attribute", pc.extractSource(element)); + "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()
.error("authentication-provider element cannot have child elements when used "
+ "with 'ref' attribute", pc.extractSource(element)); + "with 'ref' attribute", pc.extractSource(element));
} }
} }

View File

@ -46,7 +46,8 @@ 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()
.error(ATT_DATA_SOURCE + " is required for " + Elements.JDBC_USER_SERVICE,
parserContext.extractSource(element)); parserContext.extractSource(element));
} }
String usersQuery = element.getAttribute(ATT_USERS_BY_USERNAME_QUERY); String usersQuery = element.getAttribute(ATT_USERS_BY_USERNAME_QUERY);

View File

@ -315,10 +315,11 @@ 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()
.addPropertyValue("securityContextHolderStrategy",
authenticationFilterSecurityContextHolderStrategyRef); 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);
@ -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
@ -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);
@ -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 = ".*";
@ -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));
} }
} }
@ -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();
@ -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);
@ -951,8 +953,8 @@ 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) {
@ -980,7 +982,8 @@ 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()
.error("No AuthenticationEntryPoint could be established. Please "
+ "make sure you have a login mechanism configured through the namespace (such as form-login) or " + "make sure you have a login mechanism configured through the namespace (such as form-login) or "
+ "specify a custom AuthenticationEntryPoint with the '" + ATT_ENTRY_POINT_REF + "' attribute ", + "specify a custom AuthenticationEntryPoint with the '" + ATT_ENTRY_POINT_REF + "' attribute ",
this.pc.extractSource(this.httpElt)); this.pc.extractSource(this.httpElt));
@ -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);
@ -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);

View File

@ -53,13 +53,14 @@ public class FilterChainMapBeanDefinitionDecorator implements BeanDefinitionDeco
String path = chain.getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN); String path = chain.getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN);
String filters = chain.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS); String filters = chain.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS);
if (!StringUtils.hasText(path)) { if (!StringUtils.hasText(path)) {
parserContext.getReaderContext().error( parserContext.getReaderContext()
"The attribute '" + HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN + "' must not be empty", .error("The attribute '" + HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN
elt); + "' must not be empty", elt);
} }
if (!StringUtils.hasText(filters)) { if (!StringUtils.hasText(filters)) {
parserContext.getReaderContext().error( parserContext.getReaderContext()
"The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS + "'must not be empty", elt); .error("The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS + "'must not be empty",
elt);
} }
BeanDefinition matcher = matcherType.createMatcher(parserContext, path, null); BeanDefinition matcher = matcherType.createMatcher(parserContext, path, null);
if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) { if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) {

View File

@ -69,17 +69,18 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
// Check for attributes that aren't allowed in this context // Check for attributes that aren't allowed in this context
for (Element elt : interceptUrls) { for (Element elt : interceptUrls) {
if (StringUtils.hasLength(elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL))) { if (StringUtils.hasLength(elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL))) {
parserContext.getReaderContext().error("The attribute '" parserContext.getReaderContext()
+ HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL + "' isn't allowed here.", elt); .error("The attribute '" + HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL
+ "' isn't allowed here.", elt);
} }
if (StringUtils.hasLength(elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS))) { if (StringUtils.hasLength(elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS))) {
parserContext.getReaderContext().error( parserContext.getReaderContext()
"The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS + "' isn't allowed here.", .error("The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS + "' isn't allowed here.",
elt); elt);
} }
if (StringUtils.hasLength(elt.getAttribute(ATT_SERVLET_PATH))) { if (StringUtils.hasLength(elt.getAttribute(ATT_SERVLET_PATH))) {
parserContext.getReaderContext().error("The attribute '" + ATT_SERVLET_PATH + "' isn't allowed here.", parserContext.getReaderContext()
elt); .error("The attribute '" + ATT_SERVLET_PATH + "' isn't allowed here.", elt);
} }
} }
BeanDefinition mds = createSecurityMetadataSource(interceptUrls, false, element, parserContext); BeanDefinition mds = createSecurityMetadataSource(interceptUrls, false, element, parserContext);
@ -159,8 +160,8 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
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() + "'", .error(ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'",
urlElt); urlElt);
} }
BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference(matcherRef) BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference(matcherRef)

View File

@ -161,8 +161,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
parseHeaderElements(element); parseHeaderElements(element);
boolean noWriters = this.headerWriters.isEmpty(); boolean noWriters = this.headerWriters.isEmpty();
if (disabled && !noWriters) { if (disabled && !noWriters) {
parserContext.getReaderContext().error("Cannot specify <headers disabled=\"true\"> with child elements.", parserContext.getReaderContext()
element); .error("Cannot specify <headers disabled=\"true\"> with child elements.", element);
} }
else if (noWriters) { else if (noWriters) {
return null; return null;
@ -316,8 +316,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
.genericBeanDefinition(ContentSecurityPolicyHeaderWriter.class); .genericBeanDefinition(ContentSecurityPolicyHeaderWriter.class);
String policyDirectives = contentSecurityPolicyElement.getAttribute(ATT_POLICY_DIRECTIVES); String policyDirectives = contentSecurityPolicyElement.getAttribute(ATT_POLICY_DIRECTIVES);
if (!StringUtils.hasText(policyDirectives)) { if (!StringUtils.hasText(policyDirectives)) {
context.getReaderContext().error(ATT_POLICY_DIRECTIVES + " requires a 'value' to be set.", context.getReaderContext()
contentSecurityPolicyElement); .error(ATT_POLICY_DIRECTIVES + " requires a 'value' to be set.", contentSecurityPolicyElement);
} }
else { else {
headersWriter.addConstructorArgValue(policyDirectives); headersWriter.addConstructorArgValue(policyDirectives);
@ -360,8 +360,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
.genericBeanDefinition(FeaturePolicyHeaderWriter.class); .genericBeanDefinition(FeaturePolicyHeaderWriter.class);
String policyDirectives = featurePolicyElement.getAttribute(ATT_POLICY_DIRECTIVES); String policyDirectives = featurePolicyElement.getAttribute(ATT_POLICY_DIRECTIVES);
if (!StringUtils.hasText(policyDirectives)) { if (!StringUtils.hasText(policyDirectives)) {
context.getReaderContext().error(ATT_POLICY_DIRECTIVES + " requires a 'value' to be set.", context.getReaderContext()
featurePolicyElement); .error(ATT_POLICY_DIRECTIVES + " requires a 'value' to be set.", featurePolicyElement);
} }
else { else {
headersWriter.addConstructorArgValue(policyDirectives); headersWriter.addConstructorArgValue(policyDirectives);
@ -460,8 +460,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
} }
private void attrNotAllowed(ParserContext context, String attrName, String otherAttrName, Element element) { private void attrNotAllowed(ParserContext context, String attrName, String otherAttrName, Element element) {
context.getReaderContext().error("Only one of '" + attrName + "' or '" + otherAttrName + "' can be set.", context.getReaderContext()
element); .error("Only one of '" + attrName + "' or '" + otherAttrName + "' can be set.", element);
} }
private void parseHeaderElements(Element element) { private void parseHeaderElements(Element element) {
@ -531,8 +531,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
String strategyRef = getAttribute(frameElement, ATT_REF, null); String strategyRef = getAttribute(frameElement, ATT_REF, null);
String strategy = getAttribute(frameElement, ATT_STRATEGY, null); String strategy = getAttribute(frameElement, ATT_STRATEGY, null);
if (StringUtils.hasText(strategy) && StringUtils.hasText(strategyRef)) { if (StringUtils.hasText(strategy) && StringUtils.hasText(strategyRef)) {
parserContext.getReaderContext().error("Only one of 'strategy' or 'strategy-ref' can be set.", parserContext.getReaderContext()
frameElement); .error("Only one of 'strategy' or 'strategy-ref' can be set.", frameElement);
return; return;
} }
if (strategyRef != null) { if (strategyRef != null) {
@ -554,8 +554,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser {
builder.addConstructorArgValue(new StaticAllowFromStrategy(new URI(value))); builder.addConstructorArgValue(new StaticAllowFromStrategy(new URI(value)));
} }
catch (URISyntaxException ex) { catch (URISyntaxException ex) {
parserContext.getReaderContext().error("'value' attribute doesn't represent a valid URI.", frameElement, parserContext.getReaderContext()
ex); .error("'value' attribute doesn't represent a valid URI.", frameElement, ex);
} }
return; return;
} }

View File

@ -436,9 +436,8 @@ class HttpConfigurationBuilder {
if (sessionControlEnabled) { if (sessionControlEnabled) {
if (StringUtils.hasText(sessionAuthStratRef)) { if (StringUtils.hasText(sessionAuthStratRef)) {
this.pc.getReaderContext() this.pc.getReaderContext()
.error(ATT_SESSION_AUTH_STRATEGY_REF + " attribute cannot be used" .error(ATT_SESSION_AUTH_STRATEGY_REF + " attribute cannot be used" + " in combination with <"
+ " in combination with <" + Elements.CONCURRENT_SESSIONS + ">", + Elements.CONCURRENT_SESSIONS + ">", this.pc.extractSource(sessionCtrlElt));
this.pc.extractSource(sessionCtrlElt));
} }
createConcurrencyControlFilterAndSessionRegistry(sessionCtrlElt); createConcurrencyControlFilterAndSessionRegistry(sessionCtrlElt);
} }
@ -448,8 +447,9 @@ class HttpConfigurationBuilder {
sessionFixationAttribute = OPT_CHANGE_SESSION_ID; sessionFixationAttribute = OPT_CHANGE_SESSION_ID;
} }
else if (StringUtils.hasText(sessionAuthStratRef)) { else if (StringUtils.hasText(sessionAuthStratRef)) {
this.pc.getReaderContext().error(ATT_SESSION_FIXATION_PROTECTION + " attribute cannot be used" this.pc.getReaderContext()
+ " in combination with " + ATT_SESSION_AUTH_STRATEGY_REF, this.pc.extractSource(sessionMgmtElt)); .error(ATT_SESSION_FIXATION_PROTECTION + " attribute cannot be used" + " in combination with "
+ ATT_SESSION_AUTH_STRATEGY_REF, this.pc.extractSource(sessionMgmtElt));
} }
if (this.sessionPolicy == SessionCreationPolicy.STATELESS) { if (this.sessionPolicy == SessionCreationPolicy.STATELESS) {
@ -470,7 +470,8 @@ class HttpConfigurationBuilder {
concurrentSessionStrategy = BeanDefinitionBuilder concurrentSessionStrategy = BeanDefinitionBuilder
.rootBeanDefinition(ConcurrentSessionControlAuthenticationStrategy.class); .rootBeanDefinition(ConcurrentSessionControlAuthenticationStrategy.class);
concurrentSessionStrategy.addConstructorArgValue(this.sessionRegistryRef); concurrentSessionStrategy.addConstructorArgValue(this.sessionRegistryRef);
String maxSessions = this.pc.getReaderContext().getEnvironment() String maxSessions = this.pc.getReaderContext()
.getEnvironment()
.resolvePlaceholders(sessionCtrlElt.getAttribute("max-sessions")); .resolvePlaceholders(sessionCtrlElt.getAttribute("max-sessions"));
if (StringUtils.hasText(maxSessions)) { if (StringUtils.hasText(maxSessions)) {
concurrentSessionStrategy.addPropertyValue("maximumSessions", maxSessions); concurrentSessionStrategy.addPropertyValue("maximumSessions", maxSessions);
@ -572,8 +573,8 @@ class HttpConfigurationBuilder {
String expiryUrl = element.getAttribute(ATT_EXPIRY_URL); String expiryUrl = element.getAttribute(ATT_EXPIRY_URL);
String expiredSessionStrategyRef = element.getAttribute(ATT_EXPIRED_SESSION_STRATEGY_REF); String expiredSessionStrategyRef = element.getAttribute(ATT_EXPIRED_SESSION_STRATEGY_REF);
if (StringUtils.hasText(expiryUrl) && StringUtils.hasText(expiredSessionStrategyRef)) { if (StringUtils.hasText(expiryUrl) && StringUtils.hasText(expiredSessionStrategyRef)) {
this.pc.getReaderContext().error( this.pc.getReaderContext()
"Cannot use 'expired-url' attribute and 'expired-session-strategy-ref'" + " attribute together.", .error("Cannot use 'expired-url' attribute and 'expired-session-strategy-ref'" + " attribute together.",
source); source);
} }
if (StringUtils.hasText(expiryUrl)) { if (StringUtils.hasText(expiryUrl)) {
@ -620,7 +621,8 @@ class HttpConfigurationBuilder {
} }
if ("true".equals(provideJaasApi)) { if ("true".equals(provideJaasApi)) {
this.jaasApiFilter = BeanDefinitionBuilder.rootBeanDefinition(JaasApiIntegrationFilter.class) this.jaasApiFilter = BeanDefinitionBuilder.rootBeanDefinition(JaasApiIntegrationFilter.class)
.addPropertyValue("securityContextHolderStrategy", this.holderStrategyRef).getBeanDefinition(); .addPropertyValue("securityContextHolderStrategy", this.holderStrategyRef)
.getBeanDefinition();
} }
} }
@ -633,8 +635,8 @@ class HttpConfigurationBuilder {
BeanDefinitionBuilder metadataSourceBldr = BeanDefinitionBuilder BeanDefinitionBuilder metadataSourceBldr = BeanDefinitionBuilder
.rootBeanDefinition(DefaultFilterInvocationSecurityMetadataSource.class); .rootBeanDefinition(DefaultFilterInvocationSecurityMetadataSource.class);
metadataSourceBldr.addConstructorArgValue(channelRequestMap); metadataSourceBldr.addConstructorArgValue(channelRequestMap);
channelFilter.getPropertyValues().addPropertyValue("securityMetadataSource", channelFilter.getPropertyValues()
metadataSourceBldr.getBeanDefinition()); .addPropertyValue("securityMetadataSource", metadataSourceBldr.getBeanDefinition());
RootBeanDefinition channelDecisionManager = new RootBeanDefinition(ChannelDecisionManagerImpl.class); RootBeanDefinition channelDecisionManager = new RootBeanDefinition(ChannelDecisionManagerImpl.class);
ManagedList<RootBeanDefinition> channelProcessors = new ManagedList<>(3); ManagedList<RootBeanDefinition> channelProcessors = new ManagedList<>(3);
RootBeanDefinition secureChannelProcessor = new RootBeanDefinition(SecureChannelProcessor.class); RootBeanDefinition secureChannelProcessor = new RootBeanDefinition(SecureChannelProcessor.class);
@ -738,7 +740,8 @@ class HttpConfigurationBuilder {
// taglibs etc. // taglibs etc.
BeanDefinition wipe = BeanDefinitionBuilder BeanDefinition wipe = BeanDefinitionBuilder
.rootBeanDefinition(AuthorizationManagerWebInvocationPrivilegeEvaluator.class) .rootBeanDefinition(AuthorizationManagerWebInvocationPrivilegeEvaluator.class)
.addConstructorArgReference(authorizationFilterParser.getAuthorizationManagerRef()).getBeanDefinition(); .addConstructorArgReference(authorizationFilterParser.getAuthorizationManagerRef())
.getBeanDefinition();
this.pc.registerBeanComponent( this.pc.registerBeanComponent(
new BeanComponentDefinition(wipe, this.pc.getReaderContext().generateBeanName(wipe))); new BeanComponentDefinition(wipe, this.pc.getReaderContext().generateBeanName(wipe)));
this.fsi = new RuntimeBeanReference(fsiId); this.fsi = new RuntimeBeanReference(fsiId);
@ -754,7 +757,8 @@ class HttpConfigurationBuilder {
BeanDefinitionBuilder expressionVoter = BeanDefinitionBuilder.rootBeanDefinition(WebExpressionVoter.class); BeanDefinitionBuilder expressionVoter = BeanDefinitionBuilder.rootBeanDefinition(WebExpressionVoter.class);
// Read the expression handler from the FISMS // Read the expression handler from the FISMS
RuntimeBeanReference expressionHandler = (RuntimeBeanReference) securityMds.getConstructorArgumentValues() RuntimeBeanReference expressionHandler = (RuntimeBeanReference) securityMds.getConstructorArgumentValues()
.getArgumentValue(1, RuntimeBeanReference.class).getValue(); .getArgumentValue(1, RuntimeBeanReference.class)
.getValue();
expressionVoter.addPropertyValue("expressionHandler", expressionHandler); expressionVoter.addPropertyValue("expressionHandler", expressionHandler);
voters.add(expressionVoter.getBeanDefinition()); voters.add(expressionVoter.getBeanDefinition());
} }

View File

@ -116,7 +116,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
// Obtain the filter chains and add the new chain to it // Obtain the filter chains and add the new chain to it
BeanDefinition listFactoryBean = pc.getRegistry().getBeanDefinition(BeanIds.FILTER_CHAINS); BeanDefinition listFactoryBean = pc.getRegistry().getBeanDefinition(BeanIds.FILTER_CHAINS);
List<BeanReference> filterChains = (List<BeanReference>) listFactoryBean.getPropertyValues() List<BeanReference> filterChains = (List<BeanReference>) listFactoryBean.getPropertyValues()
.getPropertyValue("sourceList").getValue(); .getPropertyValue("sourceList")
.getValue();
filterChains.add(createFilterChain(element, pc)); filterChains.add(createFilterChain(element, pc));
pc.popAndRegisterContainingComponent(); pc.popAndRegisterContainingComponent();
return null; return null;
@ -131,7 +132,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
validateSecuredFilterChainElement(element, pc); validateSecuredFilterChainElement(element, pc);
for (int i = 0; i < element.getChildNodes().getLength(); i++) { for (int i = 0; i < element.getChildNodes().getLength(); i++) {
if (element.getChildNodes().item(i) instanceof Element) { if (element.getChildNodes().item(i) instanceof Element) {
pc.getReaderContext().error("If you are using <http> to define an unsecured pattern, " pc.getReaderContext()
.error("If you are using <http> to define an unsecured pattern, "
+ "it cannot contain child elements.", pc.extractSource(element)); + "it cannot contain child elements.", pc.extractSource(element));
} }
} }
@ -188,8 +190,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
String filterChainPattern = element.getAttribute(ATT_PATH_PATTERN); String filterChainPattern = element.getAttribute(ATT_PATH_PATTERN);
if (StringUtils.hasText(requestMatcherRef)) { if (StringUtils.hasText(requestMatcherRef)) {
if (StringUtils.hasText(filterChainPattern)) { if (StringUtils.hasText(filterChainPattern)) {
pc.getReaderContext().error( pc.getReaderContext()
"You can't define a pattern and a request-matcher-ref for the " + "same filter chain", .error("You can't define a pattern and a request-matcher-ref for the " + "same filter chain",
pc.extractSource(element)); pc.extractSource(element));
} }
filterChainMatcher = new RuntimeBeanReference(requestMatcherRef); filterChainMatcher = new RuntimeBeanReference(requestMatcherRef);
@ -254,8 +256,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
RootBeanDefinition clearCredentials = new RootBeanDefinition( RootBeanDefinition clearCredentials = new RootBeanDefinition(
ClearCredentialsMethodInvokingFactoryBean.class); ClearCredentialsMethodInvokingFactoryBean.class);
clearCredentials.getPropertyValues().addPropertyValue("targetObject", parentAuthManager); clearCredentials.getPropertyValues().addPropertyValue("targetObject", parentAuthManager);
clearCredentials.getPropertyValues().addPropertyValue("targetMethod", clearCredentials.getPropertyValues()
"isEraseCredentialsAfterAuthentication"); .addPropertyValue("targetMethod", "isEraseCredentialsAfterAuthentication");
authManager.addPropertyValue("eraseCredentialsAfterAuthentication", clearCredentials); authManager.addPropertyValue("eraseCredentialsAfterAuthentication", clearCredentials);
} }
else { else {
@ -265,8 +267,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
pc.registerBeanComponent(new BeanComponentDefinition(amfb, amfbId)); pc.registerBeanComponent(new BeanComponentDefinition(amfb, amfbId));
RootBeanDefinition clearCredentials = new RootBeanDefinition(MethodInvokingFactoryBean.class); RootBeanDefinition clearCredentials = new RootBeanDefinition(MethodInvokingFactoryBean.class);
clearCredentials.getPropertyValues().addPropertyValue("targetObject", new RuntimeBeanReference(amfbId)); clearCredentials.getPropertyValues().addPropertyValue("targetObject", new RuntimeBeanReference(amfbId));
clearCredentials.getPropertyValues().addPropertyValue("targetMethod", clearCredentials.getPropertyValues()
"isEraseCredentialsAfterAuthentication"); .addPropertyValue("targetMethod", "isEraseCredentialsAfterAuthentication");
authManager.addConstructorArgValue(new RuntimeBeanReference(amfbId)); authManager.addConstructorArgValue(new RuntimeBeanReference(amfbId));
authManager.addPropertyValue("eraseCredentialsAfterAuthentication", clearCredentials); authManager.addPropertyValue("eraseCredentialsAfterAuthentication", clearCredentials);
} }
@ -312,7 +314,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
} }
RuntimeBeanReference bean = new RuntimeBeanReference(ref); RuntimeBeanReference bean = new RuntimeBeanReference(ref);
if (WebConfigUtils.countNonEmpty(new String[] { after, before, position }) != 1) { if (WebConfigUtils.countNonEmpty(new String[] { after, before, position }) != 1) {
pc.getReaderContext().error("A single '" + ATT_AFTER + "', '" + ATT_BEFORE + "', or '" + ATT_POSITION pc.getReaderContext()
.error("A single '" + ATT_AFTER + "', '" + ATT_BEFORE + "', or '" + ATT_POSITION
+ "' attribute must be supplied", pc.extractSource(elt)); + "' attribute must be supplied", pc.extractSource(elt));
} }
if (StringUtils.hasText(position)) { if (StringUtils.hasText(position)) {
@ -386,8 +389,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
if (registry.containsBeanDefinition(this.beanName)) { if (registry.containsBeanDefinition(this.beanName)) {
BeanDefinition beanDefinition = registry.getBeanDefinition(this.targetBeanName); BeanDefinition beanDefinition = registry.getBeanDefinition(this.targetBeanName);
beanDefinition.getPropertyValues().add(this.targetPropertyName, beanDefinition.getPropertyValues()
new RuntimeBeanReference(this.beanName)); .add(this.targetPropertyName, new RuntimeBeanReference(this.beanName));
} }
} }

View File

@ -99,8 +99,8 @@ class LogoutBeanDefinitionParser implements BeanDefinitionParser {
builder.addPropertyValue("logoutRequestMatcher", getLogoutRequestMatcher(logoutUrl)); builder.addPropertyValue("logoutRequestMatcher", getLogoutRequestMatcher(logoutUrl));
if (StringUtils.hasText(successHandlerRef)) { if (StringUtils.hasText(successHandlerRef)) {
if (StringUtils.hasText(logoutSuccessUrl)) { if (StringUtils.hasText(logoutSuccessUrl)) {
pc.getReaderContext().error( pc.getReaderContext()
"Use " + ATT_LOGOUT_SUCCESS_URL + " or " + ATT_LOGOUT_HANDLER + ", but not both", .error("Use " + ATT_LOGOUT_SUCCESS_URL + " or " + ATT_LOGOUT_HANDLER + ", but not both",
pc.extractSource(element)); pc.extractSource(element));
} }
builder.addConstructorArgReference(successHandlerRef); builder.addConstructorArgReference(successHandlerRef);

View File

@ -37,8 +37,8 @@ import org.springframework.util.StringUtils;
*/ */
public enum MatcherType { public enum MatcherType {
ant(AntPathRequestMatcher.class), regex(RegexRequestMatcher.class), ciRegex(RegexRequestMatcher.class), mvc( ant(AntPathRequestMatcher.class), regex(RegexRequestMatcher.class), ciRegex(RegexRequestMatcher.class),
MvcRequestMatcher.class); mvc(MvcRequestMatcher.class);
private static final String HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME = "mvcHandlerMappingIntrospector"; private static final String HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME = "mvcHandlerMappingIntrospector";

View File

@ -103,10 +103,12 @@ final class OAuth2ClientBeanDefinitionParser implements BeanDefinitionParser {
this.authorizationRequestRedirectFilter = authorizationRequestRedirectFilterBuilder this.authorizationRequestRedirectFilter = authorizationRequestRedirectFilterBuilder
.addPropertyValue("authorizationRequestRepository", authorizationRequestRepository) .addPropertyValue("authorizationRequestRepository", authorizationRequestRepository)
.addPropertyValue("authorizationRedirectStrategy", authorizationRedirectStrategy) .addPropertyValue("authorizationRedirectStrategy", authorizationRedirectStrategy)
.addPropertyValue("requestCache", this.requestCache).getBeanDefinition(); .addPropertyValue("requestCache", this.requestCache)
.getBeanDefinition();
BeanDefinitionBuilder authorizationCodeGrantFilterBldr = BeanDefinitionBuilder BeanDefinitionBuilder authorizationCodeGrantFilterBldr = BeanDefinitionBuilder
.rootBeanDefinition(OAuth2AuthorizationCodeGrantFilter.class) .rootBeanDefinition(OAuth2AuthorizationCodeGrantFilter.class)
.addConstructorArgValue(clientRegistrationRepository).addConstructorArgValue(authorizedClientRepository) .addConstructorArgValue(clientRegistrationRepository)
.addConstructorArgValue(authorizedClientRepository)
.addConstructorArgValue(this.authenticationManager) .addConstructorArgValue(this.authenticationManager)
.addPropertyValue("authorizationRequestRepository", authorizationRequestRepository); .addPropertyValue("authorizationRequestRepository", authorizationRequestRepository);
if (this.authenticationFilterSecurityContextRepositoryRef != null) { if (this.authenticationFilterSecurityContextRepositoryRef != null) {
@ -118,7 +120,8 @@ final class OAuth2ClientBeanDefinitionParser implements BeanDefinitionParser {
BeanMetadataElement accessTokenResponseClient = getAccessTokenResponseClient(authorizationCodeGrantElt); BeanMetadataElement accessTokenResponseClient = getAccessTokenResponseClient(authorizationCodeGrantElt);
this.authorizationCodeAuthenticationProvider = BeanDefinitionBuilder this.authorizationCodeAuthenticationProvider = BeanDefinitionBuilder
.rootBeanDefinition(OAuth2AuthorizationCodeAuthenticationProvider.class) .rootBeanDefinition(OAuth2AuthorizationCodeAuthenticationProvider.class)
.addConstructorArgValue(accessTokenResponseClient).getBeanDefinition(); .addConstructorArgValue(accessTokenResponseClient)
.getBeanDefinition();
return null; return null;
} }
@ -129,7 +132,8 @@ final class OAuth2ClientBeanDefinitionParser implements BeanDefinitionParser {
if (!StringUtils.isEmpty(authorizationRequestRepositoryRef)) { if (!StringUtils.isEmpty(authorizationRequestRepositoryRef)) {
return new RuntimeBeanReference(authorizationRequestRepositoryRef); return new RuntimeBeanReference(authorizationRequestRepositoryRef);
} }
return BeanDefinitionBuilder.rootBeanDefinition( return BeanDefinitionBuilder
.rootBeanDefinition(
"org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository") "org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository")
.getBeanDefinition(); .getBeanDefinition();
} }
@ -150,7 +154,8 @@ final class OAuth2ClientBeanDefinitionParser implements BeanDefinitionParser {
if (!StringUtils.isEmpty(accessTokenResponseClientRef)) { if (!StringUtils.isEmpty(accessTokenResponseClientRef)) {
return new RuntimeBeanReference(accessTokenResponseClientRef); return new RuntimeBeanReference(accessTokenResponseClientRef);
} }
return BeanDefinitionBuilder.rootBeanDefinition( return BeanDefinitionBuilder
.rootBeanDefinition(
"org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient") "org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient")
.getBeanDefinition(); .getBeanDefinition();
} }

View File

@ -68,13 +68,14 @@ final class OAuth2ClientBeanDefinitionParserUtils {
BeanMetadataElement authorizedClientService) { BeanMetadataElement authorizedClientService) {
if (authorizedClientService == null) { if (authorizedClientService == null) {
authorizedClientService = BeanDefinitionBuilder authorizedClientService = BeanDefinitionBuilder
.rootBeanDefinition( .rootBeanDefinition("org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService")
"org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService") .addConstructorArgValue(clientRegistrationRepository)
.addConstructorArgValue(clientRegistrationRepository).getBeanDefinition(); .getBeanDefinition();
} }
return BeanDefinitionBuilder.rootBeanDefinition( return BeanDefinitionBuilder.rootBeanDefinition(
"org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository") "org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository")
.addConstructorArgValue(authorizedClientService).getBeanDefinition(); .addConstructorArgValue(authorizedClientService)
.getBeanDefinition();
} }
} }

View File

@ -167,7 +167,8 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
BeanMetadataElement authorizationRequestRepository = getAuthorizationRequestRepository(element); BeanMetadataElement authorizationRequestRepository = getAuthorizationRequestRepository(element);
BeanDefinitionBuilder oauth2LoginAuthenticationFilterBuilder = BeanDefinitionBuilder BeanDefinitionBuilder oauth2LoginAuthenticationFilterBuilder = BeanDefinitionBuilder
.rootBeanDefinition(OAuth2LoginAuthenticationFilter.class) .rootBeanDefinition(OAuth2LoginAuthenticationFilter.class)
.addConstructorArgValue(clientRegistrationRepository).addConstructorArgValue(authorizedClientRepository) .addConstructorArgValue(clientRegistrationRepository)
.addConstructorArgValue(authorizedClientRepository)
.addPropertyValue("authorizationRequestRepository", authorizationRequestRepository); .addPropertyValue("authorizationRequestRepository", authorizationRequestRepository);
if (this.sessionStrategy != null) { if (this.sessionStrategy != null) {
oauth2LoginAuthenticationFilterBuilder.addPropertyValue("sessionAuthenticationStrategy", oauth2LoginAuthenticationFilterBuilder.addPropertyValue("sessionAuthenticationStrategy",
@ -185,7 +186,8 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
} }
BeanDefinitionBuilder oauth2LoginAuthenticationProviderBuilder = BeanDefinitionBuilder BeanDefinitionBuilder oauth2LoginAuthenticationProviderBuilder = BeanDefinitionBuilder
.rootBeanDefinition(OAuth2LoginAuthenticationProvider.class) .rootBeanDefinition(OAuth2LoginAuthenticationProvider.class)
.addConstructorArgValue(accessTokenResponseClient).addConstructorArgValue(oauth2UserService); .addConstructorArgValue(accessTokenResponseClient)
.addConstructorArgValue(oauth2UserService);
String userAuthoritiesMapperRef = element.getAttribute(ATT_USER_AUTHORITIES_MAPPER_REF); String userAuthoritiesMapperRef = element.getAttribute(ATT_USER_AUTHORITIES_MAPPER_REF);
if (!StringUtils.isEmpty(userAuthoritiesMapperRef)) { if (!StringUtils.isEmpty(userAuthoritiesMapperRef)) {
oauth2LoginAuthenticationProviderBuilder.addPropertyReference("authoritiesMapper", oauth2LoginAuthenticationProviderBuilder.addPropertyReference("authoritiesMapper",
@ -215,7 +217,8 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
authenticationSuccessHandlerRef); authenticationSuccessHandlerRef);
} }
else { else {
BeanDefinitionBuilder successHandlerBuilder = BeanDefinitionBuilder.rootBeanDefinition( BeanDefinitionBuilder successHandlerBuilder = BeanDefinitionBuilder
.rootBeanDefinition(
"org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler") "org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler")
.addPropertyValue("requestCache", this.requestCache); .addPropertyValue("requestCache", this.requestCache);
oauth2LoginAuthenticationFilterBuilder.addPropertyValue("authenticationSuccessHandler", oauth2LoginAuthenticationFilterBuilder.addPropertyValue("authenticationSuccessHandler",
@ -225,15 +228,18 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
if (!StringUtils.isEmpty(loginPage)) { if (!StringUtils.isEmpty(loginPage)) {
WebConfigUtils.validateHttpRedirect(loginPage, parserContext, source); WebConfigUtils.validateHttpRedirect(loginPage, parserContext, source);
this.oauth2LoginAuthenticationEntryPoint = BeanDefinitionBuilder this.oauth2LoginAuthenticationEntryPoint = BeanDefinitionBuilder
.rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class).addConstructorArgValue(loginPage) .rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class)
.addPropertyValue("portMapper", this.portMapper).addPropertyValue("portResolver", this.portResolver) .addConstructorArgValue(loginPage)
.addPropertyValue("portMapper", this.portMapper)
.addPropertyValue("portResolver", this.portResolver)
.getBeanDefinition(); .getBeanDefinition();
} }
else { else {
Map<RequestMatcher, AuthenticationEntryPoint> entryPoint = getLoginEntryPoint(element); Map<RequestMatcher, AuthenticationEntryPoint> entryPoint = getLoginEntryPoint(element);
if (entryPoint != null) { if (entryPoint != null) {
this.oauth2LoginAuthenticationEntryPoint = BeanDefinitionBuilder this.oauth2LoginAuthenticationEntryPoint = BeanDefinitionBuilder
.rootBeanDefinition(DelegatingAuthenticationEntryPoint.class).addConstructorArgValue(entryPoint) .rootBeanDefinition(DelegatingAuthenticationEntryPoint.class)
.addConstructorArgValue(entryPoint)
.addPropertyValue("defaultEntryPoint", new LoginUrlAuthenticationEntryPoint(DEFAULT_LOGIN_URI)) .addPropertyValue("defaultEntryPoint", new LoginUrlAuthenticationEntryPoint(DEFAULT_LOGIN_URI))
.getBeanDefinition(); .getBeanDefinition();
} }
@ -256,7 +262,8 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
this.authenticationFilterSecurityContextHolderStrategy); this.authenticationFilterSecurityContextHolderStrategy);
// prepare loginlinks // prepare loginlinks
this.oauth2LoginLinks = BeanDefinitionBuilder.rootBeanDefinition(Map.class) this.oauth2LoginLinks = BeanDefinitionBuilder.rootBeanDefinition(Map.class)
.setFactoryMethodOnBean("getLoginLinks", oauth2LoginBeanConfigId).getBeanDefinition(); .setFactoryMethodOnBean("getLoginLinks", oauth2LoginBeanConfigId)
.getBeanDefinition();
return oauth2LoginAuthenticationFilterBuilder.getBeanDefinition(); return oauth2LoginAuthenticationFilterBuilder.getBeanDefinition();
} }
@ -265,7 +272,8 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
if (!StringUtils.isEmpty(authorizationRequestRepositoryRef)) { if (!StringUtils.isEmpty(authorizationRequestRepositoryRef)) {
return new RuntimeBeanReference(authorizationRequestRepositoryRef); return new RuntimeBeanReference(authorizationRequestRepositoryRef);
} }
return BeanDefinitionBuilder.rootBeanDefinition( return BeanDefinitionBuilder
.rootBeanDefinition(
"org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository") "org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository")
.getBeanDefinition(); .getBeanDefinition();
} }
@ -289,7 +297,8 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
BeanMetadataElement oidcUserService = getOidcUserService(element); BeanMetadataElement oidcUserService = getOidcUserService(element);
BeanDefinitionBuilder oidcAuthProviderBuilder = BeanDefinitionBuilder.rootBeanDefinition( BeanDefinitionBuilder oidcAuthProviderBuilder = BeanDefinitionBuilder.rootBeanDefinition(
"org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider") "org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider")
.addConstructorArgValue(accessTokenResponseClient).addConstructorArgValue(oidcUserService); .addConstructorArgValue(accessTokenResponseClient)
.addConstructorArgValue(oidcUserService);
if (!StringUtils.isEmpty(userAuthoritiesMapperRef)) { if (!StringUtils.isEmpty(userAuthoritiesMapperRef)) {
oidcAuthProviderBuilder.addPropertyReference("authoritiesMapper", userAuthoritiesMapperRef); oidcAuthProviderBuilder.addPropertyReference("authoritiesMapper", userAuthoritiesMapperRef);
} }
@ -325,7 +334,8 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
if (!StringUtils.isEmpty(accessTokenResponseClientRef)) { if (!StringUtils.isEmpty(accessTokenResponseClientRef)) {
return new RuntimeBeanReference(accessTokenResponseClientRef); return new RuntimeBeanReference(accessTokenResponseClientRef);
} }
return BeanDefinitionBuilder.rootBeanDefinition( return BeanDefinitionBuilder
.rootBeanDefinition(
"org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient") "org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient")
.getBeanDefinition(); .getBeanDefinition();
} }
@ -395,7 +405,9 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
@Override @Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication; OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication;
if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes() if (!authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationRequest()
.getScopes()
.contains(OidcScopes.OPENID)) { .contains(OidcScopes.OPENID)) {
return null; return null;
} }

View File

@ -147,19 +147,20 @@ final class OAuth2ResourceServerBeanDefinitionParser implements BeanDefinitionPa
void validateConfiguration(Element oauth2ResourceServer, Element jwt, Element opaqueToken, ParserContext pc) { void validateConfiguration(Element oauth2ResourceServer, Element jwt, Element opaqueToken, ParserContext pc) {
if (!oauth2ResourceServer.hasAttribute(AUTHENTICATION_MANAGER_RESOLVER_REF)) { if (!oauth2ResourceServer.hasAttribute(AUTHENTICATION_MANAGER_RESOLVER_REF)) {
if (jwt == null && opaqueToken == null) { if (jwt == null && opaqueToken == null) {
pc.getReaderContext().error("Didn't find authentication-manager-resolver-ref, " pc.getReaderContext()
+ "<jwt>, or <opaque-token>. " + "Please select one.", oauth2ResourceServer); .error("Didn't find authentication-manager-resolver-ref, " + "<jwt>, or <opaque-token>. "
+ "Please select one.", oauth2ResourceServer);
} }
return; return;
} }
if (jwt != null) { if (jwt != null) {
pc.getReaderContext().error( pc.getReaderContext()
"Found <jwt> as well as authentication-manager-resolver-ref. Please select just one.", .error("Found <jwt> as well as authentication-manager-resolver-ref. Please select just one.",
oauth2ResourceServer); oauth2ResourceServer);
} }
if (opaqueToken != null) { if (opaqueToken != null) {
pc.getReaderContext().error( pc.getReaderContext()
"Found <opaque-token> as well as authentication-manager-resolver-ref. Please select just one.", .error("Found <opaque-token> as well as authentication-manager-resolver-ref. Please select just one.",
oauth2ResourceServer); oauth2ResourceServer);
} }
} }
@ -277,7 +278,8 @@ final class OAuth2ResourceServerBeanDefinitionParser implements BeanDefinitionPa
boolean usesEndpoint = element.hasAttribute(INTROSPECTION_URI) || element.hasAttribute(CLIENT_ID) boolean usesEndpoint = element.hasAttribute(INTROSPECTION_URI) || element.hasAttribute(CLIENT_ID)
|| element.hasAttribute(CLIENT_SECRET); || element.hasAttribute(CLIENT_SECRET);
if (usesIntrospector == usesEndpoint) { if (usesIntrospector == usesEndpoint) {
pc.getReaderContext().error("Please specify either introspector-ref or all of " pc.getReaderContext()
.error("Please specify either introspector-ref or all of "
+ "introspection-uri, client-id, and client-secret.", element); + "introspection-uri, client-id, and client-secret.", element);
return; return;
} }

View File

@ -109,14 +109,14 @@ class RememberMeBeanDefinitionParser implements BeanDefinitionParser {
if (servicesRefSet && (dataSourceSet || tokenRepoSet || userServiceSet || tokenValiditySet || useSecureCookieSet if (servicesRefSet && (dataSourceSet || tokenRepoSet || userServiceSet || tokenValiditySet || useSecureCookieSet
|| remembermeParameterSet || remembermeCookieSet)) { || remembermeParameterSet || remembermeCookieSet)) {
pc.getReaderContext() pc.getReaderContext()
.error(ATT_SERVICES_REF + " can't be used in combination with attributes " + ATT_TOKEN_REPOSITORY .error(ATT_SERVICES_REF + " can't be used in combination with attributes " + ATT_TOKEN_REPOSITORY + ","
+ "," + ATT_DATA_SOURCE + ", " + ATT_USER_SERVICE_REF + ", " + ATT_TOKEN_VALIDITY + ", " + ATT_DATA_SOURCE + ", " + ATT_USER_SERVICE_REF + ", " + ATT_TOKEN_VALIDITY + ", "
+ ATT_SECURE_COOKIE + ", " + ATT_FORM_REMEMBERME_PARAMETER + " or " + ATT_REMEMBERME_COOKIE, + ATT_SECURE_COOKIE + ", " + ATT_FORM_REMEMBERME_PARAMETER + " or " + ATT_REMEMBERME_COOKIE,
source); source);
} }
if (dataSourceSet && tokenRepoSet) { if (dataSourceSet && tokenRepoSet) {
pc.getReaderContext().error("Specify " + ATT_TOKEN_REPOSITORY + " or " + ATT_DATA_SOURCE + " but not both", pc.getReaderContext()
source); .error("Specify " + ATT_TOKEN_REPOSITORY + " or " + ATT_DATA_SOURCE + " but not both", source);
} }
boolean isPersistent = dataSourceSet | tokenRepoSet; boolean isPersistent = dataSourceSet | tokenRepoSet;
if (isPersistent) { if (isPersistent) {
@ -127,8 +127,8 @@ class RememberMeBeanDefinitionParser implements BeanDefinitionParser {
} }
else { else {
tokenRepo = new RootBeanDefinition(JdbcTokenRepositoryImpl.class); tokenRepo = new RootBeanDefinition(JdbcTokenRepositoryImpl.class);
((BeanDefinition) tokenRepo).getPropertyValues().addPropertyValue("dataSource", ((BeanDefinition) tokenRepo).getPropertyValues()
new RuntimeBeanReference(dataSource)); .addPropertyValue("dataSource", new RuntimeBeanReference(dataSource));
} }
services.getConstructorArgumentValues().addIndexedArgumentValue(2, tokenRepo); services.getConstructorArgumentValues().addIndexedArgumentValue(2, tokenRepo);
} }
@ -151,7 +151,8 @@ class RememberMeBeanDefinitionParser implements BeanDefinitionParser {
if (tokenValiditySet) { if (tokenValiditySet) {
boolean isTokenValidityNegative = tokenValiditySeconds.startsWith("-"); boolean isTokenValidityNegative = tokenValiditySeconds.startsWith("-");
if (isTokenValidityNegative && isPersistent) { if (isTokenValidityNegative && isPersistent) {
pc.getReaderContext().error(ATT_TOKEN_VALIDITY + " cannot be negative if using" pc.getReaderContext()
.error(ATT_TOKEN_VALIDITY + " cannot be negative if using"
+ " a persistent remember-me token repository", source); + " a persistent remember-me token repository", source);
} }
services.getPropertyValues().addPropertyValue("tokenValiditySeconds", tokenValiditySeconds); services.getPropertyValues().addPropertyValue("tokenValiditySeconds", tokenValiditySeconds);

View File

@ -145,7 +145,8 @@ final class Saml2LoginBeanDefinitionParser implements BeanDefinitionParser {
// Configure the Saml2WebSsoAuthenticationFilter // Configure the Saml2WebSsoAuthenticationFilter
BeanDefinitionBuilder saml2WebSsoAuthenticationFilterBuilder = BeanDefinitionBuilder BeanDefinitionBuilder saml2WebSsoAuthenticationFilterBuilder = BeanDefinitionBuilder
.rootBeanDefinition(Saml2WebSsoAuthenticationFilter.class) .rootBeanDefinition(Saml2WebSsoAuthenticationFilter.class)
.addConstructorArgValue(authenticationConverter).addConstructorArgValue(this.loginProcessingUrl) .addConstructorArgValue(authenticationConverter)
.addConstructorArgValue(this.loginProcessingUrl)
.addPropertyValue("authenticationRequestRepository", authenticationRequestRepository); .addPropertyValue("authenticationRequestRepository", authenticationRequestRepository);
resolveLoginPage(element, pc); resolveLoginPage(element, pc);
resolveAuthenticationSuccessHandler(element, saml2WebSsoAuthenticationFilterBuilder); resolveAuthenticationSuccessHandler(element, saml2WebSsoAuthenticationFilterBuilder);
@ -195,8 +196,10 @@ final class Saml2LoginBeanDefinitionParser implements BeanDefinitionParser {
if (StringUtils.hasText(loginPage)) { if (StringUtils.hasText(loginPage)) {
WebConfigUtils.validateHttpRedirect(loginPage, parserContext, source); WebConfigUtils.validateHttpRedirect(loginPage, parserContext, source);
saml2LoginAuthenticationEntryPoint = BeanDefinitionBuilder saml2LoginAuthenticationEntryPoint = BeanDefinitionBuilder
.rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class).addConstructorArgValue(loginPage) .rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class)
.addPropertyValue("portMapper", this.portMapper).addPropertyValue("portResolver", this.portResolver) .addConstructorArgValue(loginPage)
.addPropertyValue("portMapper", this.portMapper)
.addPropertyValue("portResolver", this.portResolver)
.getBeanDefinition(); .getBeanDefinition();
} }
else { else {
@ -204,9 +207,11 @@ final class Saml2LoginBeanDefinitionParser implements BeanDefinitionParser {
if (identityProviderUrlMap.size() == 1) { if (identityProviderUrlMap.size() == 1) {
String loginUrl = identityProviderUrlMap.entrySet().iterator().next().getKey(); String loginUrl = identityProviderUrlMap.entrySet().iterator().next().getKey();
saml2LoginAuthenticationEntryPoint = BeanDefinitionBuilder saml2LoginAuthenticationEntryPoint = BeanDefinitionBuilder
.rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class).addConstructorArgValue(loginUrl) .rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class)
.addConstructorArgValue(loginUrl)
.addPropertyValue("portMapper", this.portMapper) .addPropertyValue("portMapper", this.portMapper)
.addPropertyValue("portResolver", this.portResolver).getBeanDefinition(); .addPropertyValue("portResolver", this.portResolver)
.getBeanDefinition();
} }
} }
if (saml2LoginAuthenticationEntryPoint != null) { if (saml2LoginAuthenticationEntryPoint != null) {
@ -244,7 +249,8 @@ final class Saml2LoginBeanDefinitionParser implements BeanDefinitionParser {
authenticationSuccessHandlerRef); authenticationSuccessHandlerRef);
} }
else { else {
BeanDefinitionBuilder successHandlerBuilder = BeanDefinitionBuilder.rootBeanDefinition( BeanDefinitionBuilder successHandlerBuilder = BeanDefinitionBuilder
.rootBeanDefinition(
"org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler") "org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler")
.addPropertyValue("requestCache", this.requestCache); .addPropertyValue("requestCache", this.requestCache);
saml2WebSsoAuthenticationFilterBuilder.addPropertyValue("authenticationSuccessHandler", saml2WebSsoAuthenticationFilterBuilder.addPropertyValue("authenticationSuccessHandler",

View File

@ -76,10 +76,12 @@ final class Saml2LoginBeanDefinitionParserUtils {
BeanMetadataElement relyingPartyRegistrationRepository) { BeanMetadataElement relyingPartyRegistrationRepository) {
BeanMetadataElement defaultRelyingPartyRegistrationResolver = BeanDefinitionBuilder BeanMetadataElement defaultRelyingPartyRegistrationResolver = BeanDefinitionBuilder
.rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class) .rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class)
.addConstructorArgValue(relyingPartyRegistrationRepository).getBeanDefinition(); .addConstructorArgValue(relyingPartyRegistrationRepository)
.getBeanDefinition();
return BeanDefinitionBuilder.rootBeanDefinition( return BeanDefinitionBuilder.rootBeanDefinition(
"org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver") "org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver")
.addConstructorArgValue(defaultRelyingPartyRegistrationResolver).getBeanDefinition(); .addConstructorArgValue(defaultRelyingPartyRegistrationResolver)
.getBeanDefinition();
} }
static BeanDefinition createAuthenticationProvider() { static BeanDefinition createAuthenticationProvider() {
@ -99,9 +101,11 @@ final class Saml2LoginBeanDefinitionParserUtils {
static BeanDefinition createDefaultAuthenticationConverter(BeanMetadataElement relyingPartyRegistrationRepository) { static BeanDefinition createDefaultAuthenticationConverter(BeanMetadataElement relyingPartyRegistrationRepository) {
AbstractBeanDefinition resolver = BeanDefinitionBuilder AbstractBeanDefinition resolver = BeanDefinitionBuilder
.rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class) .rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class)
.addConstructorArgValue(relyingPartyRegistrationRepository).getBeanDefinition(); .addConstructorArgValue(relyingPartyRegistrationRepository)
.getBeanDefinition();
return BeanDefinitionBuilder.rootBeanDefinition(Saml2AuthenticationTokenConverter.class) return BeanDefinitionBuilder.rootBeanDefinition(Saml2AuthenticationTokenConverter.class)
.addConstructorArgValue(resolver).getBeanDefinition(); .addConstructorArgValue(resolver)
.getBeanDefinition();
} }
} }

View File

@ -116,18 +116,20 @@ final class Saml2LogoutBeanDefinitionParser implements BeanDefinitionParser {
.getRelyingPartyRegistrationRepository(element); .getRelyingPartyRegistrationRepository(element);
BeanMetadataElement registrations = BeanDefinitionBuilder BeanMetadataElement registrations = BeanDefinitionBuilder
.rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class) .rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class)
.addConstructorArgValue(relyingPartyRegistrationRepository).getBeanDefinition(); .addConstructorArgValue(relyingPartyRegistrationRepository)
.getBeanDefinition();
BeanMetadataElement logoutResponseResolver = Saml2LogoutBeanDefinitionParserUtils BeanMetadataElement logoutResponseResolver = Saml2LogoutBeanDefinitionParserUtils
.getLogoutResponseResolver(element, registrations); .getLogoutResponseResolver(element, registrations);
BeanMetadataElement logoutRequestValidator = Saml2LogoutBeanDefinitionParserUtils BeanMetadataElement logoutRequestValidator = Saml2LogoutBeanDefinitionParserUtils
.getLogoutRequestValidator(element); .getLogoutRequestValidator(element);
BeanMetadataElement logoutRequestMatcher = createSaml2LogoutRequestMatcher(); BeanMetadataElement logoutRequestMatcher = createSaml2LogoutRequestMatcher();
this.logoutRequestFilter = BeanDefinitionBuilder.rootBeanDefinition(Saml2LogoutRequestFilter.class) this.logoutRequestFilter = BeanDefinitionBuilder.rootBeanDefinition(Saml2LogoutRequestFilter.class)
.addConstructorArgValue(registrations).addConstructorArgValue(logoutRequestValidator) .addConstructorArgValue(registrations)
.addConstructorArgValue(logoutResponseResolver).addConstructorArgValue(this.logoutHandlers) .addConstructorArgValue(logoutRequestValidator)
.addConstructorArgValue(logoutResponseResolver)
.addConstructorArgValue(this.logoutHandlers)
.addPropertyValue("logoutRequestMatcher", logoutRequestMatcher) .addPropertyValue("logoutRequestMatcher", logoutRequestMatcher)
.addPropertyValue("securityContextHolderStrategy", .addPropertyValue("securityContextHolderStrategy", this.authenticationFilterSecurityContextHolderStrategy)
this.authenticationFilterSecurityContextHolderStrategy)
.getBeanDefinition(); .getBeanDefinition();
BeanMetadataElement logoutResponseValidator = Saml2LogoutBeanDefinitionParserUtils BeanMetadataElement logoutResponseValidator = Saml2LogoutBeanDefinitionParserUtils
.getLogoutResponseValidator(element); .getLogoutResponseValidator(element);
@ -135,18 +137,23 @@ final class Saml2LogoutBeanDefinitionParser implements BeanDefinitionParser {
.getLogoutRequestRepository(element); .getLogoutRequestRepository(element);
BeanMetadataElement logoutResponseMatcher = createSaml2LogoutResponseMatcher(); BeanMetadataElement logoutResponseMatcher = createSaml2LogoutResponseMatcher();
this.logoutResponseFilter = BeanDefinitionBuilder.rootBeanDefinition(Saml2LogoutResponseFilter.class) this.logoutResponseFilter = BeanDefinitionBuilder.rootBeanDefinition(Saml2LogoutResponseFilter.class)
.addConstructorArgValue(registrations).addConstructorArgValue(logoutResponseValidator) .addConstructorArgValue(registrations)
.addConstructorArgValue(logoutResponseValidator)
.addConstructorArgValue(this.logoutSuccessHandler) .addConstructorArgValue(this.logoutSuccessHandler)
.addPropertyValue("logoutRequestMatcher", logoutResponseMatcher) .addPropertyValue("logoutRequestMatcher", logoutResponseMatcher)
.addPropertyValue("logoutRequestRepository", logoutRequestRepository).getBeanDefinition(); .addPropertyValue("logoutRequestRepository", logoutRequestRepository)
.getBeanDefinition();
BeanMetadataElement logoutRequestResolver = Saml2LogoutBeanDefinitionParserUtils BeanMetadataElement logoutRequestResolver = Saml2LogoutBeanDefinitionParserUtils
.getLogoutRequestResolver(element, registrations); .getLogoutRequestResolver(element, registrations);
BeanMetadataElement saml2LogoutRequestSuccessHandler = BeanDefinitionBuilder BeanMetadataElement saml2LogoutRequestSuccessHandler = BeanDefinitionBuilder
.rootBeanDefinition(Saml2RelyingPartyInitiatedLogoutSuccessHandler.class) .rootBeanDefinition(Saml2RelyingPartyInitiatedLogoutSuccessHandler.class)
.addConstructorArgValue(logoutRequestResolver).getBeanDefinition(); .addConstructorArgValue(logoutRequestResolver)
.getBeanDefinition();
this.logoutFilter = BeanDefinitionBuilder.rootBeanDefinition(LogoutFilter.class) this.logoutFilter = BeanDefinitionBuilder.rootBeanDefinition(LogoutFilter.class)
.addConstructorArgValue(saml2LogoutRequestSuccessHandler).addConstructorArgValue(this.logoutHandlers) .addConstructorArgValue(saml2LogoutRequestSuccessHandler)
.addPropertyValue("logoutRequestMatcher", createLogoutRequestMatcher()).getBeanDefinition(); .addConstructorArgValue(this.logoutHandlers)
.addPropertyValue("logoutRequestMatcher", createLogoutRequestMatcher())
.getBeanDefinition();
return null; return null;
} }
@ -160,39 +167,48 @@ final class Saml2LogoutBeanDefinitionParser implements BeanDefinitionParser {
private static BeanMetadataElement createDefaultLogoutSuccessHandler() { private static BeanMetadataElement createDefaultLogoutSuccessHandler() {
return BeanDefinitionBuilder.rootBeanDefinition(SimpleUrlLogoutSuccessHandler.class) return BeanDefinitionBuilder.rootBeanDefinition(SimpleUrlLogoutSuccessHandler.class)
.addPropertyValue("defaultTargetUrl", "/login?logout").getBeanDefinition(); .addPropertyValue("defaultTargetUrl", "/login?logout")
.getBeanDefinition();
} }
private BeanMetadataElement createLogoutRequestMatcher() { private BeanMetadataElement createLogoutRequestMatcher() {
BeanMetadataElement logoutMatcher = BeanDefinitionBuilder.rootBeanDefinition(AntPathRequestMatcher.class) BeanMetadataElement logoutMatcher = BeanDefinitionBuilder.rootBeanDefinition(AntPathRequestMatcher.class)
.addConstructorArgValue(this.logoutUrl).addConstructorArgValue("POST").getBeanDefinition(); .addConstructorArgValue(this.logoutUrl)
.addConstructorArgValue("POST")
.getBeanDefinition();
BeanMetadataElement saml2Matcher = BeanDefinitionBuilder.rootBeanDefinition(Saml2RequestMatcher.class) BeanMetadataElement saml2Matcher = BeanDefinitionBuilder.rootBeanDefinition(Saml2RequestMatcher.class)
.addPropertyValue("securityContextHolderStrategy", .addPropertyValue("securityContextHolderStrategy", this.authenticationFilterSecurityContextHolderStrategy)
this.authenticationFilterSecurityContextHolderStrategy)
.getBeanDefinition(); .getBeanDefinition();
return BeanDefinitionBuilder.rootBeanDefinition(AndRequestMatcher.class) return BeanDefinitionBuilder.rootBeanDefinition(AndRequestMatcher.class)
.addConstructorArgValue(toManagedList(logoutMatcher, saml2Matcher)).getBeanDefinition(); .addConstructorArgValue(toManagedList(logoutMatcher, saml2Matcher))
.getBeanDefinition();
} }
private BeanMetadataElement createSaml2LogoutRequestMatcher() { private BeanMetadataElement createSaml2LogoutRequestMatcher() {
BeanMetadataElement logoutRequestMatcher = BeanDefinitionBuilder.rootBeanDefinition(AntPathRequestMatcher.class) BeanMetadataElement logoutRequestMatcher = BeanDefinitionBuilder.rootBeanDefinition(AntPathRequestMatcher.class)
.addConstructorArgValue(this.logoutRequestUrl).getBeanDefinition(); .addConstructorArgValue(this.logoutRequestUrl)
.getBeanDefinition();
BeanMetadataElement saml2RequestMatcher = BeanDefinitionBuilder BeanMetadataElement saml2RequestMatcher = BeanDefinitionBuilder
.rootBeanDefinition(ParameterRequestMatcher.class).addConstructorArgValue("SAMLRequest") .rootBeanDefinition(ParameterRequestMatcher.class)
.addConstructorArgValue("SAMLRequest")
.getBeanDefinition(); .getBeanDefinition();
return BeanDefinitionBuilder.rootBeanDefinition(AndRequestMatcher.class) return BeanDefinitionBuilder.rootBeanDefinition(AndRequestMatcher.class)
.addConstructorArgValue(toManagedList(logoutRequestMatcher, saml2RequestMatcher)).getBeanDefinition(); .addConstructorArgValue(toManagedList(logoutRequestMatcher, saml2RequestMatcher))
.getBeanDefinition();
} }
private BeanMetadataElement createSaml2LogoutResponseMatcher() { private BeanMetadataElement createSaml2LogoutResponseMatcher() {
BeanMetadataElement logoutResponseMatcher = BeanDefinitionBuilder BeanMetadataElement logoutResponseMatcher = BeanDefinitionBuilder
.rootBeanDefinition(AntPathRequestMatcher.class).addConstructorArgValue(this.logoutResponseUrl) .rootBeanDefinition(AntPathRequestMatcher.class)
.addConstructorArgValue(this.logoutResponseUrl)
.getBeanDefinition(); .getBeanDefinition();
BeanMetadataElement saml2ResponseMatcher = BeanDefinitionBuilder BeanMetadataElement saml2ResponseMatcher = BeanDefinitionBuilder
.rootBeanDefinition(ParameterRequestMatcher.class).addConstructorArgValue("SAMLResponse") .rootBeanDefinition(ParameterRequestMatcher.class)
.addConstructorArgValue("SAMLResponse")
.getBeanDefinition(); .getBeanDefinition();
return BeanDefinitionBuilder.rootBeanDefinition(AndRequestMatcher.class) return BeanDefinitionBuilder.rootBeanDefinition(AndRequestMatcher.class)
.addConstructorArgValue(toManagedList(logoutResponseMatcher, saml2ResponseMatcher)).getBeanDefinition(); .addConstructorArgValue(toManagedList(logoutResponseMatcher, saml2ResponseMatcher))
.getBeanDefinition();
} }
private static List<BeanMetadataElement> toManagedList(BeanMetadataElement... elements) { private static List<BeanMetadataElement> toManagedList(BeanMetadataElement... elements) {

View File

@ -64,7 +64,8 @@ final class Saml2LogoutBeanDefinitionParserUtils {
} }
return BeanDefinitionBuilder.rootBeanDefinition( return BeanDefinitionBuilder.rootBeanDefinition(
"org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutResponseResolver") "org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutResponseResolver")
.addConstructorArgValue(registrations).getBeanDefinition(); .addConstructorArgValue(registrations)
.getBeanDefinition();
} }
static BeanMetadataElement getLogoutRequestValidator(Element element) { static BeanMetadataElement getLogoutRequestValidator(Element element) {
@ -98,7 +99,8 @@ final class Saml2LogoutBeanDefinitionParserUtils {
} }
return BeanDefinitionBuilder.rootBeanDefinition( return BeanDefinitionBuilder.rootBeanDefinition(
"org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutRequestResolver") "org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutRequestResolver")
.addConstructorArgValue(registrations).getBeanDefinition(); .addConstructorArgValue(registrations)
.getBeanDefinition();
} }
} }

View File

@ -48,7 +48,8 @@ public final class WellKnownChangePasswordBeanDefinitionParser implements BeanDe
BeanDefinition changePasswordFilter = BeanDefinitionBuilder BeanDefinition changePasswordFilter = BeanDefinitionBuilder
.rootBeanDefinition(RequestMatcherRedirectFilter.class) .rootBeanDefinition(RequestMatcherRedirectFilter.class)
.addConstructorArgValue(new AntPathRequestMatcher(WELL_KNOWN_CHANGE_PASSWORD_PATTERN)) .addConstructorArgValue(new AntPathRequestMatcher(WELL_KNOWN_CHANGE_PASSWORD_PATTERN))
.addConstructorArgValue(getChangePasswordPage(element)).getBeanDefinition(); .addConstructorArgValue(getChangePasswordPage(element))
.getBeanDefinition();
parserContext.getReaderContext().registerWithGeneratedName(changePasswordFilter); parserContext.getReaderContext().registerWithGeneratedName(changePasswordFilter);
return changePasswordFilter; return changePasswordFilter;
} }

View File

@ -89,8 +89,8 @@ public class LdapProviderBeanDefinitionParser implements BeanDefinitionParser {
String hash = passwordCompareElt.getAttribute(ATT_HASH); String hash = passwordCompareElt.getAttribute(ATT_HASH);
if (passwordEncoderElement != null) { if (passwordEncoderElement != null) {
if (StringUtils.hasText(hash)) { if (StringUtils.hasText(hash)) {
parserContext.getReaderContext().warning( parserContext.getReaderContext()
"Attribute 'hash' cannot be used with 'password-encoder' and " + "will be ignored.", .warning("Attribute 'hash' cannot be used with 'password-encoder' and " + "will be ignored.",
parserContext.extractSource(elt)); parserContext.extractSource(elt));
} }
PasswordEncoderParser pep = new PasswordEncoderParser(passwordEncoderElement, parserContext); PasswordEncoderParser pep = new PasswordEncoderParser(passwordEncoderElement, parserContext);
@ -108,8 +108,8 @@ public class LdapProviderBeanDefinitionParser implements BeanDefinitionParser {
} }
BeanDefinitionBuilder ldapProvider = BeanDefinitionBuilder.rootBeanDefinition(PROVIDER_CLASS); BeanDefinitionBuilder ldapProvider = BeanDefinitionBuilder.rootBeanDefinition(PROVIDER_CLASS);
ldapProvider.addConstructorArgValue(authenticatorBuilder.getBeanDefinition()); ldapProvider.addConstructorArgValue(authenticatorBuilder.getBeanDefinition());
ldapProvider.addConstructorArgValue( ldapProvider
LdapUserServiceBeanDefinitionParser.parseAuthoritiesPopulator(elt, parserContext)); .addConstructorArgValue(LdapUserServiceBeanDefinitionParser.parseAuthoritiesPopulator(elt, parserContext));
ldapProvider.addPropertyValue("userDetailsContextMapper", ldapProvider.addPropertyValue("userDetailsContextMapper",
LdapUserServiceBeanDefinitionParser.parseUserDetailsClassOrUserMapperRef(elt, parserContext)); LdapUserServiceBeanDefinitionParser.parseUserDetailsClassOrUserMapperRef(elt, parserContext));
return ldapProvider.getBeanDefinition(); return ldapProvider.getBeanDefinition();

View File

@ -135,7 +135,8 @@ public class LdapServerBeanDefinitionParser implements BeanDefinitionParser {
contextSource.addPropertyValue("userDn", "uid=admin,ou=system"); contextSource.addPropertyValue("userDn", "uid=admin,ou=system");
contextSource.addPropertyValue("password", "secret"); contextSource.addPropertyValue("password", "secret");
BeanDefinition embeddedLdapServerConfigBean = BeanDefinitionBuilder BeanDefinition embeddedLdapServerConfigBean = BeanDefinitionBuilder
.rootBeanDefinition(EmbeddedLdapServerConfigBean.class).getBeanDefinition(); .rootBeanDefinition(EmbeddedLdapServerConfigBean.class)
.getBeanDefinition();
String embeddedLdapServerConfigBeanName = parserContext.getReaderContext() String embeddedLdapServerConfigBeanName = parserContext.getReaderContext()
.generateBeanName(embeddedLdapServerConfigBean); .generateBeanName(embeddedLdapServerConfigBean);
parserContext.registerBeanComponent( parserContext.registerBeanComponent(
@ -153,8 +154,8 @@ public class LdapServerBeanDefinitionParser implements BeanDefinitionParser {
ldapContainer.getPropertyValues().addPropertyValue("port", getPort(element)); ldapContainer.getPropertyValues().addPropertyValue("port", getPort(element));
if (parserContext.getRegistry().containsBeanDefinition(BeanIds.EMBEDDED_APACHE_DS) if (parserContext.getRegistry().containsBeanDefinition(BeanIds.EMBEDDED_APACHE_DS)
|| parserContext.getRegistry().containsBeanDefinition(BeanIds.EMBEDDED_UNBOUNDID)) { || parserContext.getRegistry().containsBeanDefinition(BeanIds.EMBEDDED_UNBOUNDID)) {
parserContext.getReaderContext().error("Only one embedded server bean is allowed per application context", parserContext.getReaderContext()
element); .error("Only one embedded server bean is allowed per application context", element);
} }
String beanId = resolveBeanId(mode); String beanId = resolveBeanId(mode);
if (beanId != null) { if (beanId != null) {

View File

@ -143,8 +143,9 @@ public class LdapUserServiceBeanDefinitionParser extends AbstractUserDetailsServ
String userDetailsClass = elt.getAttribute(ATT_USER_CLASS); String userDetailsClass = elt.getAttribute(ATT_USER_CLASS);
String userMapperRef = elt.getAttribute(ATT_USER_CONTEXT_MAPPER_REF); String userMapperRef = elt.getAttribute(ATT_USER_CONTEXT_MAPPER_REF);
if (StringUtils.hasText(userDetailsClass) && StringUtils.hasText(userMapperRef)) { if (StringUtils.hasText(userDetailsClass) && StringUtils.hasText(userMapperRef)) {
parserContext.getReaderContext().error("Attributes " + ATT_USER_CLASS + " and " parserContext.getReaderContext()
+ ATT_USER_CONTEXT_MAPPER_REF + " cannot be used together.", parserContext.extractSource(elt)); .error("Attributes " + ATT_USER_CLASS + " and " + ATT_USER_CONTEXT_MAPPER_REF
+ " cannot be used together.", parserContext.extractSource(elt));
} }
if (StringUtils.hasText(userMapperRef)) { if (StringUtils.hasText(userMapperRef)) {
return new RuntimeBeanReference(userMapperRef); return new RuntimeBeanReference(userMapperRef);

View File

@ -37,8 +37,8 @@ class AspectJMethodMatcher implements MethodMatcher, ClassFilter, Pointcut {
supportedPrimitives.add(PointcutPrimitive.EXECUTION); supportedPrimitives.add(PointcutPrimitive.EXECUTION);
supportedPrimitives.add(PointcutPrimitive.ARGS); supportedPrimitives.add(PointcutPrimitive.ARGS);
supportedPrimitives.add(PointcutPrimitive.REFERENCE); supportedPrimitives.add(PointcutPrimitive.REFERENCE);
parser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution( parser = PointcutParser
supportedPrimitives); .getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(supportedPrimitives);
} }
private final PointcutExpression expression; private final PointcutExpression expression;

View File

@ -144,7 +144,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
Element prePostElt = DomUtils.getChildElementByTagName(element, Elements.INVOCATION_HANDLING); Element prePostElt = DomUtils.getChildElementByTagName(element, Elements.INVOCATION_HANDLING);
Element expressionHandlerElt = DomUtils.getChildElementByTagName(element, Elements.EXPRESSION_HANDLER); Element expressionHandlerElt = DomUtils.getChildElementByTagName(element, Elements.EXPRESSION_HANDLER);
if (prePostElt != null && expressionHandlerElt != null) { if (prePostElt != null && expressionHandlerElt != null) {
pc.getReaderContext().error(Elements.INVOCATION_HANDLING + " and " + Elements.EXPRESSION_HANDLER pc.getReaderContext()
.error(Elements.INVOCATION_HANDLING + " and " + Elements.EXPRESSION_HANDLER
+ " cannot be used together ", source); + " cannot be used together ", source);
} }
BeanDefinitionBuilder preInvocationVoterBldr = BeanDefinitionBuilder BeanDefinitionBuilder preInvocationVoterBldr = BeanDefinitionBuilder
@ -331,12 +332,12 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
String accessConfig = childElt.getAttribute(ATT_ACCESS); String accessConfig = childElt.getAttribute(ATT_ACCESS);
String expression = childElt.getAttribute(ATT_EXPRESSION); String expression = childElt.getAttribute(ATT_EXPRESSION);
if (!StringUtils.hasText(accessConfig)) { if (!StringUtils.hasText(accessConfig)) {
parserContext.getReaderContext().error("Access configuration required", parserContext.getReaderContext()
parserContext.extractSource(childElt)); .error("Access configuration required", parserContext.extractSource(childElt));
} }
if (!StringUtils.hasText(expression)) { if (!StringUtils.hasText(expression)) {
parserContext.getReaderContext().error("Pointcut expression required", parserContext.getReaderContext()
parserContext.extractSource(childElt)); .error("Pointcut expression required", parserContext.extractSource(childElt));
} }
String[] attributeTokens = StringUtils.commaDelimitedListToStringArray(accessConfig); String[] attributeTokens = StringUtils.commaDelimitedListToStringArray(accessConfig);
List<ConfigAttribute> attributes = new ArrayList<>(attributeTokens.length); List<ConfigAttribute> attributes = new ArrayList<>(attributeTokens.length);
@ -351,8 +352,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
private BeanReference registerMethodSecurityInterceptor(ParserContext pc, String authMgrRef, String accessManagerId, private BeanReference registerMethodSecurityInterceptor(ParserContext pc, String authMgrRef, String accessManagerId,
String runAsManagerId, BeanReference metadataSource, List<BeanMetadataElement> afterInvocationProviders, String runAsManagerId, BeanReference metadataSource, List<BeanMetadataElement> afterInvocationProviders,
Object source, boolean useAspectJ) { Object source, boolean useAspectJ) {
BeanDefinitionBuilder bldr = BeanDefinitionBuilder.rootBeanDefinition( BeanDefinitionBuilder bldr = BeanDefinitionBuilder
useAspectJ ? AspectJMethodSecurityInterceptor.class : MethodSecurityInterceptor.class); .rootBeanDefinition(useAspectJ ? AspectJMethodSecurityInterceptor.class : MethodSecurityInterceptor.class);
bldr.getRawBeanDefinition().setSource(source); bldr.getRawBeanDefinition().setSource(source);
bldr.addPropertyReference("accessDecisionManager", accessManagerId); bldr.addPropertyReference("accessDecisionManager", accessManagerId);
RootBeanDefinition authMgr = new RootBeanDefinition(AuthenticationManagerDelegator.class); RootBeanDefinition authMgr = new RootBeanDefinition(AuthenticationManagerDelegator.class);

View File

@ -88,7 +88,8 @@ public class InterceptMethodsBeanDefinitionDecorator implements BeanDefinitionDe
authorizationManager(interceptMethodsElt, protectElt)); authorizationManager(interceptMethodsElt, protectElt));
} }
return interceptor.addConstructorArgValue(Pointcut.TRUE) return interceptor.addConstructorArgValue(Pointcut.TRUE)
.addConstructorArgValue(authorizationManager(managers)).getBeanDefinition(); .addConstructorArgValue(authorizationManager(managers))
.getBeanDefinition();
} }
boolean supports(Node node) { boolean supports(Node node) {
@ -112,12 +113,14 @@ public class InterceptMethodsBeanDefinitionDecorator implements BeanDefinitionDe
} }
String access = protectElt.getAttribute(ATT_ACCESS); String access = protectElt.getAttribute(ATT_ACCESS);
return BeanDefinitionBuilder.rootBeanDefinition(MethodExpressionAuthorizationManager.class) return BeanDefinitionBuilder.rootBeanDefinition(MethodExpressionAuthorizationManager.class)
.addConstructorArgValue(access).getBeanDefinition(); .addConstructorArgValue(access)
.getBeanDefinition();
} }
private BeanMetadataElement authorizationManager(Map<Pointcut, BeanMetadataElement> managers) { private BeanMetadataElement authorizationManager(Map<Pointcut, BeanMetadataElement> managers) {
return BeanDefinitionBuilder.rootBeanDefinition(PointcutDelegatingAuthorizationManager.class) return BeanDefinitionBuilder.rootBeanDefinition(PointcutDelegatingAuthorizationManager.class)
.addConstructorArgValue(managers).getBeanDefinition(); .addConstructorArgValue(managers)
.getBeanDefinition();
} }
} }

View File

@ -38,7 +38,8 @@ abstract class MethodConfigUtils {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static void registerDefaultMethodAccessManagerIfNecessary(ParserContext parserContext) { static void registerDefaultMethodAccessManagerIfNecessary(ParserContext parserContext) {
if (!parserContext.getRegistry().containsBeanDefinition(BeanIds.METHOD_ACCESS_MANAGER)) { if (!parserContext.getRegistry().containsBeanDefinition(BeanIds.METHOD_ACCESS_MANAGER)) {
parserContext.getRegistry().registerBeanDefinition(BeanIds.METHOD_ACCESS_MANAGER, parserContext.getRegistry()
.registerBeanDefinition(BeanIds.METHOD_ACCESS_MANAGER,
createAccessManagerBean(RoleVoter.class, AuthenticatedVoter.class)); createAccessManagerBean(RoleVoter.class, AuthenticatedVoter.class));
} }
} }

View File

@ -119,19 +119,24 @@ public class MethodSecurityBeanDefinitionParser implements BeanDefinitionParser
} }
else { else {
BeanDefinition expressionHandler = BeanDefinitionBuilder BeanDefinition expressionHandler = BeanDefinitionBuilder
.rootBeanDefinition(MethodSecurityExpressionHandlerBean.class).getBeanDefinition(); .rootBeanDefinition(MethodSecurityExpressionHandlerBean.class)
.getBeanDefinition();
preFilterInterceptor.addPropertyValue("expressionHandler", expressionHandler); preFilterInterceptor.addPropertyValue("expressionHandler", expressionHandler);
preAuthorizeInterceptor.addPropertyValue("expressionHandler", expressionHandler); preAuthorizeInterceptor.addPropertyValue("expressionHandler", expressionHandler);
postAuthorizeInterceptor.addPropertyValue("expressionHandler", expressionHandler); postAuthorizeInterceptor.addPropertyValue("expressionHandler", expressionHandler);
postFilterInterceptor.addPropertyValue("expressionHandler", expressionHandler); postFilterInterceptor.addPropertyValue("expressionHandler", expressionHandler);
} }
pc.getRegistry().registerBeanDefinition("preFilterAuthorizationMethodInterceptor", pc.getRegistry()
.registerBeanDefinition("preFilterAuthorizationMethodInterceptor",
preFilterInterceptor.getBeanDefinition()); preFilterInterceptor.getBeanDefinition());
pc.getRegistry().registerBeanDefinition("preAuthorizeAuthorizationMethodInterceptor", pc.getRegistry()
.registerBeanDefinition("preAuthorizeAuthorizationMethodInterceptor",
preAuthorizeInterceptor.getBeanDefinition()); preAuthorizeInterceptor.getBeanDefinition());
pc.getRegistry().registerBeanDefinition("postAuthorizeAuthorizationMethodInterceptor", pc.getRegistry()
.registerBeanDefinition("postAuthorizeAuthorizationMethodInterceptor",
postAuthorizeInterceptor.getBeanDefinition()); postAuthorizeInterceptor.getBeanDefinition());
pc.getRegistry().registerBeanDefinition("postFilterAuthorizationMethodInterceptor", pc.getRegistry()
.registerBeanDefinition("postFilterAuthorizationMethodInterceptor",
postFilterInterceptor.getBeanDefinition()); postFilterInterceptor.getBeanDefinition());
} }
boolean securedEnabled = "true".equals(element.getAttribute(ATT_USE_SECURED)); boolean securedEnabled = "true".equals(element.getAttribute(ATT_USE_SECURED));
@ -141,7 +146,8 @@ public class MethodSecurityBeanDefinitionParser implements BeanDefinitionParser
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE) .setRole(BeanDefinition.ROLE_INFRASTRUCTURE)
.addPropertyValue("securityContextHolderStrategy", securityContextHolderStrategy) .addPropertyValue("securityContextHolderStrategy", securityContextHolderStrategy)
.setFactoryMethod("secured"); .setFactoryMethod("secured");
pc.getRegistry().registerBeanDefinition("securedAuthorizationMethodInterceptor", pc.getRegistry()
.registerBeanDefinition("securedAuthorizationMethodInterceptor",
securedInterceptor.getBeanDefinition()); securedInterceptor.getBeanDefinition());
} }
boolean jsr250Enabled = "true".equals(element.getAttribute(ATT_USE_JSR250)); boolean jsr250Enabled = "true".equals(element.getAttribute(ATT_USE_JSR250));
@ -150,15 +156,15 @@ public class MethodSecurityBeanDefinitionParser implements BeanDefinitionParser
.rootBeanDefinition(Jsr250AuthorizationMethodInterceptor.class) .rootBeanDefinition(Jsr250AuthorizationMethodInterceptor.class)
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE) .setRole(BeanDefinition.ROLE_INFRASTRUCTURE)
.addPropertyValue("securityContextHolderStrategy", securityContextHolderStrategy); .addPropertyValue("securityContextHolderStrategy", securityContextHolderStrategy);
pc.getRegistry().registerBeanDefinition("jsr250AuthorizationMethodInterceptor", pc.getRegistry()
jsr250Interceptor.getBeanDefinition()); .registerBeanDefinition("jsr250AuthorizationMethodInterceptor", jsr250Interceptor.getBeanDefinition());
} }
Map<Pointcut, BeanMetadataElement> managers = new ManagedMap<>(); Map<Pointcut, BeanMetadataElement> managers = new ManagedMap<>();
List<Element> methods = DomUtils.getChildElementsByTagName(element, Elements.PROTECT_POINTCUT); List<Element> methods = DomUtils.getChildElementsByTagName(element, Elements.PROTECT_POINTCUT);
if (useAspectJ) { if (useAspectJ) {
if (!methods.isEmpty()) { if (!methods.isEmpty()) {
pc.getReaderContext().error("Cannot use <protect-pointcut> and mode='aspectj' together", pc.getReaderContext()
pc.extractSource(element)); .error("Cannot use <protect-pointcut> and mode='aspectj' together", pc.extractSource(element));
} }
registerInterceptors(pc.getRegistry()); registerInterceptors(pc.getRegistry());
} }
@ -173,7 +179,8 @@ public class MethodSecurityBeanDefinitionParser implements BeanDefinitionParser
.addPropertyValue("securityContextHolderStrategy", securityContextHolderStrategy) .addPropertyValue("securityContextHolderStrategy", securityContextHolderStrategy)
.addConstructorArgValue(pointcut(managers.keySet())) .addConstructorArgValue(pointcut(managers.keySet()))
.addConstructorArgValue(authorizationManager(managers)); .addConstructorArgValue(authorizationManager(managers));
pc.getRegistry().registerBeanDefinition("protectPointcutInterceptor", pc.getRegistry()
.registerBeanDefinition("protectPointcutInterceptor",
protectPointcutInterceptor.getBeanDefinition()); protectPointcutInterceptor.getBeanDefinition());
} }
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(pc, element); AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(pc, element);
@ -223,12 +230,14 @@ public class MethodSecurityBeanDefinitionParser implements BeanDefinitionParser
} }
String access = protectElt.getAttribute(ATT_ACCESS); String access = protectElt.getAttribute(ATT_ACCESS);
return BeanDefinitionBuilder.rootBeanDefinition(MethodExpressionAuthorizationManager.class) return BeanDefinitionBuilder.rootBeanDefinition(MethodExpressionAuthorizationManager.class)
.addConstructorArgValue(access).getBeanDefinition(); .addConstructorArgValue(access)
.getBeanDefinition();
} }
private BeanMetadataElement authorizationManager(Map<Pointcut, BeanMetadataElement> managers) { private BeanMetadataElement authorizationManager(Map<Pointcut, BeanMetadataElement> managers) {
return BeanDefinitionBuilder.rootBeanDefinition(PointcutDelegatingAuthorizationManager.class) return BeanDefinitionBuilder.rootBeanDefinition(PointcutDelegatingAuthorizationManager.class)
.addConstructorArgValue(managers).getBeanDefinition(); .addConstructorArgValue(managers)
.getBeanDefinition();
} }
private void registerInterceptors(BeanDefinitionRegistry registry) { private void registerInterceptors(BeanDefinitionRegistry registry) {

View File

@ -97,8 +97,7 @@ final class ProtectPointcutPostProcessor implements BeanPostProcessor {
// supportedPrimitives.add(PointcutPrimitive.AT_ARGS); // supportedPrimitives.add(PointcutPrimitive.AT_ARGS);
// supportedPrimitives.add(PointcutPrimitive.AT_TARGET); // supportedPrimitives.add(PointcutPrimitive.AT_TARGET);
this.parser = PointcutParser this.parser = PointcutParser
.getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution( .getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(supportedPrimitives);
supportedPrimitives);
} }
@Override @Override

View File

@ -92,7 +92,8 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
List<ClientRegistration> clientRegistrations = getClientRegistrations(element, parserContext, providers); List<ClientRegistration> clientRegistrations = getClientRegistrations(element, parserContext, providers);
BeanDefinition clientRegistrationRepositoryBean = BeanDefinitionBuilder BeanDefinition clientRegistrationRepositoryBean = BeanDefinitionBuilder
.rootBeanDefinition(InMemoryClientRegistrationRepository.class) .rootBeanDefinition(InMemoryClientRegistrationRepository.class)
.addConstructorArgValue(clientRegistrations).getBeanDefinition(); .addConstructorArgValue(clientRegistrations)
.getBeanDefinition();
String clientRegistrationRepositoryId = parserContext.getReaderContext() String clientRegistrationRepositoryId = parserContext.getReaderContext()
.generateBeanName(clientRegistrationRepositoryBean); .generateBeanName(clientRegistrationRepositoryBean);
parserContext.registerBeanComponent( parserContext.registerBeanComponent(
@ -124,13 +125,16 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_SECRET)) getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_SECRET))
.ifPresent(builder::clientSecret); .ifPresent(builder::clientSecret);
getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_AUTHENTICATION_METHOD)) getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_AUTHENTICATION_METHOD))
.map(ClientAuthenticationMethod::new).ifPresent(builder::clientAuthenticationMethod); .map(ClientAuthenticationMethod::new)
.ifPresent(builder::clientAuthenticationMethod);
getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_AUTHORIZATION_GRANT_TYPE)) getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_AUTHORIZATION_GRANT_TYPE))
.map(AuthorizationGrantType::new).ifPresent(builder::authorizationGrantType); .map(AuthorizationGrantType::new)
.ifPresent(builder::authorizationGrantType);
getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_REDIRECT_URI)) getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_REDIRECT_URI))
.ifPresent(builder::redirectUri); .ifPresent(builder::redirectUri);
getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_SCOPE)) getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_SCOPE))
.map(StringUtils::commaDelimitedListToSet).ifPresent(builder::scope); .map(StringUtils::commaDelimitedListToSet)
.ifPresent(builder::scope);
getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_NAME)) getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_NAME))
.ifPresent(builder::clientName); .ifPresent(builder::clientName);
clientRegistrations.add(builder.build()); clientRegistrations.add(builder.build());
@ -200,7 +204,8 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
getOptionalIfNotEmpty(parserContext, provider.get(ATT_TOKEN_URI)).ifPresent(builder::tokenUri); getOptionalIfNotEmpty(parserContext, provider.get(ATT_TOKEN_URI)).ifPresent(builder::tokenUri);
getOptionalIfNotEmpty(parserContext, provider.get(ATT_USER_INFO_URI)).ifPresent(builder::userInfoUri); getOptionalIfNotEmpty(parserContext, provider.get(ATT_USER_INFO_URI)).ifPresent(builder::userInfoUri);
getOptionalIfNotEmpty(parserContext, provider.get(ATT_USER_INFO_AUTHENTICATION_METHOD)) getOptionalIfNotEmpty(parserContext, provider.get(ATT_USER_INFO_AUTHENTICATION_METHOD))
.map(AuthenticationMethod::new).ifPresent(builder::userInfoAuthenticationMethod); .map(AuthenticationMethod::new)
.ifPresent(builder::userInfoAuthenticationMethod);
getOptionalIfNotEmpty(parserContext, provider.get(ATT_JWK_SET_URI)).ifPresent(builder::jwkSetUri); getOptionalIfNotEmpty(parserContext, provider.get(ATT_JWK_SET_URI)).ifPresent(builder::jwkSetUri);
getOptionalIfNotEmpty(parserContext, provider.get(ATT_USER_INFO_USER_NAME_ATTRIBUTE)) getOptionalIfNotEmpty(parserContext, provider.get(ATT_USER_INFO_USER_NAME_ATTRIBUTE))
.ifPresent(builder::userNameAttributeName); .ifPresent(builder::userNameAttributeName);
@ -208,7 +213,8 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
} }
private static Optional<String> getOptionalIfNotEmpty(ParserContext parserContext, String str) { private static Optional<String> getOptionalIfNotEmpty(ParserContext parserContext, String str) {
return Optional.ofNullable(str).filter((s) -> !s.isEmpty()) return Optional.ofNullable(str)
.filter((s) -> !s.isEmpty())
.map(parserContext.getReaderContext().getEnvironment()::resolvePlaceholders); .map(parserContext.getReaderContext().getEnvironment()::resolvePlaceholders);
} }
@ -244,7 +250,9 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
private static String getCanonicalName(String name) { private static String getCanonicalName(String name) {
StringBuilder canonicalName = new StringBuilder(name.length()); StringBuilder canonicalName = new StringBuilder(name.length());
name.chars().filter(Character::isLetterOrDigit).map(Character::toLowerCase) name.chars()
.filter(Character::isLetterOrDigit)
.map(Character::toLowerCase)
.forEach((c) -> canonicalName.append((char) c)); .forEach((c) -> canonicalName.append((char) c));
return canonicalName.toString(); return canonicalName.toString();
} }

View File

@ -106,7 +106,8 @@ public final class RelyingPartyRegistrationsBeanDefinitionParser implements Bean
assertingParties, parserContext); assertingParties, parserContext);
BeanDefinition relyingPartyRegistrationRepositoryBean = BeanDefinitionBuilder BeanDefinition relyingPartyRegistrationRepositoryBean = BeanDefinitionBuilder
.rootBeanDefinition(InMemoryRelyingPartyRegistrationRepository.class) .rootBeanDefinition(InMemoryRelyingPartyRegistrationRepository.class)
.addConstructorArgValue(relyingPartyRegistrations).getBeanDefinition(); .addConstructorArgValue(relyingPartyRegistrations)
.getBeanDefinition();
String relyingPartyRegistrationRepositoryId = parserContext.getReaderContext() String relyingPartyRegistrationRepositoryId = parserContext.getReaderContext()
.generateBeanName(relyingPartyRegistrationRepositoryBean); .generateBeanName(relyingPartyRegistrationRepositoryBean);
parserContext.registerBeanComponent(new BeanComponentDefinition(relyingPartyRegistrationRepositoryBean, parserContext.registerBeanComponent(new BeanComponentDefinition(relyingPartyRegistrationRepositoryBean,
@ -214,8 +215,8 @@ public final class RelyingPartyRegistrationsBeanDefinitionParser implements Bean
} }
else { else {
builder = RelyingPartyRegistration.withRegistrationId(registrationId) builder = RelyingPartyRegistration.withRegistrationId(registrationId)
.assertingPartyDetails((apBuilder) -> buildAssertingParty(relyingPartyRegistrationElt, .assertingPartyDetails((apBuilder) -> buildAssertingParty(relyingPartyRegistrationElt, assertingParties,
assertingParties, apBuilder, parserContext)); apBuilder, parserContext));
} }
addRemainingProperties(relyingPartyRegistrationElt, builder); addRemainingProperties(relyingPartyRegistrationElt, builder);
return builder; return builder;
@ -274,7 +275,8 @@ public final class RelyingPartyRegistrationsBeanDefinitionParser implements Bean
String singleLogoutServiceBinding = getAsString(assertingParty, ATT_SINGLE_LOGOUT_SERVICE_BINDING); String singleLogoutServiceBinding = getAsString(assertingParty, ATT_SINGLE_LOGOUT_SERVICE_BINDING);
Saml2MessageBinding saml2LogoutMessageBinding = StringUtils.hasText(singleLogoutServiceBinding) Saml2MessageBinding saml2LogoutMessageBinding = StringUtils.hasText(singleLogoutServiceBinding)
? Saml2MessageBinding.valueOf(singleLogoutServiceBinding) : Saml2MessageBinding.REDIRECT; ? Saml2MessageBinding.valueOf(singleLogoutServiceBinding) : Saml2MessageBinding.REDIRECT;
builder.entityId(entityId).wantAuthnRequestsSigned(Boolean.parseBoolean(wantAuthnRequestsSigned)) builder.entityId(entityId)
.wantAuthnRequestsSigned(Boolean.parseBoolean(wantAuthnRequestsSigned))
.singleSignOnServiceLocation(singleSignOnServiceLocation) .singleSignOnServiceLocation(singleSignOnServiceLocation)
.singleSignOnServiceBinding(saml2MessageBinding) .singleSignOnServiceBinding(saml2MessageBinding)
.singleLogoutServiceLocation(singleLogoutServiceLocation) .singleLogoutServiceLocation(singleLogoutServiceLocation)

View File

@ -1522,8 +1522,9 @@ public class ServerHttpSecurity {
} }
ServerWebExchangeDelegatingServerAccessDeniedHandler result = new ServerWebExchangeDelegatingServerAccessDeniedHandler( ServerWebExchangeDelegatingServerAccessDeniedHandler result = new ServerWebExchangeDelegatingServerAccessDeniedHandler(
this.defaultAccessDeniedHandlers); this.defaultAccessDeniedHandlers);
result.setDefaultAccessDeniedHandler(this.defaultAccessDeniedHandlers result.setDefaultAccessDeniedHandler(
.get(this.defaultAccessDeniedHandlers.size() - 1).getAccessDeniedHandler()); this.defaultAccessDeniedHandlers.get(this.defaultAccessDeniedHandlers.size() - 1)
.getAccessDeniedHandler());
return result; return result;
} }
@ -3580,8 +3581,8 @@ public class ServerHttpSecurity {
ServerOAuth2AuthorizationCodeAuthenticationTokenConverter delegate = new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter( ServerOAuth2AuthorizationCodeAuthenticationTokenConverter delegate = new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(
clientRegistrationRepository); clientRegistrationRepository);
delegate.setAuthorizationRequestRepository(getAuthorizationRequestRepository()); delegate.setAuthorizationRequestRepository(getAuthorizationRequestRepository());
ServerAuthenticationConverter authenticationConverter = (exchange) -> delegate.convert(exchange).onErrorMap( ServerAuthenticationConverter authenticationConverter = (exchange) -> delegate.convert(exchange)
OAuth2AuthorizationException.class, .onErrorMap(OAuth2AuthorizationException.class,
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString())); (e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString()));
this.authenticationConverter = authenticationConverter; this.authenticationConverter = authenticationConverter;
return authenticationConverter; return authenticationConverter;

View File

@ -181,8 +181,9 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
new RuntimeBeanReference(holderStrategyRef)); new RuntimeBeanReference(holderStrategyRef));
} }
else { else {
inboundChannelSecurityInterceptor.addPropertyValue("securityContextHolderStrategy", BeanDefinitionBuilder inboundChannelSecurityInterceptor.addPropertyValue("securityContextHolderStrategy",
.rootBeanDefinition(SecurityContextHolderStrategyFactory.class).getBeanDefinition()); BeanDefinitionBuilder.rootBeanDefinition(SecurityContextHolderStrategyFactory.class)
.getBeanDefinition());
} }
return context.registerWithGeneratedName(inboundChannelSecurityInterceptor.getBeanDefinition()); return context.registerWithGeneratedName(inboundChannelSecurityInterceptor.getBeanDefinition());
@ -276,7 +277,8 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
factoryName = "createSubscribeMatcher"; factoryName = "createSubscribeMatcher";
} }
else { else {
parserContext.getReaderContext().error("Cannot use intercept-websocket@message-type=" + messageType parserContext.getReaderContext()
.error("Cannot use intercept-websocket@message-type=" + messageType
+ " with a pattern because the type does not have a destination.", interceptMessage); + " with a pattern because the type does not have a destination.", interceptMessage);
} }
} }

View File

@ -62,7 +62,8 @@ public class InvalidConfigurationTests {
@Test @Test
public void missingAuthenticationManagerGivesSensibleErrorMessage() { public void missingAuthenticationManagerGivesSensibleErrorMessage() {
assertThatExceptionOfType(BeanCreationException.class) assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> setContext("<http auto-config='true' />")).satisfies((ex) -> { .isThrownBy(() -> setContext("<http auto-config='true' />"))
.satisfies((ex) -> {
Throwable cause = ultimateCause(ex); Throwable cause = ultimateCause(ex);
assertThat(cause).isInstanceOf(NoSuchBeanDefinitionException.class); assertThat(cause).isInstanceOf(NoSuchBeanDefinitionException.class);
NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause; NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause;

View File

@ -92,16 +92,19 @@ public class AuthenticationManagerBuilderTests {
AuthenticationEventPublisher aep = mock(AuthenticationEventPublisher.class); AuthenticationEventPublisher aep = mock(AuthenticationEventPublisher.class);
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0)); given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep) AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build(); .inMemoryAuthentication()
assertThatExceptionOfType(AuthenticationException.class).isThrownBy( .and()
() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"))); .build();
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")));
verify(aep).publishAuthenticationFailure(any(), any()); verify(aep).publishAuthenticationFailure(any(), any());
} }
@Test @Test
public void getAuthenticationManagerWhenGlobalPasswordEncoderBeanThenUsed() throws Exception { public void getAuthenticationManagerWhenGlobalPasswordEncoderBeanThenUsed() throws Exception {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire(); this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager manager = this.spring.getContext()
.getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
Authentication auth = manager Authentication auth = manager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
@ -112,7 +115,8 @@ public class AuthenticationManagerBuilderTests {
@Test @Test
public void getAuthenticationManagerWhenProtectedPasswordEncoderBeanThenUsed() throws Exception { public void getAuthenticationManagerWhenProtectedPasswordEncoderBeanThenUsed() throws Exception {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire(); this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager manager = this.spring.getContext()
.getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
Authentication auth = manager Authentication auth = manager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")); .authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));

View File

@ -91,8 +91,10 @@ public class AuthenticationConfigurationTests {
@Test @Test
public void orderingAutowiredOnEnableGlobalMethodSecurity() { public void orderingAutowiredOnEnableGlobalMethodSecurity() {
this.spring.register(AuthenticationTestConfiguration.class, GlobalMethodSecurityAutowiredConfig.class, this.spring
ServicesConfig.class).autowire(); .register(AuthenticationTestConfiguration.class, GlobalMethodSecurityAutowiredConfig.class,
ServicesConfig.class)
.autowire();
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER")); .setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.service.run(); this.service.run();
@ -100,8 +102,10 @@ public class AuthenticationConfigurationTests {
@Test @Test
public void orderingAutowiredOnEnableWebSecurity() { public void orderingAutowiredOnEnableWebSecurity() {
this.spring.register(AuthenticationTestConfiguration.class, WebSecurityConfig.class, this.spring
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class).autowire(); .register(AuthenticationTestConfiguration.class, WebSecurityConfig.class,
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class)
.autowire();
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER")); .setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.service.run(); this.service.run();
@ -109,8 +113,10 @@ public class AuthenticationConfigurationTests {
@Test @Test
public void orderingAutowiredOnEnableWebMvcSecurity() { public void orderingAutowiredOnEnableWebMvcSecurity() {
this.spring.register(AuthenticationTestConfiguration.class, WebMvcSecurityConfig.class, this.spring
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class).autowire(); .register(AuthenticationTestConfiguration.class, WebMvcSecurityConfig.class,
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class)
.autowire();
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER")); .setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.service.run(); this.service.run();
@ -125,8 +131,10 @@ public class AuthenticationConfigurationTests {
@Test @Test
public void getAuthenticationManagerWhenNoOpGlobalAuthenticationConfigurerAdapterThenNull() throws Exception { public void getAuthenticationManagerWhenNoOpGlobalAuthenticationConfigurerAdapterThenNull() throws Exception {
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, this.spring
NoOpGlobalAuthenticationConfigurerAdapter.class).autowire(); .register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
NoOpGlobalAuthenticationConfigurerAdapter.class)
.autowire();
assertThat(this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager()) assertThat(this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager())
.isNull(); .isNull();
} }
@ -135,9 +143,12 @@ public class AuthenticationConfigurationTests {
public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthenticates() throws Exception { public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthenticates() throws Exception {
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password"); "password");
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, this.spring
UserGlobalAuthenticationConfigurerAdapter.class).autowire(); .register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class) UserGlobalAuthenticationConfigurerAdapter.class)
.autowire();
AuthenticationManager authentication = this.spring.getContext()
.getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName()); assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName());
} }
@ -146,9 +157,12 @@ public class AuthenticationConfigurationTests {
public void getAuthenticationWhenAuthenticationManagerBeanThenAuthenticates() throws Exception { public void getAuthenticationWhenAuthenticationManagerBeanThenAuthenticates() throws Exception {
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
"password"); "password");
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, this.spring
AuthenticationManagerBeanConfig.class).autowire(); .register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManagerBeanConfig.class)
.autowire();
AuthenticationManager authentication = this.spring.getContext()
.getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
given(authentication.authenticate(token)).willReturn(TestAuthentication.authenticatedUser()); given(authentication.authenticate(token)).willReturn(TestAuthentication.authenticatedUser());
assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName()); assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName());
@ -156,8 +170,10 @@ public class AuthenticationConfigurationTests {
@Test @Test
public void getAuthenticationWhenMultipleThenOrdered() throws Exception { public void getAuthenticationWhenMultipleThenOrdered() throws Exception {
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, this.spring
AuthenticationManagerBeanConfig.class).autowire(); .register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
AuthenticationManagerBeanConfig.class)
.autowire();
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class); AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
config.setGlobalAuthenticationConfigurers(Arrays.asList(new LowestOrderGlobalAuthenticationConfigurerAdapter(), config.setGlobalAuthenticationConfigurers(Arrays.asList(new LowestOrderGlobalAuthenticationConfigurerAdapter(),
new HighestOrderGlobalAuthenticationConfigurerAdapter(), new HighestOrderGlobalAuthenticationConfigurerAdapter(),
@ -209,12 +225,13 @@ public class AuthenticationConfigurationTests {
throws Exception { throws Exception {
this.spring.register(UserDetailsServiceBeanConfig.class).autowire(); this.spring.register(UserDetailsServiceBeanConfig.class).autowire();
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class); UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager am = this.spring.getContext()
.getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user()); given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")); am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy( assertThatExceptionOfType(AuthenticationException.class)
() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid"))); .isThrownBy(() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
} }
@Test @Test
@ -223,13 +240,14 @@ public class AuthenticationConfigurationTests {
AuthorityUtils.createAuthorityList("ROLE_USER")); AuthorityUtils.createAuthorityList("ROLE_USER"));
this.spring.register(UserDetailsServiceBeanWithPasswordEncoderConfig.class).autowire(); this.spring.register(UserDetailsServiceBeanWithPasswordEncoderConfig.class).autowire();
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class); UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager am = this.spring.getContext()
.getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(), given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build()); User.withUserDetails(user).build());
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")); am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy( assertThatExceptionOfType(AuthenticationException.class)
() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid"))); .isThrownBy(() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
} }
@Test @Test
@ -238,7 +256,8 @@ public class AuthenticationConfigurationTests {
this.spring.register(UserDetailsPasswordManagerBeanConfig.class).autowire(); this.spring.register(UserDetailsPasswordManagerBeanConfig.class).autowire();
UserDetailsPasswordManagerBeanConfig.Manager manager = this.spring.getContext() UserDetailsPasswordManagerBeanConfig.Manager manager = this.spring.getContext()
.getBean(UserDetailsPasswordManagerBeanConfig.Manager.class); .getBean(UserDetailsPasswordManagerBeanConfig.Manager.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager am = this.spring.getContext()
.getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
given(manager.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(), given(manager.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build()); User.withUserDetails(user).build());
@ -252,7 +271,8 @@ public class AuthenticationConfigurationTests {
throws Exception { throws Exception {
this.spring.register(AuthenticationProviderBeanAndUserDetailsServiceConfig.class).autowire(); this.spring.register(AuthenticationProviderBeanAndUserDetailsServiceConfig.class).autowire();
AuthenticationProvider ap = this.spring.getContext().getBean(AuthenticationProvider.class); AuthenticationProvider ap = this.spring.getContext().getBean(AuthenticationProvider.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager am = this.spring.getContext()
.getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
given(ap.supports(any())).willReturn(true); given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser()); given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
@ -264,7 +284,8 @@ public class AuthenticationConfigurationTests {
public void getAuthenticationWhenAuthenticationProviderBeanThenUsed() throws Exception { public void getAuthenticationWhenAuthenticationProviderBeanThenUsed() throws Exception {
this.spring.register(AuthenticationProviderBeanConfig.class).autowire(); this.spring.register(AuthenticationProviderBeanConfig.class).autowire();
AuthenticationProvider ap = this.spring.getContext().getBean(AuthenticationProvider.class); AuthenticationProvider ap = this.spring.getContext().getBean(AuthenticationProvider.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class) AuthenticationManager am = this.spring.getContext()
.getBean(AuthenticationConfiguration.class)
.getAuthenticationManager(); .getAuthenticationManager();
given(ap.supports(any())).willReturn(true); given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser()); given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
@ -280,8 +301,10 @@ public class AuthenticationConfigurationTests {
@Test @Test
public void enableGlobalMethodSecurityWhenPreAuthorizeThenUsesMethodSecurityService() { public void enableGlobalMethodSecurityWhenPreAuthorizeThenUsesMethodSecurityService() {
this.spring.register(ServicesConfig.class, UsesPreAuthorizeMethodSecurityConfig.class, this.spring
AuthenticationManagerBeanConfig.class).autowire(); .register(ServicesConfig.class, UsesPreAuthorizeMethodSecurityConfig.class,
AuthenticationManagerBeanConfig.class)
.autowire();
// no exception // no exception
} }
@ -312,8 +335,10 @@ public class AuthenticationConfigurationTests {
@Test @Test
public void configureWhenCustomAuthenticationEventPublisherThenCustomAuthenticationEventPublisher() { public void configureWhenCustomAuthenticationEventPublisherThenCustomAuthenticationEventPublisher() {
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, this.spring
CustomAuthenticationEventPublisherConfig.class).autowire(); .register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
CustomAuthenticationEventPublisherConfig.class)
.autowire();
AuthenticationManagerBuilder authenticationManagerBuilder = this.spring.getContext() AuthenticationManagerBuilder authenticationManagerBuilder = this.spring.getContext()
.getBean(AuthenticationManagerBuilder.class); .getBean(AuthenticationManagerBuilder.class);
AuthenticationEventPublisher eventPublisher = (AuthenticationEventPublisher) ReflectionTestUtils AuthenticationEventPublisher eventPublisher = (AuthenticationEventPublisher) ReflectionTestUtils

View File

@ -118,8 +118,9 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser @WithMockUser
public void contextRefreshWhenUsingAspectJThenAutowire() throws Exception { public void contextRefreshWhenUsingAspectJThenAutowire() throws Exception {
this.spring.register(AspectJModeConfig.class, MethodSecurityServiceConfig.class).autowire(); this.spring.register(AspectJModeConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.spring.getContext().getBean( assertThat(this.spring.getContext()
Class.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect"))) .getBean(Class
.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect")))
.isNotNull(); .isNotNull();
assertThat(this.spring.getContext().getBean(AspectJMethodSecurityInterceptor.class)).isNotNull(); assertThat(this.spring.getContext().getBean(AspectJMethodSecurityInterceptor.class)).isNotNull();
// TODO diagnose why aspectj isn't weaving method security advice around // TODO diagnose why aspectj isn't weaving method security advice around
@ -130,8 +131,9 @@ public class NamespaceGlobalMethodSecurityTests {
public void contextRefreshWhenUsingAspectJAndCustomGlobalMethodSecurityConfigurationThenAutowire() public void contextRefreshWhenUsingAspectJAndCustomGlobalMethodSecurityConfigurationThenAutowire()
throws Exception { throws Exception {
this.spring.register(AspectJModeExtendsGMSCConfig.class).autowire(); this.spring.register(AspectJModeExtendsGMSCConfig.class).autowire();
assertThat(this.spring.getContext().getBean( assertThat(this.spring.getContext()
Class.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect"))) .getBean(Class
.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect")))
.isNotNull(); .isNotNull();
assertThat(this.spring.getContext().getBean(AspectJMethodSecurityInterceptor.class)).isNotNull(); assertThat(this.spring.getContext().getBean(AspectJMethodSecurityInterceptor.class)).isNotNull();
} }
@ -140,7 +142,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser @WithMockUser
public void methodSecurityWhenOrderSpecifiedThenConfigured() { public void methodSecurityWhenOrderSpecifiedThenConfigured() {
this.spring.register(CustomOrderConfig.class, MethodSecurityServiceConfig.class).autowire(); this.spring.register(CustomOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class) assertThat(this.spring.getContext()
.getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(-135); .getOrder()).isEqualTo(-135);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250()); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250());
} }
@ -149,7 +152,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser @WithMockUser
public void methodSecurityWhenOrderUnspecifiedThenConfiguredToLowestPrecedence() { public void methodSecurityWhenOrderUnspecifiedThenConfiguredToLowestPrecedence() {
this.spring.register(DefaultOrderConfig.class, MethodSecurityServiceConfig.class).autowire(); this.spring.register(DefaultOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class) assertThat(this.spring.getContext()
.getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); .getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250()); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250());
} }
@ -159,7 +163,8 @@ public class NamespaceGlobalMethodSecurityTests {
public void methodSecurityWhenOrderUnspecifiedAndCustomGlobalMethodSecurityConfigurationThenConfiguredToLowestPrecedence() { public void methodSecurityWhenOrderUnspecifiedAndCustomGlobalMethodSecurityConfigurationThenConfiguredToLowestPrecedence() {
this.spring.register(DefaultOrderExtendsMethodSecurityConfig.class, MethodSecurityServiceConfig.class) this.spring.register(DefaultOrderExtendsMethodSecurityConfig.class, MethodSecurityServiceConfig.class)
.autowire(); .autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class) assertThat(this.spring.getContext()
.getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); .getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250()); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250());
} }

View File

@ -116,7 +116,8 @@ public class PrePostMethodSecurityConfigurationTests {
public void preAuthorizeNotAnonymousWhenRoleAnonymousThenAccessDeniedException() { public void preAuthorizeNotAnonymousWhenRoleAnonymousThenAccessDeniedException() {
this.spring.register(MethodSecurityServiceConfig.class).autowire(); this.spring.register(MethodSecurityServiceConfig.class).autowire();
assertThatExceptionOfType(AccessDeniedException.class) assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(this.methodSecurityService::preAuthorizeNotAnonymous).withMessage("Access Denied"); .isThrownBy(this.methodSecurityService::preAuthorizeNotAnonymous)
.withMessage("Access Denied");
} }
@WithMockUser @WithMockUser
@ -196,7 +197,8 @@ public class PrePostMethodSecurityConfigurationTests {
public void postHasPermissionWhenParameterIsNotGrantThenAccessDeniedException() { public void postHasPermissionWhenParameterIsNotGrantThenAccessDeniedException() {
this.spring.register(CustomPermissionEvaluatorConfig.class, MethodSecurityServiceConfig.class).autowire(); this.spring.register(CustomPermissionEvaluatorConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatExceptionOfType(AccessDeniedException.class) assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.methodSecurityService.postHasPermission("deny")).withMessage("Access Denied"); .isThrownBy(() -> this.methodSecurityService.postHasPermission("deny"))
.withMessage("Access Denied");
} }
@WithMockUser @WithMockUser
@ -212,7 +214,8 @@ public class PrePostMethodSecurityConfigurationTests {
public void postAnnotationWhenParameterIsNotGrantThenAccessDeniedException() { public void postAnnotationWhenParameterIsNotGrantThenAccessDeniedException() {
this.spring.register(MethodSecurityServiceConfig.class).autowire(); this.spring.register(MethodSecurityServiceConfig.class).autowire();
assertThatExceptionOfType(AccessDeniedException.class) assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.methodSecurityService.postAnnotation("deny")).withMessage("Access Denied"); .isThrownBy(() -> this.methodSecurityService.postAnnotation("deny"))
.withMessage("Access Denied");
} }
@WithMockUser @WithMockUser
@ -425,7 +428,8 @@ public class PrePostMethodSecurityConfigurationTests {
@Test @Test
public void configureWhenBeanOverridingDisallowedThenWorks() { public void configureWhenBeanOverridingDisallowedThenWorks() {
this.spring.register(MethodSecurityServiceConfig.class, BusinessServiceConfig.class) this.spring.register(MethodSecurityServiceConfig.class, BusinessServiceConfig.class)
.postProcessor(disallowBeanOverriding()).autowire(); .postProcessor(disallowBeanOverriding())
.autowire();
} }
private static Consumer<ConfigurableWebApplicationContext> disallowBeanOverriding() { private static Consumer<ConfigurableWebApplicationContext> disallowBeanOverriding() {

View File

@ -188,7 +188,8 @@ public class AbstractRequestMatcherRegistryTests {
mockMvcPresentClasspath(true); mockMvcPresentClasspath(true);
mockMvcIntrospector(false); mockMvcIntrospector(false);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class) assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> this.matcherRegistry.requestMatchers("/path")).withMessageContaining( .isThrownBy(() -> this.matcherRegistry.requestMatchers("/path"))
.withMessageContaining(
"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext"); "Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
} }

View File

@ -78,8 +78,8 @@ public class WebSecurityConfigurerAdapterMockitoTests {
@Test @Test
public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() { public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() {
DefaultConfigurer configurer = new DefaultConfigurer(); DefaultConfigurer configurer = new DefaultConfigurer();
this.springFactoriesLoader.when( this.springFactoriesLoader
() -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader())) .when(() -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
.thenReturn(Arrays.asList(configurer)); .thenReturn(Arrays.asList(configurer));
loadConfig(Config.class); loadConfig(Config.class);
assertThat(configurer.init).isTrue(); assertThat(configurer.init).isTrue();
@ -96,9 +96,11 @@ public class WebSecurityConfigurerAdapterMockitoTests {
verify(webAsyncManager, atLeastOnce()).registerCallableInterceptor(any(), verify(webAsyncManager, atLeastOnce()).registerCallableInterceptor(any(),
callableProcessingInterceptorArgCaptor.capture()); callableProcessingInterceptorArgCaptor.capture());
CallableProcessingInterceptor callableProcessingInterceptor = callableProcessingInterceptorArgCaptor CallableProcessingInterceptor callableProcessingInterceptor = callableProcessingInterceptorArgCaptor
.getAllValues().stream() .getAllValues()
.stream()
.filter((e) -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass())) .filter((e) -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
.findFirst().orElse(null); .findFirst()
.orElse(null);
assertThat(callableProcessingInterceptor).isNotNull(); assertThat(callableProcessingInterceptor).isNotNull();
} }

View File

@ -56,17 +56,17 @@ public class HttpSecurityAddFilterTests {
@Test @Test
public void addFilterAfterFilterNotRegisteredYetThenThrowIllegalArgument() { public void addFilterAfterFilterNotRegisteredYetThenThrowIllegalArgument() {
assertThatExceptionOfType(UnsatisfiedDependencyException.class) assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy( .isThrownBy(() -> this.spring.register(MyOtherFilterAfterMyFilterNotRegisteredYetConfig.class).autowire())
() -> this.spring.register(MyOtherFilterAfterMyFilterNotRegisteredYetConfig.class).autowire()) .havingRootCause()
.havingRootCause().isInstanceOf(IllegalArgumentException.class); .isInstanceOf(IllegalArgumentException.class);
} }
@Test @Test
public void addFilterBeforeFilterNotRegisteredYetThenThrowIllegalArgument() { public void addFilterBeforeFilterNotRegisteredYetThenThrowIllegalArgument() {
assertThatExceptionOfType(UnsatisfiedDependencyException.class) assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy( .isThrownBy(() -> this.spring.register(MyOtherFilterBeforeMyFilterNotRegisteredYetConfig.class).autowire())
() -> this.spring.register(MyOtherFilterBeforeMyFilterNotRegisteredYetConfig.class).autowire()) .havingRootCause()
.havingRootCause().isInstanceOf(IllegalArgumentException.class); .isInstanceOf(IllegalArgumentException.class);
} }
@Test @Test
@ -135,7 +135,9 @@ public class HttpSecurityAddFilterTests {
private ListAssert<Class<?>> assertThatFilters() { private ListAssert<Class<?>> assertThatFilters() {
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class); FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
List<Class<?>> filters = filterChain.getFilters("/").stream().map(Object::getClass) List<Class<?>> filters = filterChain.getFilters("/")
.stream()
.map(Object::getClass)
.collect(Collectors.toList()); .collect(Collectors.toList());
return assertThat(filters); return assertThat(filters);
} }

View File

@ -103,7 +103,8 @@ public class NamespaceHttpTests {
@Test // http@access-denied-page @Test // http@access-denied-page
public void configureWhenAccessDeniedPageSetAndRequestForbiddenThenForwardedToAccessDeniedPage() throws Exception { public void configureWhenAccessDeniedPageSetAndRequestForbiddenThenForwardedToAccessDeniedPage() throws Exception {
this.spring.register(AccessDeniedPageConfig.class).autowire(); this.spring.register(AccessDeniedPageConfig.class).autowire();
this.mockMvc.perform(get("/admin").with(user(PasswordEncodedUser.user()))).andExpect(status().isForbidden()) this.mockMvc.perform(get("/admin").with(user(PasswordEncodedUser.user())))
.andExpect(status().isForbidden())
.andExpect(forwardedUrl("/AccessDeniedPage")); .andExpect(forwardedUrl("/AccessDeniedPage"));
} }
@ -610,7 +611,8 @@ public class NamespaceHttpTests {
web.postBuildAction(() -> { web.postBuildAction(() -> {
FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class); FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class);
UseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor UseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor
.getSecurityMetadataSource().getClass(); .getSecurityMetadataSource()
.getClass();
}); });
} }
@ -639,7 +641,8 @@ public class NamespaceHttpTests {
web.postBuildAction(() -> { web.postBuildAction(() -> {
FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class); FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class);
DisableUseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor DisableUseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor
.getSecurityMetadataSource().getClass(); .getSecurityMetadataSource()
.getClass();
}); });
} }

View File

@ -158,8 +158,10 @@ public class HttpSecurityConfigurationTests {
@Test @Test
public void asyncDispatchWhenCustomSecurityContextHolderStrategyThenUses() throws Exception { public void asyncDispatchWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
this.spring.register(DefaultWithFilterChainConfig.class, SecurityContextChangedListenerConfig.class, this.spring
NameController.class).autowire(); .register(DefaultWithFilterChainConfig.class, SecurityContextChangedListenerConfig.class,
NameController.class)
.autowire();
// @formatter:off // @formatter:off
MockHttpServletRequestBuilder requestWithBob = get("/name").with(user("Bob")); MockHttpServletRequestBuilder requestWithBob = get("/name").with(user("Bob"));
MvcResult mvcResult = this.mockMvc.perform(requestWithBob) MvcResult mvcResult = this.mockMvc.perform(requestWithBob)
@ -272,8 +274,10 @@ public class HttpSecurityConfigurationTests {
@Test @Test
public void loginWhenUsingCustomAuthenticationEventPublisherThenAuthenticationEventPublished() throws Exception { public void loginWhenUsingCustomAuthenticationEventPublisherThenAuthenticationEventPublished() throws Exception {
this.spring.register(SecurityEnabledConfig.class, UserDetailsConfig.class, this.spring
CustomAuthenticationEventPublisherConfig.class).autowire(); .register(SecurityEnabledConfig.class, UserDetailsConfig.class,
CustomAuthenticationEventPublisherConfig.class)
.autowire();
CustomAuthenticationEventPublisherConfig.clearEvents(); CustomAuthenticationEventPublisherConfig.clearEvents();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection()); this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
assertThat(CustomAuthenticationEventPublisherConfig.EVENTS).isNotEmpty(); assertThat(CustomAuthenticationEventPublisherConfig.EVENTS).isNotEmpty();
@ -293,8 +297,7 @@ public class HttpSecurityConfigurationTests {
@Test @Test
public void configureWhenAuthorizeHttpRequestsBeforeAuthorizeRequestThenException() { public void configureWhenAuthorizeHttpRequestsBeforeAuthorizeRequestThenException() {
assertThatExceptionOfType(BeanCreationException.class) assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy( .isThrownBy(() -> this.spring.register(AuthorizeHttpRequestsBeforeAuthorizeRequestsConfig.class).autowire())
() -> this.spring.register(AuthorizeHttpRequestsBeforeAuthorizeRequestsConfig.class).autowire())
.withMessageContaining( .withMessageContaining(
"authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one."); "authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one.");
} }
@ -302,8 +305,7 @@ public class HttpSecurityConfigurationTests {
@Test @Test
public void configureWhenAuthorizeHttpRequestsAfterAuthorizeRequestThenException() { public void configureWhenAuthorizeHttpRequestsAfterAuthorizeRequestThenException() {
assertThatExceptionOfType(BeanCreationException.class) assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy( .isThrownBy(() -> this.spring.register(AuthorizeHttpRequestsAfterAuthorizeRequestsConfig.class).autowire())
() -> this.spring.register(AuthorizeHttpRequestsAfterAuthorizeRequestsConfig.class).autowire())
.withMessageContaining( .withMessageContaining(
"authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one."); "authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one.");
} }
@ -311,8 +313,8 @@ public class HttpSecurityConfigurationTests {
@Test @Test
public void configureWhenDefaultConfigurerAsSpringFactoryThenDefaultConfigurerApplied() { public void configureWhenDefaultConfigurerAsSpringFactoryThenDefaultConfigurerApplied() {
DefaultConfigurer configurer = new DefaultConfigurer(); DefaultConfigurer configurer = new DefaultConfigurer();
this.springFactoriesLoader.when( this.springFactoriesLoader
() -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader())) .when(() -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
.thenReturn(Arrays.asList(configurer)); .thenReturn(Arrays.asList(configurer));
this.spring.register(DefaultWithFilterChainConfig.class).autowire(); this.spring.register(DefaultWithFilterChainConfig.class).autowire();
assertThat(configurer.init).isTrue(); assertThat(configurer.init).isTrue();

View File

@ -82,14 +82,16 @@ public class OAuth2ClientConfigurationTests {
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password"); TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class); ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.registrationId(clientRegistrationId).build(); .registrationId(clientRegistrationId)
.build();
given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId))) given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId)))
.willReturn(clientRegistration); .willReturn(clientRegistration);
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class); OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class); OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
given(authorizedClient.getClientRegistration()).willReturn(clientRegistration); given(authorizedClient.getClientRegistration()).willReturn(clientRegistration);
given(authorizedClientRepository.loadAuthorizedClient(eq(clientRegistrationId), eq(authentication), given(authorizedClientRepository.loadAuthorizedClient(eq(clientRegistrationId), eq(authentication),
any(HttpServletRequest.class))).willReturn(authorizedClient); any(HttpServletRequest.class)))
.willReturn(authorizedClient);
OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class); OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
given(authorizedClient.getAccessToken()).willReturn(accessToken); given(authorizedClient.getAccessToken()).willReturn(accessToken);
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class); OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
@ -115,7 +117,8 @@ public class OAuth2ClientConfigurationTests {
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class); OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class); OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials() ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.registrationId(clientRegistrationId).build(); .registrationId(clientRegistrationId)
.build();
given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration); given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration);
// @formatter:off // @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse
@ -143,9 +146,11 @@ public class OAuth2ClientConfigurationTests {
// gh-5321 // gh-5321
@Test @Test
public void loadContextWhenOAuth2AuthorizedClientRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() { public void loadContextWhenOAuth2AuthorizedClientRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() {
assertThatExceptionOfType(BeanCreationException.class).isThrownBy( assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(
() -> this.spring.register(OAuth2AuthorizedClientRepositoryRegisteredTwiceConfig.class).autowire()) () -> this.spring.register(OAuth2AuthorizedClientRepositoryRegisteredTwiceConfig.class).autowire())
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).withMessageContaining( .withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class)
.withMessageContaining(
"Expected single matching bean of type '" + OAuth2AuthorizedClientRepository.class.getName() "Expected single matching bean of type '" + OAuth2AuthorizedClientRepository.class.getName()
+ "' but found 2: authorizedClientRepository1,authorizedClientRepository2"); + "' but found 2: authorizedClientRepository1,authorizedClientRepository2");
} }
@ -153,9 +158,9 @@ public class OAuth2ClientConfigurationTests {
@Test @Test
public void loadContextWhenClientRegistrationRepositoryNotRegisteredThenThrowNoSuchBeanDefinitionException() { public void loadContextWhenClientRegistrationRepositoryNotRegisteredThenThrowNoSuchBeanDefinitionException() {
assertThatExceptionOfType(Exception.class) assertThatExceptionOfType(Exception.class)
.isThrownBy( .isThrownBy(() -> this.spring.register(ClientRegistrationRepositoryNotRegisteredConfig.class).autowire())
() -> this.spring.register(ClientRegistrationRepositoryNotRegisteredConfig.class).autowire()) .withRootCauseInstanceOf(NoSuchBeanDefinitionException.class)
.withRootCauseInstanceOf(NoSuchBeanDefinitionException.class).withMessageContaining( .withMessageContaining(
"No qualifying bean of type '" + ClientRegistrationRepository.class.getName() + "' available"); "No qualifying bean of type '" + ClientRegistrationRepository.class.getName() + "' available");
} }
@ -192,7 +197,8 @@ public class OAuth2ClientConfigurationTests {
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class); OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AuthorizedClientManager authorizedClientManager = mock(OAuth2AuthorizedClientManager.class); OAuth2AuthorizedClientManager authorizedClientManager = mock(OAuth2AuthorizedClientManager.class);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.registrationId(clientRegistrationId).build(); .registrationId(clientRegistrationId)
.build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName, OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName,
TestOAuth2AccessTokens.noScopes()); TestOAuth2AccessTokens.noScopes());
given(authorizedClientManager.authorize(any())).willReturn(authorizedClient); given(authorizedClientManager.authorize(any())).willReturn(authorizedClient);

View File

@ -93,8 +93,10 @@ public class SecurityReactorContextConfigurationResourceServerTests {
@Test @Test
public void requestWhenCustomSecurityContextHolderStrategyThenUses() throws Exception { public void requestWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer(); BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer();
this.spring.register(BearerFilterConfig.class, WebServerConfig.class, Controller.class, this.spring
SecurityContextChangedListenerConfig.class).autowire(); .register(BearerFilterConfig.class, WebServerConfig.class, Controller.class,
SecurityContextChangedListenerConfig.class)
.autowire();
MockHttpServletRequestBuilder authenticatedRequest = get("/token").with(authentication(authentication)); MockHttpServletRequestBuilder authenticatedRequest = get("/token").with(authentication(authentication));
// @formatter:off // @formatter:off
this.mockMvc.perform(authenticatedRequest) this.mockMvc.perform(authenticatedRequest)

View File

@ -181,7 +181,8 @@ public class WebSecurityConfigurationTests {
public void loadConfigWhenSecurityExpressionHandlerIsNullThenException() { public void loadConfigWhenSecurityExpressionHandlerIsNullThenException() {
assertThatExceptionOfType(BeanCreationException.class) assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire()) .isThrownBy(() -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire())
.havingRootCause().isExactlyInstanceOf(IllegalArgumentException.class); .havingRootCause()
.isExactlyInstanceOf(IllegalArgumentException.class);
} }
@Test @Test

View File

@ -69,8 +69,10 @@ public class AnonymousConfigurerTests {
@Test @Test
public void requestWhenCustomSecurityContextHolderStrategyThenUses() throws Exception { public void requestWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
this.spring.register(AnonymousPrincipalInLambdaConfig.class, SecurityContextChangedListenerConfig.class, this.spring
PrincipalController.class).autowire(); .register(AnonymousPrincipalInLambdaConfig.class, SecurityContextChangedListenerConfig.class,
PrincipalController.class)
.autowire();
this.mockMvc.perform(get("/")).andExpect(content().string("principal")); this.mockMvc.perform(get("/")).andExpect(content().string("principal"));
SecurityContextChangedListener listener = this.spring.getContext() SecurityContextChangedListener listener = this.spring.getContext()
.getBean(SecurityContextChangedListener.class); .getBean(SecurityContextChangedListener.class);

View File

@ -86,7 +86,8 @@ public class AuthorizeHttpRequestsConfigurerTests {
@Test @Test
public void configureWhenAuthorizedHttpRequestsAndNoRequestsThenException() { public void configureWhenAuthorizedHttpRequestsAndNoRequestsThenException() {
assertThatExceptionOfType(BeanCreationException.class) assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire()).withMessageContaining( .isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire())
.withMessageContaining(
"At least one mapping is required (for example, authorizeHttpRequests().anyRequest().authenticated())"); "At least one mapping is required (for example, authorizeHttpRequests().anyRequest().authenticated())");
} }

View File

@ -152,8 +152,8 @@ public class AuthorizeRequestsTests {
SecurityContext securityContext = new SecurityContextImpl(); SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(UsernamePasswordAuthenticationToken.authenticated("test", "notused", securityContext.setAuthentication(UsernamePasswordAuthenticationToken.authenticated("test", "notused",
AuthorityUtils.createAuthorityList("ROLE_USER"))); AuthorityUtils.createAuthorityList("ROLE_USER")));
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, this.request.getSession()
securityContext); .setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
} }

View File

@ -67,7 +67,8 @@ public class CorsConfigurerTests {
@Test @Test
public void configureWhenNoMvcThenException() { public void configureWhenNoMvcThenException() {
assertThatExceptionOfType(BeanCreationException.class) assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(DefaultCorsConfig.class).autowire()).withMessageContaining( .isThrownBy(() -> this.spring.register(DefaultCorsConfig.class).autowire())
.withMessageContaining(
"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext"); "Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
} }
@ -82,9 +83,11 @@ public class CorsConfigurerTests {
@Test @Test
public void optionsWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception { public void optionsWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsConfig.class).autowire(); this.spring.register(MvcCorsConfig.class).autowire();
this.mvc.perform(options("/") this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name()) .header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk()) .header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin")) .andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options")); .andExpect(header().exists("X-Content-Type-Options"));
} }
@ -100,9 +103,11 @@ public class CorsConfigurerTests {
@Test @Test
public void optionsWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception { public void optionsWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsInLambdaConfig.class).autowire(); this.spring.register(MvcCorsInLambdaConfig.class).autowire();
this.mvc.perform(options("/") this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name()) .header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk()) .header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin")) .andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options")); .andExpect(header().exists("X-Content-Type-Options"));
} }
@ -118,9 +123,11 @@ public class CorsConfigurerTests {
@Test @Test
public void optionsWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception { public void optionsWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(ConfigSourceConfig.class).autowire(); this.spring.register(ConfigSourceConfig.class).autowire();
this.mvc.perform(options("/") this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name()) .header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk()) .header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin")) .andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options")); .andExpect(header().exists("X-Content-Type-Options"));
} }
@ -138,9 +145,11 @@ public class CorsConfigurerTests {
public void optionsWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() public void optionsWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders()
throws Exception { throws Exception {
this.spring.register(ConfigSourceInLambdaConfig.class).autowire(); this.spring.register(ConfigSourceInLambdaConfig.class).autowire();
this.mvc.perform(options("/") this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name()) .header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk()) .header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin")) .andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options")); .andExpect(header().exists("X-Content-Type-Options"));
} }
@ -156,9 +165,11 @@ public class CorsConfigurerTests {
@Test @Test
public void optionsWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception { public void optionsWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterConfig.class).autowire(); this.spring.register(CorsFilterConfig.class).autowire();
this.mvc.perform(options("/") this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name()) .header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk()) .header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin")) .andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options")); .andExpect(header().exists("X-Content-Type-Options"));
} }
@ -174,9 +185,11 @@ public class CorsConfigurerTests {
@Test @Test
public void optionsWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception { public void optionsWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterInLambdaConfig.class).autowire(); this.spring.register(CorsFilterInLambdaConfig.class).autowire();
this.mvc.perform(options("/") this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name()) .header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk()) .header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin")) .andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options")); .andExpect(header().exists("X-Content-Type-Options"));
} }

View File

@ -206,8 +206,11 @@ public class CsrfConfigurerTests {
public void loginWhenCsrfDisabledThenRedirectsToPreviousPostRequest() throws Exception { public void loginWhenCsrfDisabledThenRedirectsToPreviousPostRequest() throws Exception {
this.spring.register(DisableCsrfEnablesRequestCacheConfig.class).autowire(); this.spring.register(DisableCsrfEnablesRequestCacheConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(post("/to-save")).andReturn(); MvcResult mvcResult = this.mvc.perform(post("/to-save")).andReturn();
this.mvc.perform(post("/login").param("username", "user").param("password", "password") this.mvc
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound()) .perform(post("/login").param("username", "user")
.param("password", "password")
.session((MockHttpSession) mvcResult.getRequest().getSession()))
.andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/to-save")); .andExpect(redirectedUrl("http://localhost/to-save"));
} }
@ -216,11 +219,16 @@ public class CsrfConfigurerTests {
CsrfDisablesPostRequestFromRequestCacheConfig.REPO = mock(CsrfTokenRepository.class); CsrfDisablesPostRequestFromRequestCacheConfig.REPO = mock(CsrfTokenRepository.class);
DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token"); DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadDeferredToken(any(HttpServletRequest.class), given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadDeferredToken(any(HttpServletRequest.class),
any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken)); any(HttpServletResponse.class)))
.willReturn(new TestDeferredCsrfToken(csrfToken));
this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire(); this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(post("/some-url")).andReturn(); MvcResult mvcResult = this.mvc.perform(post("/some-url")).andReturn();
this.mvc.perform(post("/login").param("username", "user").param("password", "password").with(csrf()) this.mvc
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound()) .perform(post("/login").param("username", "user")
.param("password", "password")
.with(csrf())
.session((MockHttpSession) mvcResult.getRequest().getSession()))
.andExpect(status().isFound())
.andExpect(redirectedUrl("/")); .andExpect(redirectedUrl("/"));
verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce()) verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce())
.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class)); .loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
@ -231,11 +239,16 @@ public class CsrfConfigurerTests {
CsrfDisablesPostRequestFromRequestCacheConfig.REPO = mock(CsrfTokenRepository.class); CsrfDisablesPostRequestFromRequestCacheConfig.REPO = mock(CsrfTokenRepository.class);
DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token"); DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadDeferredToken(any(HttpServletRequest.class), given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadDeferredToken(any(HttpServletRequest.class),
any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken)); any(HttpServletResponse.class)))
.willReturn(new TestDeferredCsrfToken(csrfToken));
this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire(); this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/some-url")).andReturn(); MvcResult mvcResult = this.mvc.perform(get("/some-url")).andReturn();
this.mvc.perform(post("/login").param("username", "user").param("password", "password").with(csrf()) this.mvc
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound()) .perform(post("/login").param("username", "user")
.param("password", "password")
.with(csrf())
.session((MockHttpSession) mvcResult.getRequest().getSession()))
.andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/some-url")); .andExpect(redirectedUrl("http://localhost/some-url"));
verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce()) verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce())
.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class)); .loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
@ -245,8 +258,10 @@ public class CsrfConfigurerTests {
@Test @Test
public void postWhenCsrfEnabledAndSessionIsExpiredThenRespondsWithForbidden() throws Exception { public void postWhenCsrfEnabledAndSessionIsExpiredThenRespondsWithForbidden() throws Exception {
this.spring.register(InvalidSessionUrlConfig.class).autowire(); this.spring.register(InvalidSessionUrlConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(post("/").param("_csrf", "abc")).andExpect(status().isFound()) MvcResult mvcResult = this.mvc.perform(post("/").param("_csrf", "abc"))
.andExpect(redirectedUrl("/error/sessionError")).andReturn(); .andExpect(status().isFound())
.andExpect(redirectedUrl("/error/sessionError"))
.andReturn();
this.mvc.perform(post("/").session((MockHttpSession) mvcResult.getRequest().getSession())) this.mvc.perform(post("/").session((MockHttpSession) mvcResult.getRequest().getSession()))
.andExpect(status().isForbidden()); .andExpect(status().isForbidden());
} }
@ -309,7 +324,8 @@ public class CsrfConfigurerTests {
DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token"); DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
given(CsrfTokenRepositoryConfig.REPO.loadToken(any())).willReturn(csrfToken); given(CsrfTokenRepositoryConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfTokenRepositoryConfig.REPO.loadDeferredToken(any(HttpServletRequest.class), given(CsrfTokenRepositoryConfig.REPO.loadDeferredToken(any(HttpServletRequest.class),
any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken)); any(HttpServletResponse.class)))
.willReturn(new TestDeferredCsrfToken(csrfToken));
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire(); this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
// @formatter:off // @formatter:off
MockHttpServletRequestBuilder loginRequest = post("/login") MockHttpServletRequestBuilder loginRequest = post("/login")
@ -440,7 +456,8 @@ public class CsrfConfigurerTests {
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository; CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new CsrfTokenRequestAttributeHandler(); CsrfTokenRequestHandlerConfig.HANDLER = new CsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire(); this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/login")).andExpect(status().isOk()) this.mvc.perform(get("/login"))
.andExpect(status().isOk())
.andExpect(content().string(containsString(csrfToken.getToken()))); .andExpect(content().string(containsString(csrfToken.getToken())));
verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class)); verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository); verifyNoMoreInteractions(csrfTokenRepository);
@ -480,7 +497,8 @@ public class CsrfConfigurerTests {
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository; CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new XorCsrfTokenRequestAttributeHandler(); CsrfTokenRequestHandlerConfig.HANDLER = new XorCsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire(); this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/login")).andExpect(status().isOk()) this.mvc.perform(get("/login"))
.andExpect(status().isOk())
.andExpect(content().string(not(containsString(csrfToken.getToken())))); .andExpect(content().string(not(containsString(csrfToken.getToken()))));
verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class)); verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository); verifyNoMoreInteractions(csrfTokenRepository);

View File

@ -82,28 +82,34 @@ public class DefaultFiltersTests {
@Test @Test
public void nullWebInvocationPrivilegeEvaluator() { public void nullWebInvocationPrivilegeEvaluator() {
this.spring.register(NullWebInvocationPrivilegeEvaluatorConfig.class, UserDetailsServiceConfig.class); this.spring.register(NullWebInvocationPrivilegeEvaluatorConfig.class, UserDetailsServiceConfig.class);
List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class) List<SecurityFilterChain> filterChains = this.spring.getContext()
.getBean(FilterChainProxy.class)
.getFilterChains(); .getFilterChains();
assertThat(filterChains.size()).isEqualTo(1); assertThat(filterChains.size()).isEqualTo(1);
DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0); DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0);
assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class); assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
assertThat(filterChain.getFilters().size()).isEqualTo(1); assertThat(filterChain.getFilters().size()).isEqualTo(1);
long filter = filterChain.getFilters().stream() long filter = filterChain.getFilters()
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter).count(); .stream()
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter)
.count();
assertThat(filter).isEqualTo(1); assertThat(filter).isEqualTo(1);
} }
@Test @Test
public void filterChainProxyBuilderIgnoringResources() { public void filterChainProxyBuilderIgnoringResources() {
this.spring.register(FilterChainProxyBuilderIgnoringConfig.class, UserDetailsServiceConfig.class); this.spring.register(FilterChainProxyBuilderIgnoringConfig.class, UserDetailsServiceConfig.class);
List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class) List<SecurityFilterChain> filterChains = this.spring.getContext()
.getBean(FilterChainProxy.class)
.getFilterChains(); .getFilterChains();
assertThat(filterChains.size()).isEqualTo(2); assertThat(filterChains.size()).isEqualTo(2);
DefaultSecurityFilterChain firstFilter = (DefaultSecurityFilterChain) filterChains.get(0); DefaultSecurityFilterChain firstFilter = (DefaultSecurityFilterChain) filterChains.get(0);
DefaultSecurityFilterChain secondFilter = (DefaultSecurityFilterChain) filterChains.get(1); DefaultSecurityFilterChain secondFilter = (DefaultSecurityFilterChain) filterChains.get(1);
assertThat(firstFilter.getFilters().isEmpty()).isEqualTo(true); assertThat(firstFilter.getFilters().isEmpty()).isEqualTo(true);
assertThat(secondFilter.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class); assertThat(secondFilter.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
List<? extends Class<? extends Filter>> classes = secondFilter.getFilters().stream().map(Filter::getClass) List<? extends Class<? extends Filter>> classes = secondFilter.getFilters()
.stream()
.map(Filter::getClass)
.collect(Collectors.toList()); .collect(Collectors.toList());
assertThat(classes.contains(WebAsyncManagerIntegrationFilter.class)).isTrue(); assertThat(classes.contains(WebAsyncManagerIntegrationFilter.class)).isTrue();
assertThat(classes.contains(SecurityContextPersistenceFilter.class)).isTrue(); assertThat(classes.contains(SecurityContextPersistenceFilter.class)).isTrue();
@ -127,8 +133,9 @@ public class DefaultFiltersTests {
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN"); CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
new HttpSessionCsrfTokenRepository().saveToken(csrfToken, request, response); new HttpSessionCsrfTokenRepository().saveToken(csrfToken, request, response);
request.setParameter(csrfToken.getParameterName(), csrfToken.getToken()); request.setParameter(csrfToken.getParameterName(), csrfToken.getToken());
this.spring.getContext().getBean("springSecurityFilterChain", Filter.class).doFilter(request, response, this.spring.getContext()
new MockFilterChain()); .getBean("springSecurityFilterChain", Filter.class)
.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isEqualTo("/login?logout"); assertThat(response.getRedirectedUrl()).isEqualTo("/login?logout");
} }

View File

@ -374,9 +374,12 @@ public class DefaultLoginPageConfigurerTests {
public void configureWhenAuthenticationEntryPointThenNoDefaultLoginPageGeneratingFilter() { public void configureWhenAuthenticationEntryPointThenNoDefaultLoginPageGeneratingFilter() {
this.spring.register(DefaultLoginWithCustomAuthenticationEntryPointConfig.class).autowire(); this.spring.register(DefaultLoginWithCustomAuthenticationEntryPointConfig.class).autowire();
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class); FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChain.getFilterChains().get(0).getFilters().stream() assertThat(filterChain.getFilterChains()
.filter((filter) -> filter.getClass().isAssignableFrom(DefaultLoginPageGeneratingFilter.class)).count()) .get(0)
.isZero(); .getFilters()
.stream()
.filter((filter) -> filter.getClass().isAssignableFrom(DefaultLoginPageGeneratingFilter.class))
.count()).isZero();
} }
@Test @Test

View File

@ -176,7 +176,8 @@ public class ExceptionHandlingConfigurerTests {
@Test @Test
public void getWhenAcceptIsChromeThenRespondsWith302() throws Exception { public void getWhenAcceptIsChromeThenRespondsWith302() throws Exception {
this.spring.register(DefaultSecurityConfig.class).autowire(); this.spring.register(DefaultSecurityConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, this.mvc
.perform(get("/").header(HttpHeaders.ACCEPT,
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"))
.andExpect(status().isFound()); .andExpect(status().isFound());
} }

View File

@ -90,7 +90,8 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void configureWhenHasRoleStartingWithStringRoleThenException() { public void configureWhenHasRoleStartingWithStringRoleThenException() {
assertThatExceptionOfType(BeanCreationException.class) assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(HasRoleStartingWithRoleConfig.class).autowire()) .isThrownBy(() -> this.spring.register(HasRoleStartingWithRoleConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class).withMessageContaining( .withRootCauseInstanceOf(IllegalArgumentException.class)
.withMessageContaining(
"role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_USER'"); "role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_USER'");
} }
@ -103,7 +104,8 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test @Test
public void configureWhenAuthorizedRequestsAndNoRequestsThenException() { public void configureWhenAuthorizedRequestsAndNoRequestsThenException() {
assertThatExceptionOfType(BeanCreationException.class) assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire()).withMessageContaining( .isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire())
.withMessageContaining(
"At least one mapping is required (i.e. authorizeRequests().anyRequest().authenticated())"); "At least one mapping is required (i.e. authorizeRequests().anyRequest().authenticated())");
} }

View File

@ -616,7 +616,8 @@ public class FormLoginConfigurerTests {
.portMapper(PORT_MAPPER); .portMapper(PORT_MAPPER);
// @formatter:on // @formatter:on
LoginUrlAuthenticationEntryPoint authenticationEntryPoint = (LoginUrlAuthenticationEntryPoint) http LoginUrlAuthenticationEntryPoint authenticationEntryPoint = (LoginUrlAuthenticationEntryPoint) http
.getConfigurer(FormLoginConfigurer.class).getAuthenticationEntryPoint(); .getConfigurer(FormLoginConfigurer.class)
.getAuthenticationEntryPoint();
authenticationEntryPoint.setForceHttps(true); authenticationEntryPoint.setForceHttps(true);
} }

View File

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

View File

@ -75,12 +75,12 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)) MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")) .andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name())) .andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
.andExpect( .andExpect(header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate")) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0")) .andExpect(header().string(HttpHeaders.EXPIRES, "0"))
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache")) .andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn(); .andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder( assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(
HttpHeaders.X_CONTENT_TYPE_OPTIONS, HttpHeaders.X_FRAME_OPTIONS, HttpHeaders.STRICT_TRANSPORT_SECURITY, HttpHeaders.X_CONTENT_TYPE_OPTIONS, HttpHeaders.X_FRAME_OPTIONS, HttpHeaders.STRICT_TRANSPORT_SECURITY,
HttpHeaders.CACHE_CONTROL, HttpHeaders.EXPIRES, HttpHeaders.PRAGMA, HttpHeaders.X_XSS_PROTECTION); HttpHeaders.CACHE_CONTROL, HttpHeaders.EXPIRES, HttpHeaders.PRAGMA, HttpHeaders.X_XSS_PROTECTION);
@ -92,12 +92,12 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)) MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")) .andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name())) .andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
.andExpect( .andExpect(header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate")) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0")) .andExpect(header().string(HttpHeaders.EXPIRES, "0"))
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache")) .andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn(); .andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder( assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(
HttpHeaders.X_CONTENT_TYPE_OPTIONS, HttpHeaders.X_FRAME_OPTIONS, HttpHeaders.STRICT_TRANSPORT_SECURITY, HttpHeaders.X_CONTENT_TYPE_OPTIONS, HttpHeaders.X_FRAME_OPTIONS, HttpHeaders.STRICT_TRANSPORT_SECURITY,
HttpHeaders.CACHE_CONTROL, HttpHeaders.EXPIRES, HttpHeaders.PRAGMA, HttpHeaders.X_XSS_PROTECTION); HttpHeaders.CACHE_CONTROL, HttpHeaders.EXPIRES, HttpHeaders.PRAGMA, HttpHeaders.X_XSS_PROTECTION);
@ -108,7 +108,8 @@ public class HeadersConfigurerTests {
throws Exception { throws Exception {
this.spring.register(ContentTypeOptionsConfig.class).autowire(); this.spring.register(ContentTypeOptionsConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")) MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")).andReturn(); .andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS); assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS);
} }
@ -116,7 +117,8 @@ public class HeadersConfigurerTests {
public void getWhenOnlyContentTypeConfiguredInLambdaThenOnlyContentTypeHeaderInResponse() throws Exception { public void getWhenOnlyContentTypeConfiguredInLambdaThenOnlyContentTypeHeaderInResponse() throws Exception {
this.spring.register(ContentTypeOptionsInLambdaConfig.class).autowire(); this.spring.register(ContentTypeOptionsInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")) MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")).andReturn(); .andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS); assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS);
} }
@ -125,7 +127,8 @@ public class HeadersConfigurerTests {
throws Exception { throws Exception {
this.spring.register(FrameOptionsConfig.class).autowire(); this.spring.register(FrameOptionsConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")) MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name())).andReturn(); .andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_FRAME_OPTIONS); assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_FRAME_OPTIONS);
} }
@ -134,8 +137,7 @@ public class HeadersConfigurerTests {
throws Exception { throws Exception {
this.spring.register(HstsConfig.class).autowire(); this.spring.register(HstsConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)) MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect( .andExpect(header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
.andReturn(); .andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.STRICT_TRANSPORT_SECURITY); assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.STRICT_TRANSPORT_SECURITY);
} }
@ -147,7 +149,8 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)) MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate")) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0")) .andExpect(header().string(HttpHeaders.EXPIRES, "0"))
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache")).andReturn(); .andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(HttpHeaders.CACHE_CONTROL, assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(HttpHeaders.CACHE_CONTROL,
HttpHeaders.EXPIRES, HttpHeaders.PRAGMA); HttpHeaders.EXPIRES, HttpHeaders.PRAGMA);
} }
@ -159,7 +162,8 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)) MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate")) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0")) .andExpect(header().string(HttpHeaders.EXPIRES, "0"))
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache")).andReturn(); .andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(HttpHeaders.CACHE_CONTROL, assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(HttpHeaders.CACHE_CONTROL,
HttpHeaders.EXPIRES, HttpHeaders.PRAGMA); HttpHeaders.EXPIRES, HttpHeaders.PRAGMA);
} }
@ -169,7 +173,8 @@ public class HeadersConfigurerTests {
throws Exception { throws Exception {
this.spring.register(XssProtectionConfig.class).autowire(); this.spring.register(XssProtectionConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)) MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn(); .andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION); assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
} }
@ -178,7 +183,8 @@ public class HeadersConfigurerTests {
throws Exception { throws Exception {
this.spring.register(XssProtectionValueDisabledConfig.class).autowire(); this.spring.register(XssProtectionValueDisabledConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)) MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0")).andReturn(); .andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION); assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
} }
@ -186,7 +192,8 @@ public class HeadersConfigurerTests {
public void getWhenOnlyXssProtectionConfiguredInLambdaThenOnlyXssProtectionHeaderInResponse() throws Exception { public void getWhenOnlyXssProtectionConfiguredInLambdaThenOnlyXssProtectionHeaderInResponse() throws Exception {
this.spring.register(XssProtectionInLambdaConfig.class).autowire(); this.spring.register(XssProtectionInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)) MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn(); .andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION); assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
} }
@ -195,7 +202,8 @@ public class HeadersConfigurerTests {
throws Exception { throws Exception {
this.spring.register(XssProtectionValueDisabledInLambdaConfig.class).autowire(); this.spring.register(XssProtectionValueDisabledInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)) MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0")).andReturn(); .andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION); assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
} }
@ -547,7 +555,8 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/")) MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin")) .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin"))
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp")) .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp"))
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin")).andReturn(); .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY,
HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY); HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY);
} }
@ -559,7 +568,8 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/")) MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin")) .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin"))
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp")) .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp"))
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin")).andReturn(); .andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY,
HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY); HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY);
} }

View File

@ -133,7 +133,8 @@ public class HttpBasicConfigurerTests {
@Test @Test
public void httpBasicWhenDefaultsThenAcceptsBasicCredentials() throws Exception { public void httpBasicWhenDefaultsThenAcceptsBasicCredentials() throws Exception {
this.spring.register(HttpBasic.class, Users.class, Home.class).autowire(); this.spring.register(HttpBasic.class, Users.class, Home.class).autowire();
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isOk()) this.mvc.perform(get("/").with(httpBasic("user", "password")))
.andExpect(status().isOk())
.andExpect(content().string("user")); .andExpect(content().string("user"));
} }
@ -141,7 +142,8 @@ public class HttpBasicConfigurerTests {
public void httpBasicWhenCustomSecurityContextHolderStrategyThenUses() throws Exception { public void httpBasicWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
this.spring.register(HttpBasic.class, Users.class, Home.class, SecurityContextChangedListenerConfig.class) this.spring.register(HttpBasic.class, Users.class, Home.class, SecurityContextChangedListenerConfig.class)
.autowire(); .autowire();
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isOk()) this.mvc.perform(get("/").with(httpBasic("user", "password")))
.andExpect(status().isOk())
.andExpect(content().string("user")); .andExpect(content().string("user"));
SecurityContextChangedListener listener = this.spring.getContext() SecurityContextChangedListener listener = this.spring.getContext()
.getBean(SecurityContextChangedListener.class); .getBean(SecurityContextChangedListener.class);

View File

@ -75,8 +75,8 @@ public class HttpSecurityLogoutTests {
loadConfig(ClearAuthenticationFalseConfig.class); loadConfig(ClearAuthenticationFalseConfig.class);
SecurityContext currentContext = SecurityContextHolder.createEmptyContext(); SecurityContext currentContext = SecurityContextHolder.createEmptyContext();
currentContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER")); currentContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, this.request.getSession()
currentContext); .setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, currentContext);
this.request.setMethod("POST"); this.request.setMethod("POST");
this.request.setServletPath("/logout"); this.request.setServletPath("/logout");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);

View File

@ -546,7 +546,10 @@ public class HttpSecuritySecurityMatchersTests {
@Bean @Bean
UserDetailsService userDetailsService() { UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER") UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build(); .build();
return new InMemoryUserDetailsManager(user); return new InMemoryUserDetailsManager(user);
} }

View File

@ -236,7 +236,8 @@ public class LogoutConfigurerTests {
@Test @Test
public void rememberMeWhenRememberMeServicesNotLogoutHandlerThenRedirectsToLogin() throws Exception { public void rememberMeWhenRememberMeServicesNotLogoutHandlerThenRedirectsToLogin() throws Exception {
this.spring.register(RememberMeNoLogoutHandler.class).autowire(); this.spring.register(RememberMeNoLogoutHandler.class).autowire();
this.mvc.perform(post("/logout").with(csrf())).andExpect(status().isFound()) this.mvc.perform(post("/logout").with(csrf()))
.andExpect(status().isFound())
.andExpect(redirectedUrl("/login?logout")); .andExpect(redirectedUrl("/login?logout"));
} }

View File

@ -198,7 +198,8 @@ public class NamespaceHttpAnonymousTests {
} }
Optional<AnonymousAuthenticationToken> anonymousToken() { Optional<AnonymousAuthenticationToken> anonymousToken() {
return Optional.of(SecurityContextHolder.getContext()).map(SecurityContext::getAuthentication) return Optional.of(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.filter((a) -> a instanceof AnonymousAuthenticationToken) .filter((a) -> a instanceof AnonymousAuthenticationToken)
.map(AnonymousAuthenticationToken.class::cast); .map(AnonymousAuthenticationToken.class::cast);
} }

View File

@ -94,7 +94,9 @@ public class NamespaceHttpCustomFilterTests {
private ListAssert<Class<?>> assertThatFilters() { private ListAssert<Class<?>> assertThatFilters() {
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class); FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
List<Class<?>> filters = filterChain.getFilters("/").stream().map(Object::getClass) List<Class<?>> filters = filterChain.getFilters("/")
.stream()
.map(Object::getClass)
.collect(Collectors.toList()); .collect(Collectors.toList());
return assertThat(filters); return assertThat(filters);
} }

View File

@ -81,7 +81,8 @@ public class NamespaceHttpJeeTests {
User result = new User(user.getName(), "N/A", true, true, true, true, User result = new User(user.getName(), "N/A", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_user")); AuthorityUtils.createAuthorityList("ROLE_user"));
given(bean(AuthenticationUserDetailsService.class).loadUserDetails(any())).willReturn(result); given(bean(AuthenticationUserDetailsService.class).loadUserDetails(any())).willReturn(result);
this.mvc.perform(get("/roles").principal(user)).andExpect(status().isOk()) this.mvc.perform(get("/roles").principal(user))
.andExpect(status().isOk())
.andExpect(content().string("ROLE_user")); .andExpect(content().string("ROLE_user"));
verifyBean(AuthenticationUserDetailsService.class).loadUserDetails(any()); verifyBean(AuthenticationUserDetailsService.class).loadUserDetails(any());
} }

View File

@ -151,7 +151,8 @@ public class NamespaceHttpLogoutTests {
ResultMatcher authenticated(boolean authenticated) { ResultMatcher authenticated(boolean authenticated) {
return (result) -> assertThat(Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()) return (result) -> assertThat(Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::isAuthenticated).orElse(false)).isEqualTo(authenticated); .map(Authentication::isAuthenticated)
.orElse(false)).isEqualTo(authenticated);
} }
ResultMatcher noCookies() { ResultMatcher noCookies() {

View File

@ -104,27 +104,36 @@ public class NamespaceHttpOpenIDLoginTests {
given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.associate(any())) given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.associate(any()))
.willReturn(mockDiscoveryInformation); .willReturn(mockDiscoveryInformation);
given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(), given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
any())).willReturn(mockAuthRequest); any()))
.willReturn(mockAuthRequest);
this.spring.register(OpenIDLoginAttributeExchangeConfig.class).autowire(); this.spring.register(OpenIDLoginAttributeExchangeConfig.class).autowire();
try (MockWebServer server = new MockWebServer()) { try (MockWebServer server = new MockWebServer()) {
String endpoint = server.url("/").toString(); String endpoint = server.url("/").toString();
server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint)); server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint));
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint))); .setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
MvcResult mvcResult = this.mvc.perform(get("/login/openid") MvcResult mvcResult = this.mvc
.param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, "https://www.google.com/1")) .perform(get("/login/openid").param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD,
.andExpect(status().isFound()).andReturn(); "https://www.google.com/1"))
Object attributeObject = mvcResult.getRequest().getSession() .andExpect(status().isFound())
.andReturn();
Object attributeObject = mvcResult.getRequest()
.getSession()
.getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST"); .getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST");
assertThat(attributeObject).isInstanceOf(List.class); assertThat(attributeObject).isInstanceOf(List.class);
List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject; List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject;
assertThat(attributeList.stream().anyMatch((attribute) -> "firstname".equals(attribute.getName()) assertThat(attributeList.stream()
&& "https://axschema.org/namePerson/first".equals(attribute.getType()) && attribute.isRequired())) .anyMatch((attribute) -> "firstname".equals(attribute.getName())
&& "https://axschema.org/namePerson/first".equals(attribute.getType())
&& attribute.isRequired()))
.isTrue(); .isTrue();
assertThat(attributeList.stream().anyMatch((attribute) -> "lastname".equals(attribute.getName()) assertThat(attributeList.stream()
&& "https://axschema.org/namePerson/last".equals(attribute.getType()) && attribute.isRequired())) .anyMatch((attribute) -> "lastname".equals(attribute.getName())
&& "https://axschema.org/namePerson/last".equals(attribute.getType())
&& attribute.isRequired()))
.isTrue(); .isTrue();
assertThat(attributeList.stream().anyMatch((attribute) -> "email".equals(attribute.getName()) assertThat(attributeList.stream()
.anyMatch((attribute) -> "email".equals(attribute.getName())
&& "https://axschema.org/contact/email".equals(attribute.getType()) && attribute.isRequired())) && "https://axschema.org/contact/email".equals(attribute.getType()) && attribute.isRequired()))
.isTrue(); .isTrue();
} }

View File

@ -198,8 +198,9 @@ public class NamespaceSessionManagementTests {
@Test @Test
public void authenticateWhenMigrateSessionFixationProtectionThenMatchesNamespace() throws Exception { public void authenticateWhenMigrateSessionFixationProtectionThenMatchesNamespace() throws Exception {
this.spring.register(SFPMigrateSessionManagementConfig.class, BasicController.class, this.spring
UserDetailsServiceConfig.class).autowire(); .register(SFPMigrateSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
.autowire();
MockHttpSession givenSession = new MockHttpSession(); MockHttpSession givenSession = new MockHttpSession();
String givenSessionId = givenSession.getId(); String givenSessionId = givenSession.getId();
givenSession.setAttribute("name", "value"); givenSession.setAttribute("name", "value");

View File

@ -51,7 +51,8 @@ public class PasswordManagementConfigurerTests {
public void whenChangePasswordPageNotSetThenDefaultChangePasswordPageUsed() throws Exception { public void whenChangePasswordPageNotSetThenDefaultChangePasswordPageUsed() throws Exception {
this.spring.register(PasswordManagementWithDefaultChangePasswordPageConfig.class).autowire(); this.spring.register(PasswordManagementWithDefaultChangePasswordPageConfig.class).autowire();
this.mvc.perform(get("/.well-known/change-password")).andExpect(status().isFound()) this.mvc.perform(get("/.well-known/change-password"))
.andExpect(status().isFound())
.andExpect(redirectedUrl("/change-password")); .andExpect(redirectedUrl("/change-password"));
} }
@ -59,7 +60,8 @@ public class PasswordManagementConfigurerTests {
public void whenChangePasswordPageSetThenSpecifiedChangePasswordPageUsed() throws Exception { public void whenChangePasswordPageSetThenSpecifiedChangePasswordPageUsed() throws Exception {
this.spring.register(PasswordManagementWithCustomChangePasswordPageConfig.class).autowire(); this.spring.register(PasswordManagementWithCustomChangePasswordPageConfig.class).autowire();
this.mvc.perform(get("/.well-known/change-password")).andExpect(status().isFound()) this.mvc.perform(get("/.well-known/change-password"))
.andExpect(status().isFound())
.andExpect(redirectedUrl("/custom-change-password-page")); .andExpect(redirectedUrl("/custom-change-password-page"));
} }

View File

@ -77,7 +77,8 @@ public class PermitAllSupportTests {
@Test @Test
public void configureWhenNotAuthorizeRequestsThenException() { public void configureWhenNotAuthorizeRequestsThenException() {
assertThatExceptionOfType(BeanCreationException.class) assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire()).withMessageContaining( .isThrownBy(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire())
.withMessageContaining(
"permitAll only works with either HttpSecurity.authorizeRequests() or HttpSecurity.authorizeHttpRequests()"); "permitAll only works with either HttpSecurity.authorizeRequests() or HttpSecurity.authorizeHttpRequests()");
} }

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