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(
service, Arrays.asList(mock(Permission.class)));
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));
}

View File

@ -126,7 +126,8 @@ public class AclEntryAfterInvocationProviderTests {
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service,
Arrays.asList(mock(Permission.class)));
assertThat(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null)).isNull();
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null))
.isNull();
verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class));
}

View File

@ -77,8 +77,8 @@ public class AccessControlImplEntryTests {
assertThat(ace).isNotNull();
assertThat(ace).isNotEqualTo(100L);
assertThat(ace).isEqualTo(ace);
assertThat(ace).isEqualTo(
new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true));
assertThat(ace)
.isEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true));
assertThat(ace).isNotEqualTo(
new AccessControlEntryImpl(2L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true));
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));
assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue();
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,
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
assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> rootAcl.isGranted(WRITE,
Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false));

View File

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

View File

@ -47,8 +47,10 @@ public class PermissionTests {
public void expectedIntegerValues() {
assertThat(BasePermission.READ.getMask()).isEqualTo(1);
assertThat(BasePermission.ADMINISTRATION.getMask()).isEqualTo(16);
assertThat(new CumulativePermission().set(BasePermission.READ).set(BasePermission.WRITE)
.set(BasePermission.CREATE).getMask()).isEqualTo(7);
assertThat(new CumulativePermission().set(BasePermission.READ)
.set(BasePermission.WRITE)
.set(BasePermission.CREATE)
.getMask()).isEqualTo(7);
assertThat(new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION).getMask())
.isEqualTo(17);
}
@ -72,12 +74,15 @@ public class PermissionTests {
.isEqualTo("CumulativePermission[..........................EA....=48]");
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ).toString())
.isEqualTo("CumulativePermission[...........................A...R=17]");
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
.clear(BasePermission.ADMINISTRATION).toString())
.isEqualTo("CumulativePermission[...............................R=1]");
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
.clear(BasePermission.ADMINISTRATION).clear(BasePermission.READ).toString())
.isEqualTo("CumulativePermission[................................=0]");
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION)
.set(BasePermission.READ)
.clear(BasePermission.ADMINISTRATION)
.toString()).isEqualTo("CumulativePermission[...............................R=1]");
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION)
.set(BasePermission.READ)
.clear(BasePermission.ADMINISTRATION)
.clear(BasePermission.READ)
.toString()).isEqualTo("CumulativePermission[................................=0]");
}
}

View File

@ -132,7 +132,8 @@ public class CasAuthenticationFilterTests {
assertThat(filter.requiresAuthentication(request, response)).isFalse();
request.setParameter(properties.getArtifactParameter(), "value");
assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key", "principal",
SecurityContextHolder.getContext()
.setAuthentication(new AnonymousAuthenticationToken("key", "principal",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("un", "principal"));

View File

@ -74,8 +74,8 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupRoleAttribute", "cn");
assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupSearchBase", "");
assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupSearchFilter", "(uniqueMember={0})");
assertThat(authoritiesPopulator).extracting("searchControls").hasFieldOrPropertyWithValue("searchScope",
SearchControls.ONELEVEL_SCOPE);
assertThat(authoritiesPopulator).extracting("searchControls")
.hasFieldOrPropertyWithValue("searchScope", SearchControls.ONELEVEL_SCOPE);
assertThat(ReflectionTestUtils.getField(getAuthoritiesMapper(provider), "prefix")).isEqualTo("ROLE_");
}
@ -103,7 +103,8 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
LdapAuthenticationProvider provider = ldapProvider();
assertThat(ReflectionTestUtils.getField(getAuthoritiesPopulator(provider), "searchControls"))
.extracting("searchScope").isEqualTo(SearchControls.SUBTREE_SCOPE);
.extracting("searchScope")
.isEqualTo(SearchControls.SUBTREE_SCOPE);
}
@Test
@ -135,7 +136,8 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
private LdapAuthenticationProvider ldapProvider() {
return ((List<LdapAuthenticationProvider>) ReflectionTestUtils.getField(this.authenticationManager,
"providers")).get(0);
"providers"))
.get(0);
}
private LdapAuthoritiesPopulator getAuthoritiesPopulator(LdapAuthenticationProvider provider) {

View File

@ -137,8 +137,11 @@ public class JwtITests {
}
private Jwt jwt() {
return TestJwts.jwt().claim(IdTokenClaimNames.ISS, "https://issuer.example.com")
.claim(IdTokenClaimNames.SUB, "rob").claim(IdTokenClaimNames.AUD, Arrays.asList("client-id")).build();
return TestJwts.jwt()
.claim(IdTokenClaimNames.ISS, "https://issuer.example.com")
.claim(IdTokenClaimNames.SUB, "rob")
.claim(IdTokenClaimNames.AUD, Arrays.asList("client-id"))
.build();
}
private RSocketRequester.Builder requester() {

View File

@ -80,7 +80,8 @@ public class LdapBindAuthenticationManagerFactoryITests {
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"))));
}
@ -91,7 +92,8 @@ public class LdapBindAuthenticationManagerFactoryITests {
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"))));
}

View File

@ -137,8 +137,8 @@ public class LdapProviderBeanDefinitionParserTests {
ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class);
assertThat(providerManager.getProviders()).hasSize(1);
assertThat(providerManager.getProviders()).extracting("userDetailsContextMapper").allSatisfy(
(contextMapper) -> assertThat(contextMapper).isInstanceOf(InetOrgPersonContextMapper.class));
assertThat(providerManager.getProviders()).extracting("userDetailsContextMapper")
.allSatisfy((contextMapper) -> assertThat(contextMapper).isInstanceOf(InetOrgPersonContextMapper.class));
}
@Test

View File

@ -85,17 +85,19 @@ public final class SecurityNamespaceHandler implements NamespaceHandler {
String version = pkg.getImplementationVersion();
this.logger.info("Spring Security 'config' module version is " + version);
if (version.compareTo(coreVersion) != 0) {
this.logger.error(
"You are running with different versions of the Spring Security 'core' and 'config' modules");
this.logger
.error("You are running with different versions of the Spring Security 'core' and 'config' modules");
}
}
@Override
public BeanDefinition parse(Element element, ParserContext pc) {
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 "
+ "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);
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) {
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);
}

View File

@ -184,7 +184,8 @@ public class AuthenticationConfiguration {
return Collections.emptyList();
}
for (String beanName : beanNamesForType) {
if (((ConfigurableApplicationContext) this.applicationContext).getBeanFactory().getBeanDefinition(beanName)
if (((ConfigurableApplicationContext) this.applicationContext).getBeanFactory()
.getBeanDefinition(beanName)
.isPrimary()) {
list.add(beanName);
}

View File

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

View File

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

View File

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

View File

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

View File

@ -76,7 +76,6 @@ import org.springframework.security.web.SecurityFilterChain;
* </pre>
*
* @see WebSecurityConfigurer
*
* @author Rob Winch
* @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
* integration. This configuration is added whenever {@link EnableWebMvc} is added by
* <a href="
* {@docRoot}/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.html">SpringWebMvcImportSelector</a>
* and the DispatcherServlet is present on the classpath. It also adds the
* {@docRoot}/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.html">SpringWebMvcImportSelector</a> and
* the DispatcherServlet is present on the classpath. It also adds the
* {@link AuthenticationPrincipalArgumentResolver} as a
* {@link HandlerMethodArgumentResolver}.
*

View File

@ -154,7 +154,8 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
this.webSecurity.debug(this.debugEnabled);
}
List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers = new AutowiredWebSecurityConfigurersIgnoreParents(
beanFactory).getWebSecurityConfigurers();
beanFactory)
.getWebSecurityConfigurers();
webSecurityConfigurers.sort(AnnotationAwareOrderComparator.INSTANCE);
Integer previousOrder = null;
Object previousConfig = null;

View File

@ -192,8 +192,8 @@ public final class JeeConfigurer<H extends HttpSecurityBuilder<H>> extends Abstr
PreAuthenticatedAuthenticationProvider authenticationProvider = new PreAuthenticatedAuthenticationProvider();
authenticationProvider.setPreAuthenticatedUserDetailsService(getUserDetailsService());
authenticationProvider = postProcess(authenticationProvider);
http.authenticationProvider(authenticationProvider).setSharedObject(AuthenticationEntryPoint.class,
new Http403ForbiddenEntryPoint());
http.authenticationProvider(authenticationProvider)
.setSharedObject(AuthenticationEntryPoint.class, new Http403ForbiddenEntryPoint());
}
@Override

View File

@ -58,7 +58,8 @@ final class PermitAllSupport {
for (RequestMatcher matcher : requestMatchers) {
if (matcher != null) {
if (configurer != null) {
configurer.getRegistry().addMapping(0, new UrlMapping(matcher,
configurer.getRegistry()
.addMapping(0, new UrlMapping(matcher,
SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll)));
}
else {

View File

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

View File

@ -402,7 +402,8 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
throw new NoUniqueBeanDefinitionException(type, names);
}
if (names.length == 1) {
return (JwtDecoderFactory<ClientRegistration>) this.getBuilder().getSharedObject(ApplicationContext.class)
return (JwtDecoderFactory<ClientRegistration>) this.getBuilder()
.getSharedObject(ApplicationContext.class)
.getBean(names[0]);
}
return null;
@ -742,8 +743,8 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
*/
public UserInfoEndpointConfig userAuthoritiesMapper(GrantedAuthoritiesMapper userAuthoritiesMapper) {
Assert.notNull(userAuthoritiesMapper, "userAuthoritiesMapper cannot be null");
OAuth2LoginConfigurer.this.getBuilder().setSharedObject(GrantedAuthoritiesMapper.class,
userAuthoritiesMapper);
OAuth2LoginConfigurer.this.getBuilder()
.setSharedObject(GrantedAuthoritiesMapper.class, userAuthoritiesMapper);
return this;
}

View File

@ -117,7 +117,12 @@ final class ReactiveOAuth2ClientImportSelector implements ImportSelector {
ReactiveOAuth2AuthorizedClientManager authorizedClientManager = null;
if (this.authorizedClientRepository != null && this.clientRegistrationRepository != null) {
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder().authorizationCode().refreshToken().clientCredentials().password().build();
.builder()
.authorizationCode()
.refreshToken()
.clientCredentials()
.password()
.build();
DefaultReactiveOAuth2AuthorizedClientManager defaultReactiveOAuth2AuthorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, getAuthorizedClientRepository());
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
* configuration integrate with Spring MVC.
*
* @deprecated Use EnableWebSecurity instead which will automatically add the Spring MVC
* related Security items.
* @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
* integration. This configuration is added whenever {@link EnableWebMvc} is added by
* <a href="
* {@docRoot}/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.html">SpringWebMvcImportSelector</a>
* and the DispatcherServlet is present on the classpath. It also adds the
* {@docRoot}/org/springframework/security/config/annotation/web/configuration/SpringWebMvcImportSelector.html">SpringWebMvcImportSelector</a> and
* the DispatcherServlet is present on the classpath. It also adds the
* {@link AuthenticationPrincipalArgumentResolver} as a
* {@link HandlerMethodArgumentResolver}.
*

View File

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

View File

@ -61,7 +61,10 @@ final class WebSocketMessageBrokerSecurityConfiguration
private MessageMatcherDelegatingAuthorizationManager b;
private static final AuthorizationManager<Message<?>> ANY_MESSAGE_AUTHENTICATED = MessageMatcherDelegatingAuthorizationManager
.builder().anyMessage().authenticated().build();
.builder()
.anyMessage()
.authenticated()
.build();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();

View File

@ -64,8 +64,8 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition
String id = element.getAttribute("id");
if (!StringUtils.hasText(id)) {
if (pc.getRegistry().containsBeanDefinition(BeanIds.AUTHENTICATION_MANAGER)) {
pc.getReaderContext().warning("Overriding globally registered AuthenticationManager",
pc.extractSource(element));
pc.getReaderContext()
.warning("Overriding globally registered AuthenticationManager", pc.extractSource(element));
}
id = BeanIds.AUTHENTICATION_MANAGER;
}
@ -124,13 +124,15 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition
return new RuntimeBeanReference(providerId);
}
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));
}
NodeList providerChildren = providerElement.getChildNodes();
for (int i = 0; i < providerChildren.getLength(); i++) {
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));
}
}

View File

@ -46,7 +46,8 @@ public class JdbcUserServiceBeanDefinitionParser extends AbstractUserDetailsServ
builder.addPropertyReference("dataSource", dataSource);
}
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));
}
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("authenticationManager", authManager);
if (authenticationFilterSecurityContextRepositoryRef != null) {
formFilter.getPropertyValues().addPropertyValue("securityContextRepository",
authenticationFilterSecurityContextRepositoryRef);
formFilter.getPropertyValues()
.addPropertyValue("securityContextRepository", authenticationFilterSecurityContextRepositoryRef);
}
formFilter.getPropertyValues().addPropertyValue("securityContextHolderStrategy",
formFilter.getPropertyValues()
.addPropertyValue("securityContextHolderStrategy",
authenticationFilterSecurityContextHolderStrategyRef);
// Id is required by login page filter
this.formFilterId = this.pc.getReaderContext().generateBeanName(formFilter);
@ -353,8 +354,8 @@ final class AuthenticationConfigBuilder {
registerDefaultAuthorizedClientRepositoryIfNecessary(defaultAuthorizedClientRepository);
oauth2LoginFilterBean.getPropertyValues().addPropertyValue("authenticationManager", authManager);
if (authenticationFilterSecurityContextRepositoryRef != null) {
oauth2LoginFilterBean.getPropertyValues().addPropertyValue("securityContextRepository",
authenticationFilterSecurityContextRepositoryRef);
oauth2LoginFilterBean.getPropertyValues()
.addPropertyValue("securityContextRepository", authenticationFilterSecurityContextRepositoryRef);
}
// retrieve the other bean result
@ -451,8 +452,8 @@ final class AuthenticationConfigBuilder {
openIDFilter.getPropertyValues().addPropertyValue("allowSessionCreation", this.allowSessionCreation);
openIDFilter.getPropertyValues().addPropertyValue("authenticationManager", authManager);
if (authenticationFilterSecurityContextRepositoryRef != null) {
openIDFilter.getPropertyValues().addPropertyValue("securityContextRepository",
authenticationFilterSecurityContextRepositoryRef);
openIDFilter.getPropertyValues()
.addPropertyValue("securityContextRepository", authenticationFilterSecurityContextRepositoryRef);
}
// Required by login page filter
this.openIDFilterId = this.pc.getReaderContext().generateBeanName(openIDFilter);
@ -520,8 +521,9 @@ final class AuthenticationConfigBuilder {
String identifierMatch = attrExElt.getAttribute("identifier-match");
if (!StringUtils.hasText(identifierMatch)) {
if (attrExElts.size() > 1) {
this.pc.getReaderContext().error("You must supply an identifier-match attribute if using more"
+ " than one " + Elements.OPENID_ATTRIBUTE_EXCHANGE + " element", attrExElt);
this.pc.getReaderContext()
.error("You must supply an identifier-match attribute if using more" + " than one "
+ Elements.OPENID_ATTRIBUTE_EXCHANGE + " element", attrExElt);
}
// Match anything
identifierMatch = ".*";
@ -572,8 +574,8 @@ final class AuthenticationConfigBuilder {
private void injectRememberMeServicesRef(RootBeanDefinition bean, String rememberMeServicesId) {
if (rememberMeServicesId != null) {
bean.getPropertyValues().addPropertyValue("rememberMeServices",
new RuntimeBeanReference(rememberMeServicesId));
bean.getPropertyValues()
.addPropertyValue("rememberMeServices", new RuntimeBeanReference(rememberMeServicesId));
}
}
@ -697,8 +699,8 @@ final class AuthenticationConfigBuilder {
rolesBuilder.addConstructorArgValue(roles);
rolesBuilder.setFactoryMethod("commaDelimitedListToSet");
RootBeanDefinition mappableRolesRetriever = new RootBeanDefinition(SimpleMappableAttributesRetriever.class);
mappableRolesRetriever.getPropertyValues().addPropertyValue("mappableAttributes",
rolesBuilder.getBeanDefinition());
mappableRolesRetriever.getPropertyValues()
.addPropertyValue("mappableAttributes", rolesBuilder.getBeanDefinition());
adsBldr.addPropertyValue("mappableRolesRetriever", mappableRolesRetriever);
filterBuilder.addPropertyValue("authenticationDetailsSource", adsBldr.getBeanDefinition());
filter = (RootBeanDefinition) filterBuilder.getBeanDefinition();
@ -856,10 +858,10 @@ final class AuthenticationConfigBuilder {
this.anonymousFilter = new RootBeanDefinition(AnonymousAuthenticationFilter.class);
this.anonymousFilter.getConstructorArgumentValues().addIndexedArgumentValue(0, key);
this.anonymousFilter.getConstructorArgumentValues().addIndexedArgumentValue(1, username);
this.anonymousFilter.getConstructorArgumentValues().addIndexedArgumentValue(2,
AuthorityUtils.commaSeparatedStringToAuthorityList(grantedAuthority));
this.anonymousFilter.getPropertyValues().addPropertyValue("securityContextHolderStrategy",
authenticationFilterSecurityContextHolderStrategyRef);
this.anonymousFilter.getConstructorArgumentValues()
.addIndexedArgumentValue(2, AuthorityUtils.commaSeparatedStringToAuthorityList(grantedAuthority));
this.anonymousFilter.getPropertyValues()
.addPropertyValue("securityContextHolderStrategy", authenticationFilterSecurityContextHolderStrategyRef);
this.anonymousFilter.setSource(source);
RootBeanDefinition anonymousProviderBean = new RootBeanDefinition(AnonymousAuthenticationProvider.class);
anonymousProviderBean.getConstructorArgumentValues().addIndexedArgumentValue(0, key);
@ -951,8 +953,8 @@ final class AuthenticationConfigBuilder {
// is used if no openID login page
// has been set.
if (this.formLoginPage != null && this.openIDLoginPage != null) {
this.pc.getReaderContext().error(
"Only one login-page can be defined, either for OpenID or form-login, " + "but not both.",
this.pc.getReaderContext()
.error("Only one login-page can be defined, either for OpenID or form-login, " + "but not both.",
this.pc.extractSource(openIDLoginElt));
}
if (this.formFilterId != null && this.openIDLoginPage == null) {
@ -980,7 +982,8 @@ final class AuthenticationConfigBuilder {
if (this.oauth2LoginEntryPoint != null) {
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 "
+ "specify a custom AuthenticationEntryPoint with the '" + ATT_ENTRY_POINT_REF + "' attribute ",
this.pc.extractSource(this.httpElt));
@ -1025,8 +1028,8 @@ final class AuthenticationConfigBuilder {
SecurityFilters.OAUTH2_AUTHORIZATION_REQUEST_FILTER));
}
if (this.openIDFilterId != null) {
filters.add(
new OrderDecorator(new RuntimeBeanReference(this.openIDFilterId), SecurityFilters.OPENID_FILTER));
filters
.add(new OrderDecorator(new RuntimeBeanReference(this.openIDFilterId), SecurityFilters.OPENID_FILTER));
}
if (this.loginPageGenerationFilter != null) {
filters.add(new OrderDecorator(this.loginPageGenerationFilter, SecurityFilters.LOGIN_PAGE_FILTER));

View File

@ -73,13 +73,14 @@ class AuthorizationFilterParser implements BeanDefinitionParser {
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
if (!isUseExpressions(element)) {
parserContext.getReaderContext().error("AuthorizationManager must be used with `use-expressions=\"true\"",
element);
parserContext.getReaderContext()
.error("AuthorizationManager must be used with `use-expressions=\"true\"", element);
return null;
}
if (StringUtils.hasText(element.getAttribute(ATT_ACCESS_DECISION_MANAGER_REF))) {
parserContext.getReaderContext().error(
"AuthorizationManager cannot be used in conjunction with `access-decision-manager-ref`", element);
parserContext.getReaderContext()
.error("AuthorizationManager cannot be used in conjunction with `access-decision-manager-ref`",
element);
return null;
}
this.authorizationManagerRef = createAuthorizationManager(element, parserContext);
@ -150,8 +151,9 @@ class AuthorizationFilterParser implements BeanDefinitionParser {
servletPath = null;
}
else if (!MatcherType.mvc.equals(matcherType)) {
parserContext.getReaderContext().error(
ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'", urlElt);
parserContext.getReaderContext()
.error(ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'",
urlElt);
}
return hasMatcherRef ? new RuntimeBeanReference(matcherRef)
: 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 filters = chain.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS);
if (!StringUtils.hasText(path)) {
parserContext.getReaderContext().error(
"The attribute '" + HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN + "' must not be empty",
elt);
parserContext.getReaderContext()
.error("The attribute '" + HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN
+ "' must not be empty", elt);
}
if (!StringUtils.hasText(filters)) {
parserContext.getReaderContext().error(
"The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS + "'must not be empty", elt);
parserContext.getReaderContext()
.error("The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS + "'must not be empty",
elt);
}
BeanDefinition matcher = matcherType.createMatcher(parserContext, path, null);
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
for (Element elt : interceptUrls) {
if (StringUtils.hasLength(elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL))) {
parserContext.getReaderContext().error("The attribute '"
+ HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL + "' isn't allowed here.", elt);
parserContext.getReaderContext()
.error("The attribute '" + HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL
+ "' isn't allowed here.", elt);
}
if (StringUtils.hasLength(elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS))) {
parserContext.getReaderContext().error(
"The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS + "' isn't allowed here.",
parserContext.getReaderContext()
.error("The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS + "' isn't allowed here.",
elt);
}
if (StringUtils.hasLength(elt.getAttribute(ATT_SERVLET_PATH))) {
parserContext.getReaderContext().error("The attribute '" + ATT_SERVLET_PATH + "' isn't allowed here.",
elt);
parserContext.getReaderContext()
.error("The attribute '" + ATT_SERVLET_PATH + "' isn't allowed here.", elt);
}
}
BeanDefinition mds = createSecurityMetadataSource(interceptUrls, false, element, parserContext);
@ -159,8 +160,8 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit
servletPath = null;
}
else if (!MatcherType.mvc.equals(matcherType)) {
parserContext.getReaderContext().error(
ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'",
parserContext.getReaderContext()
.error(ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'",
urlElt);
}
BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference(matcherRef)

View File

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

View File

@ -436,9 +436,8 @@ class HttpConfigurationBuilder {
if (sessionControlEnabled) {
if (StringUtils.hasText(sessionAuthStratRef)) {
this.pc.getReaderContext()
.error(ATT_SESSION_AUTH_STRATEGY_REF + " attribute cannot be used"
+ " in combination with <" + Elements.CONCURRENT_SESSIONS + ">",
this.pc.extractSource(sessionCtrlElt));
.error(ATT_SESSION_AUTH_STRATEGY_REF + " attribute cannot be used" + " in combination with <"
+ Elements.CONCURRENT_SESSIONS + ">", this.pc.extractSource(sessionCtrlElt));
}
createConcurrencyControlFilterAndSessionRegistry(sessionCtrlElt);
}
@ -448,8 +447,9 @@ class HttpConfigurationBuilder {
sessionFixationAttribute = OPT_CHANGE_SESSION_ID;
}
else if (StringUtils.hasText(sessionAuthStratRef)) {
this.pc.getReaderContext().error(ATT_SESSION_FIXATION_PROTECTION + " attribute cannot be used"
+ " in combination with " + ATT_SESSION_AUTH_STRATEGY_REF, this.pc.extractSource(sessionMgmtElt));
this.pc.getReaderContext()
.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) {
@ -470,7 +470,8 @@ class HttpConfigurationBuilder {
concurrentSessionStrategy = BeanDefinitionBuilder
.rootBeanDefinition(ConcurrentSessionControlAuthenticationStrategy.class);
concurrentSessionStrategy.addConstructorArgValue(this.sessionRegistryRef);
String maxSessions = this.pc.getReaderContext().getEnvironment()
String maxSessions = this.pc.getReaderContext()
.getEnvironment()
.resolvePlaceholders(sessionCtrlElt.getAttribute("max-sessions"));
if (StringUtils.hasText(maxSessions)) {
concurrentSessionStrategy.addPropertyValue("maximumSessions", maxSessions);
@ -572,8 +573,8 @@ class HttpConfigurationBuilder {
String expiryUrl = element.getAttribute(ATT_EXPIRY_URL);
String expiredSessionStrategyRef = element.getAttribute(ATT_EXPIRED_SESSION_STRATEGY_REF);
if (StringUtils.hasText(expiryUrl) && StringUtils.hasText(expiredSessionStrategyRef)) {
this.pc.getReaderContext().error(
"Cannot use 'expired-url' attribute and 'expired-session-strategy-ref'" + " attribute together.",
this.pc.getReaderContext()
.error("Cannot use 'expired-url' attribute and 'expired-session-strategy-ref'" + " attribute together.",
source);
}
if (StringUtils.hasText(expiryUrl)) {
@ -620,7 +621,8 @@ class HttpConfigurationBuilder {
}
if ("true".equals(provideJaasApi)) {
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
.rootBeanDefinition(DefaultFilterInvocationSecurityMetadataSource.class);
metadataSourceBldr.addConstructorArgValue(channelRequestMap);
channelFilter.getPropertyValues().addPropertyValue("securityMetadataSource",
metadataSourceBldr.getBeanDefinition());
channelFilter.getPropertyValues()
.addPropertyValue("securityMetadataSource", metadataSourceBldr.getBeanDefinition());
RootBeanDefinition channelDecisionManager = new RootBeanDefinition(ChannelDecisionManagerImpl.class);
ManagedList<RootBeanDefinition> channelProcessors = new ManagedList<>(3);
RootBeanDefinition secureChannelProcessor = new RootBeanDefinition(SecureChannelProcessor.class);
@ -738,7 +740,8 @@ class HttpConfigurationBuilder {
// taglibs etc.
BeanDefinition wipe = BeanDefinitionBuilder
.rootBeanDefinition(AuthorizationManagerWebInvocationPrivilegeEvaluator.class)
.addConstructorArgReference(authorizationFilterParser.getAuthorizationManagerRef()).getBeanDefinition();
.addConstructorArgReference(authorizationFilterParser.getAuthorizationManagerRef())
.getBeanDefinition();
this.pc.registerBeanComponent(
new BeanComponentDefinition(wipe, this.pc.getReaderContext().generateBeanName(wipe)));
this.fsi = new RuntimeBeanReference(fsiId);
@ -754,7 +757,8 @@ class HttpConfigurationBuilder {
BeanDefinitionBuilder expressionVoter = BeanDefinitionBuilder.rootBeanDefinition(WebExpressionVoter.class);
// Read the expression handler from the FISMS
RuntimeBeanReference expressionHandler = (RuntimeBeanReference) securityMds.getConstructorArgumentValues()
.getArgumentValue(1, RuntimeBeanReference.class).getValue();
.getArgumentValue(1, RuntimeBeanReference.class)
.getValue();
expressionVoter.addPropertyValue("expressionHandler", expressionHandler);
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
BeanDefinition listFactoryBean = pc.getRegistry().getBeanDefinition(BeanIds.FILTER_CHAINS);
List<BeanReference> filterChains = (List<BeanReference>) listFactoryBean.getPropertyValues()
.getPropertyValue("sourceList").getValue();
.getPropertyValue("sourceList")
.getValue();
filterChains.add(createFilterChain(element, pc));
pc.popAndRegisterContainingComponent();
return null;
@ -131,7 +132,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
validateSecuredFilterChainElement(element, pc);
for (int i = 0; i < element.getChildNodes().getLength(); i++) {
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));
}
}
@ -188,8 +190,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
String filterChainPattern = element.getAttribute(ATT_PATH_PATTERN);
if (StringUtils.hasText(requestMatcherRef)) {
if (StringUtils.hasText(filterChainPattern)) {
pc.getReaderContext().error(
"You can't define a pattern and a request-matcher-ref for the " + "same filter chain",
pc.getReaderContext()
.error("You can't define a pattern and a request-matcher-ref for the " + "same filter chain",
pc.extractSource(element));
}
filterChainMatcher = new RuntimeBeanReference(requestMatcherRef);
@ -254,8 +256,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
RootBeanDefinition clearCredentials = new RootBeanDefinition(
ClearCredentialsMethodInvokingFactoryBean.class);
clearCredentials.getPropertyValues().addPropertyValue("targetObject", parentAuthManager);
clearCredentials.getPropertyValues().addPropertyValue("targetMethod",
"isEraseCredentialsAfterAuthentication");
clearCredentials.getPropertyValues()
.addPropertyValue("targetMethod", "isEraseCredentialsAfterAuthentication");
authManager.addPropertyValue("eraseCredentialsAfterAuthentication", clearCredentials);
}
else {
@ -265,8 +267,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
pc.registerBeanComponent(new BeanComponentDefinition(amfb, amfbId));
RootBeanDefinition clearCredentials = new RootBeanDefinition(MethodInvokingFactoryBean.class);
clearCredentials.getPropertyValues().addPropertyValue("targetObject", new RuntimeBeanReference(amfbId));
clearCredentials.getPropertyValues().addPropertyValue("targetMethod",
"isEraseCredentialsAfterAuthentication");
clearCredentials.getPropertyValues()
.addPropertyValue("targetMethod", "isEraseCredentialsAfterAuthentication");
authManager.addConstructorArgValue(new RuntimeBeanReference(amfbId));
authManager.addPropertyValue("eraseCredentialsAfterAuthentication", clearCredentials);
}
@ -312,7 +314,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
}
RuntimeBeanReference bean = new RuntimeBeanReference(ref);
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));
}
if (StringUtils.hasText(position)) {
@ -386,8 +389,8 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
if (registry.containsBeanDefinition(this.beanName)) {
BeanDefinition beanDefinition = registry.getBeanDefinition(this.targetBeanName);
beanDefinition.getPropertyValues().add(this.targetPropertyName,
new RuntimeBeanReference(this.beanName));
beanDefinition.getPropertyValues()
.add(this.targetPropertyName, new RuntimeBeanReference(this.beanName));
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -109,14 +109,14 @@ class RememberMeBeanDefinitionParser implements BeanDefinitionParser {
if (servicesRefSet && (dataSourceSet || tokenRepoSet || userServiceSet || tokenValiditySet || useSecureCookieSet
|| remembermeParameterSet || remembermeCookieSet)) {
pc.getReaderContext()
.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 + ", "
.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_SECURE_COOKIE + ", " + ATT_FORM_REMEMBERME_PARAMETER + " or " + ATT_REMEMBERME_COOKIE,
source);
}
if (dataSourceSet && tokenRepoSet) {
pc.getReaderContext().error("Specify " + ATT_TOKEN_REPOSITORY + " or " + ATT_DATA_SOURCE + " but not both",
source);
pc.getReaderContext()
.error("Specify " + ATT_TOKEN_REPOSITORY + " or " + ATT_DATA_SOURCE + " but not both", source);
}
boolean isPersistent = dataSourceSet | tokenRepoSet;
if (isPersistent) {
@ -127,8 +127,8 @@ class RememberMeBeanDefinitionParser implements BeanDefinitionParser {
}
else {
tokenRepo = new RootBeanDefinition(JdbcTokenRepositoryImpl.class);
((BeanDefinition) tokenRepo).getPropertyValues().addPropertyValue("dataSource",
new RuntimeBeanReference(dataSource));
((BeanDefinition) tokenRepo).getPropertyValues()
.addPropertyValue("dataSource", new RuntimeBeanReference(dataSource));
}
services.getConstructorArgumentValues().addIndexedArgumentValue(2, tokenRepo);
}
@ -151,7 +151,8 @@ class RememberMeBeanDefinitionParser implements BeanDefinitionParser {
if (tokenValiditySet) {
boolean isTokenValidityNegative = tokenValiditySeconds.startsWith("-");
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);
}
services.getPropertyValues().addPropertyValue("tokenValiditySeconds", tokenValiditySeconds);

View File

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

View File

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

View File

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

View File

@ -64,7 +64,8 @@ final class Saml2LogoutBeanDefinitionParserUtils {
}
return BeanDefinitionBuilder.rootBeanDefinition(
"org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutResponseResolver")
.addConstructorArgValue(registrations).getBeanDefinition();
.addConstructorArgValue(registrations)
.getBeanDefinition();
}
static BeanMetadataElement getLogoutRequestValidator(Element element) {
@ -98,7 +99,8 @@ final class Saml2LogoutBeanDefinitionParserUtils {
}
return BeanDefinitionBuilder.rootBeanDefinition(
"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
.rootBeanDefinition(RequestMatcherRedirectFilter.class)
.addConstructorArgValue(new AntPathRequestMatcher(WELL_KNOWN_CHANGE_PASSWORD_PATTERN))
.addConstructorArgValue(getChangePasswordPage(element)).getBeanDefinition();
.addConstructorArgValue(getChangePasswordPage(element))
.getBeanDefinition();
parserContext.getReaderContext().registerWithGeneratedName(changePasswordFilter);
return changePasswordFilter;
}

View File

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

View File

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

View File

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

View File

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

View File

@ -144,7 +144,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
Element prePostElt = DomUtils.getChildElementByTagName(element, Elements.INVOCATION_HANDLING);
Element expressionHandlerElt = DomUtils.getChildElementByTagName(element, Elements.EXPRESSION_HANDLER);
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);
}
BeanDefinitionBuilder preInvocationVoterBldr = BeanDefinitionBuilder
@ -331,12 +332,12 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP
String accessConfig = childElt.getAttribute(ATT_ACCESS);
String expression = childElt.getAttribute(ATT_EXPRESSION);
if (!StringUtils.hasText(accessConfig)) {
parserContext.getReaderContext().error("Access configuration required",
parserContext.extractSource(childElt));
parserContext.getReaderContext()
.error("Access configuration required", parserContext.extractSource(childElt));
}
if (!StringUtils.hasText(expression)) {
parserContext.getReaderContext().error("Pointcut expression required",
parserContext.extractSource(childElt));
parserContext.getReaderContext()
.error("Pointcut expression required", parserContext.extractSource(childElt));
}
String[] attributeTokens = StringUtils.commaDelimitedListToStringArray(accessConfig);
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,
String runAsManagerId, BeanReference metadataSource, List<BeanMetadataElement> afterInvocationProviders,
Object source, boolean useAspectJ) {
BeanDefinitionBuilder bldr = BeanDefinitionBuilder.rootBeanDefinition(
useAspectJ ? AspectJMethodSecurityInterceptor.class : MethodSecurityInterceptor.class);
BeanDefinitionBuilder bldr = BeanDefinitionBuilder
.rootBeanDefinition(useAspectJ ? AspectJMethodSecurityInterceptor.class : MethodSecurityInterceptor.class);
bldr.getRawBeanDefinition().setSource(source);
bldr.addPropertyReference("accessDecisionManager", accessManagerId);
RootBeanDefinition authMgr = new RootBeanDefinition(AuthenticationManagerDelegator.class);

View File

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

View File

@ -38,7 +38,8 @@ abstract class MethodConfigUtils {
@SuppressWarnings("unchecked")
static void registerDefaultMethodAccessManagerIfNecessary(ParserContext parserContext) {
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));
}
}

View File

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

View File

@ -92,7 +92,8 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
List<ClientRegistration> clientRegistrations = getClientRegistrations(element, parserContext, providers);
BeanDefinition clientRegistrationRepositoryBean = BeanDefinitionBuilder
.rootBeanDefinition(InMemoryClientRegistrationRepository.class)
.addConstructorArgValue(clientRegistrations).getBeanDefinition();
.addConstructorArgValue(clientRegistrations)
.getBeanDefinition();
String clientRegistrationRepositoryId = parserContext.getReaderContext()
.generateBeanName(clientRegistrationRepositoryBean);
parserContext.registerBeanComponent(
@ -124,13 +125,16 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_SECRET))
.ifPresent(builder::clientSecret);
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))
.map(AuthorizationGrantType::new).ifPresent(builder::authorizationGrantType);
.map(AuthorizationGrantType::new)
.ifPresent(builder::authorizationGrantType);
getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_REDIRECT_URI))
.ifPresent(builder::redirectUri);
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))
.ifPresent(builder::clientName);
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_USER_INFO_URI)).ifPresent(builder::userInfoUri);
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_USER_INFO_USER_NAME_ATTRIBUTE))
.ifPresent(builder::userNameAttributeName);
@ -208,7 +213,8 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
}
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);
}
@ -244,7 +250,9 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
private static String getCanonicalName(String name) {
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));
return canonicalName.toString();
}

View File

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

View File

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

View File

@ -181,8 +181,9 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
new RuntimeBeanReference(holderStrategyRef));
}
else {
inboundChannelSecurityInterceptor.addPropertyValue("securityContextHolderStrategy", BeanDefinitionBuilder
.rootBeanDefinition(SecurityContextHolderStrategyFactory.class).getBeanDefinition());
inboundChannelSecurityInterceptor.addPropertyValue("securityContextHolderStrategy",
BeanDefinitionBuilder.rootBeanDefinition(SecurityContextHolderStrategyFactory.class)
.getBeanDefinition());
}
return context.registerWithGeneratedName(inboundChannelSecurityInterceptor.getBeanDefinition());
@ -276,7 +277,8 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements
factoryName = "createSubscribeMatcher";
}
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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -188,7 +188,8 @@ public class AbstractRequestMatcherRegistryTests {
mockMvcPresentClasspath(true);
mockMvcIntrospector(false);
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");
}

View File

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

View File

@ -56,17 +56,17 @@ public class HttpSecurityAddFilterTests {
@Test
public void addFilterAfterFilterNotRegisteredYetThenThrowIllegalArgument() {
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(
() -> this.spring.register(MyOtherFilterAfterMyFilterNotRegisteredYetConfig.class).autowire())
.havingRootCause().isInstanceOf(IllegalArgumentException.class);
.isThrownBy(() -> this.spring.register(MyOtherFilterAfterMyFilterNotRegisteredYetConfig.class).autowire())
.havingRootCause()
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void addFilterBeforeFilterNotRegisteredYetThenThrowIllegalArgument() {
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(
() -> this.spring.register(MyOtherFilterBeforeMyFilterNotRegisteredYetConfig.class).autowire())
.havingRootCause().isInstanceOf(IllegalArgumentException.class);
.isThrownBy(() -> this.spring.register(MyOtherFilterBeforeMyFilterNotRegisteredYetConfig.class).autowire())
.havingRootCause()
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@ -135,7 +135,9 @@ public class HttpSecurityAddFilterTests {
private ListAssert<Class<?>> assertThatFilters() {
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());
return assertThat(filters);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -86,7 +86,8 @@ public class AuthorizeHttpRequestsConfigurerTests {
@Test
public void configureWhenAuthorizedHttpRequestsAndNoRequestsThenException() {
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())");
}

View File

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

View File

@ -67,7 +67,8 @@ public class CorsConfigurerTests {
@Test
public void configureWhenNoMvcThenException() {
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");
}
@ -82,9 +83,11 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
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(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("X-Content-Type-Options"));
}
@ -100,9 +103,11 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
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(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("X-Content-Type-Options"));
}
@ -118,9 +123,11 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception {
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(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("X-Content-Type-Options"));
}
@ -138,9 +145,11 @@ public class CorsConfigurerTests {
public void optionsWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders()
throws Exception {
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(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("X-Content-Type-Options"));
}
@ -156,9 +165,11 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
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(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("X-Content-Type-Options"));
}
@ -174,9 +185,11 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
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(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("X-Content-Type-Options"));
}

View File

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

View File

@ -82,28 +82,34 @@ public class DefaultFiltersTests {
@Test
public void nullWebInvocationPrivilegeEvaluator() {
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();
assertThat(filterChains.size()).isEqualTo(1);
DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0);
assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
assertThat(filterChain.getFilters().size()).isEqualTo(1);
long filter = filterChain.getFilters().stream()
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter).count();
long filter = filterChain.getFilters()
.stream()
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter)
.count();
assertThat(filter).isEqualTo(1);
}
@Test
public void filterChainProxyBuilderIgnoringResources() {
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();
assertThat(filterChains.size()).isEqualTo(2);
DefaultSecurityFilterChain firstFilter = (DefaultSecurityFilterChain) filterChains.get(0);
DefaultSecurityFilterChain secondFilter = (DefaultSecurityFilterChain) filterChains.get(1);
assertThat(firstFilter.getFilters().isEmpty()).isEqualTo(true);
assertThat(secondFilter.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
List<? extends Class<? extends Filter>> classes = secondFilter.getFilters().stream().map(Filter::getClass)
List<? extends Class<? extends Filter>> classes = secondFilter.getFilters()
.stream()
.map(Filter::getClass)
.collect(Collectors.toList());
assertThat(classes.contains(WebAsyncManagerIntegrationFilter.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");
new HttpSessionCsrfTokenRepository().saveToken(csrfToken, request, response);
request.setParameter(csrfToken.getParameterName(), csrfToken.getToken());
this.spring.getContext().getBean("springSecurityFilterChain", Filter.class).doFilter(request, response,
new MockFilterChain());
this.spring.getContext()
.getBean("springSecurityFilterChain", Filter.class)
.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isEqualTo("/login?logout");
}

View File

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

View File

@ -176,7 +176,8 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptIsChromeThenRespondsWith302() throws Exception {
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"))
.andExpect(status().isFound());
}

View File

@ -90,7 +90,8 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void configureWhenHasRoleStartingWithStringRoleThenException() {
assertThatExceptionOfType(BeanCreationException.class)
.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'");
}
@ -103,7 +104,8 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void configureWhenAuthorizedRequestsAndNoRequestsThenException() {
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())");
}

View File

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

View File

@ -49,7 +49,8 @@ public class HeadersConfigurerEagerHeadersTests {
@Test
public void requestWhenHeadersEagerlyConfiguredThenHeadersAreWritten() throws Exception {
this.spring.register(HeadersAtTheBeginningOfRequestConfig.class).autowire();
this.mvc.perform(get("/").secure(true)).andExpect(header().string("X-Content-Type-Options", "nosniff"))
this.mvc.perform(get("/").secure(true))
.andExpect(header().string("X-Content-Type-Options", "nosniff"))
.andExpect(header().string("X-Frame-Options", "DENY"))
.andExpect(header().string("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"))
.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))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
.andExpect(
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
.andExpect(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.EXPIRES, "0"))
.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(
HttpHeaders.X_CONTENT_TYPE_OPTIONS, HttpHeaders.X_FRAME_OPTIONS, HttpHeaders.STRICT_TRANSPORT_SECURITY,
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))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
.andExpect(
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
.andExpect(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.EXPIRES, "0"))
.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(
HttpHeaders.X_CONTENT_TYPE_OPTIONS, HttpHeaders.X_FRAME_OPTIONS, HttpHeaders.STRICT_TRANSPORT_SECURITY,
HttpHeaders.CACHE_CONTROL, HttpHeaders.EXPIRES, HttpHeaders.PRAGMA, HttpHeaders.X_XSS_PROTECTION);
@ -108,7 +108,8 @@ public class HeadersConfigurerTests {
throws Exception {
this.spring.register(ContentTypeOptionsConfig.class).autowire();
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);
}
@ -116,7 +117,8 @@ public class HeadersConfigurerTests {
public void getWhenOnlyContentTypeConfiguredInLambdaThenOnlyContentTypeHeaderInResponse() throws Exception {
this.spring.register(ContentTypeOptionsInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")).andReturn();
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS);
}
@ -125,7 +127,8 @@ public class HeadersConfigurerTests {
throws Exception {
this.spring.register(FrameOptionsConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name())).andReturn();
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_FRAME_OPTIONS);
}
@ -134,8 +137,7 @@ public class HeadersConfigurerTests {
throws Exception {
this.spring.register(HstsConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
.andExpect(header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.STRICT_TRANSPORT_SECURITY);
}
@ -147,7 +149,8 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache")).andReturn();
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(HttpHeaders.CACHE_CONTROL,
HttpHeaders.EXPIRES, HttpHeaders.PRAGMA);
}
@ -159,7 +162,8 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache")).andReturn();
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(HttpHeaders.CACHE_CONTROL,
HttpHeaders.EXPIRES, HttpHeaders.PRAGMA);
}
@ -169,7 +173,8 @@ public class HeadersConfigurerTests {
throws Exception {
this.spring.register(XssProtectionConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn();
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
}
@ -178,7 +183,8 @@ public class HeadersConfigurerTests {
throws Exception {
this.spring.register(XssProtectionValueDisabledConfig.class).autowire();
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);
}
@ -186,7 +192,8 @@ public class HeadersConfigurerTests {
public void getWhenOnlyXssProtectionConfiguredInLambdaThenOnlyXssProtectionHeaderInResponse() throws Exception {
this.spring.register(XssProtectionInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn();
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
.andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
}
@ -195,7 +202,8 @@ public class HeadersConfigurerTests {
throws Exception {
this.spring.register(XssProtectionValueDisabledInLambdaConfig.class).autowire();
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);
}
@ -547,7 +555,8 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/"))
.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_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,
HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY);
}
@ -559,7 +568,8 @@ public class HeadersConfigurerTests {
MvcResult mvcResult = this.mvc.perform(get("/"))
.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_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,
HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY);
}

View File

@ -133,7 +133,8 @@ public class HttpBasicConfigurerTests {
@Test
public void httpBasicWhenDefaultsThenAcceptsBasicCredentials() throws Exception {
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"));
}
@ -141,7 +142,8 @@ public class HttpBasicConfigurerTests {
public void httpBasicWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
this.spring.register(HttpBasic.class, Users.class, Home.class, SecurityContextChangedListenerConfig.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"));
SecurityContextChangedListener listener = this.spring.getContext()
.getBean(SecurityContextChangedListener.class);

View File

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

View File

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

View File

@ -236,7 +236,8 @@ public class LogoutConfigurerTests {
@Test
public void rememberMeWhenRememberMeServicesNotLogoutHandlerThenRedirectsToLogin() throws Exception {
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"));
}

View File

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

View File

@ -94,7 +94,9 @@ public class NamespaceHttpCustomFilterTests {
private ListAssert<Class<?>> assertThatFilters() {
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());
return assertThat(filters);
}

View File

@ -81,7 +81,8 @@ public class NamespaceHttpJeeTests {
User result = new User(user.getName(), "N/A", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_user"));
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"));
verifyBean(AuthenticationUserDetailsService.class).loadUserDetails(any());
}

View File

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

View File

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

View File

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

View File

@ -51,7 +51,8 @@ public class PasswordManagementConfigurerTests {
public void whenChangePasswordPageNotSetThenDefaultChangePasswordPageUsed() throws Exception {
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"));
}
@ -59,7 +60,8 @@ public class PasswordManagementConfigurerTests {
public void whenChangePasswordPageSetThenSpecifiedChangePasswordPageUsed() throws Exception {
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"));
}

View File

@ -77,7 +77,8 @@ public class PermitAllSupportTests {
@Test
public void configureWhenNotAuthorizeRequestsThenException() {
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()");
}

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