Remove WebSecurityConfigurerAdapter

Closes gh-10902
This commit is contained in:
Marcus Da Coregio 2022-09-30 10:31:15 -03:00 committed by Marcus Hert Da Coregio
parent a10b0f526f
commit 35f7e46d05
127 changed files with 2947 additions and 4988 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -33,10 +33,10 @@ import org.springframework.context.annotation.Import;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
@ -70,7 +70,6 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
public void defaultConfiguration() {
this.spring.register(DefaultLdapConfig.class).autowire();
LdapAuthenticationProvider provider = ldapProvider();
LdapAuthoritiesPopulator authoritiesPopulator = getAuthoritiesPopulator(provider);
assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupRoleAttribute", "cn");
assertThat(authoritiesPopulator).hasFieldOrPropertyWithValue("groupSearchBase", "");
@ -160,8 +159,8 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
@EnableWebSecurity
static class DefaultLdapConfig extends BaseLdapProviderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -170,14 +169,20 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
// @formatter:on
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
@Configuration
@EnableWebSecurity
static class GroupRolesConfig extends BaseLdapProviderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -187,14 +192,20 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
// @formatter:on
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
@Configuration
@EnableWebSecurity
static class GroupSearchConfig extends BaseLdapProviderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -204,14 +215,20 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
// @formatter:on
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
@Configuration
@EnableWebSecurity
static class GroupSubtreeSearchConfig extends BaseLdapProviderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -222,14 +239,20 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
// @formatter:on
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
@Configuration
@EnableWebSecurity
static class RolePrefixConfig extends BaseLdapProviderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -239,14 +262,20 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
// @formatter:on
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
@Configuration
@EnableWebSecurity
static class BindAuthenticationConfig extends BaseLdapServerConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -257,14 +286,20 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
// @formatter:on
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
@Configuration
@EnableWebSecurity
static class PasswordEncoderConfig extends BaseLdapServerConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -276,6 +311,12 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
// @formatter:on
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
@Configuration
@ -296,7 +337,7 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
@EnableWebSecurity
@EnableGlobalAuthentication
@Import(ObjectPostProcessorConfiguration.class)
abstract static class BaseLdapProviderConfig extends WebSecurityConfigurerAdapter {
abstract static class BaseLdapProviderConfig {
@Bean
BaseLdapPathContextSource contextSource() throws Exception {
@ -308,15 +349,6 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
return contextSource;
}
@Bean
AuthenticationManager authenticationManager(AuthenticationManagerBuilder auth) throws Exception {
configure(auth);
return auth.build();
}
@Override
protected abstract void configure(AuthenticationManagerBuilder auth) throws Exception;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -26,7 +26,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.ldap.LdapAuthenticationProviderBuilderSecurityBuilderTests.BaseLdapProviderConfig;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.authority.AuthorityUtils;
@ -105,10 +104,10 @@ public class LdapAuthenticationProviderConfigurerTests {
// @formatter:off
SecurityMockMvcRequestBuilders.FormLoginRequestBuilder request = formLogin()
.user("ben")
.password("benspassword");
.user("otherben")
.password("otherbenspassword");
SecurityMockMvcResultMatchers.AuthenticatedMatcher expectedUser = authenticated()
.withUsername("ben")
.withUsername("otherben")
.withAuthorities(
AuthorityUtils.createAuthorityList("ROLE_SUBMANAGERS", "ROLE_MANAGERS", "ROLE_DEVELOPERS"));
// @formatter:on
@ -117,10 +116,10 @@ public class LdapAuthenticationProviderConfigurerTests {
@Configuration
@EnableWebSecurity
static class MultiLdapAuthenticationProvidersConfig extends WebSecurityConfigurerAdapter {
static class MultiLdapAuthenticationProvidersConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -139,10 +138,10 @@ public class LdapAuthenticationProviderConfigurerTests {
@Configuration
@EnableWebSecurity
static class MultiLdapWithCustomRolePrefixAuthenticationProvidersConfig extends WebSecurityConfigurerAdapter {
static class MultiLdapWithCustomRolePrefixAuthenticationProvidersConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -163,10 +162,10 @@ public class LdapAuthenticationProviderConfigurerTests {
@Configuration
@EnableWebSecurity
static class LdapWithRandomPortConfig extends WebSecurityConfigurerAdapter {
static class LdapWithRandomPortConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -174,7 +173,7 @@ public class LdapAuthenticationProviderConfigurerTests {
.groupSearchFilter("(member={0})")
.userDnPatterns("uid={0},ou=people")
.contextSource()
.port(0);
.port(0);
// @formatter:on
}
@ -184,8 +183,8 @@ public class LdapAuthenticationProviderConfigurerTests {
@EnableWebSecurity
static class GroupSubtreeSearchConfig extends BaseLdapProviderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,10 +16,10 @@
package org.springframework.security.config.annotation.authentication.ldap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
import org.springframework.security.ldap.userdetails.PersonContextMapper;
@ -32,10 +32,10 @@ public class NamespaceLdapAuthenticationProviderTestsConfigs {
@Configuration
@EnableWebSecurity
static class LdapAuthenticationProviderConfig extends WebSecurityConfigurerAdapter {
static class LdapAuthenticationProviderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -48,10 +48,10 @@ public class NamespaceLdapAuthenticationProviderTestsConfigs {
@Configuration
@EnableWebSecurity
static class CustomLdapAuthenticationProviderConfig extends WebSecurityConfigurerAdapter {
static class CustomLdapAuthenticationProviderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -70,7 +70,7 @@ public class NamespaceLdapAuthenticationProviderTestsConfigs {
.managerPassword("secret") // ldap-server@manager-password
.port(0) // ldap-server@port
.root("dc=springframework,dc=org"); // ldap-server@root
// .url("ldap://localhost:33389/dc-springframework,dc=org") this overrides root and port and is used for external
// .url("ldap://localhost:33389/dc-springframework,dc=org") this overrides root and port and is used for external
// @formatter:on
}
@ -78,12 +78,12 @@ public class NamespaceLdapAuthenticationProviderTestsConfigs {
@Configuration
@EnableWebSecurity
static class CustomAuthoritiesPopulatorConfig extends WebSecurityConfigurerAdapter {
static class CustomAuthoritiesPopulatorConfig {
static LdapAuthoritiesPopulator LAP;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()
@ -96,10 +96,10 @@ public class NamespaceLdapAuthenticationProviderTestsConfigs {
@Configuration
@EnableWebSecurity
static class PasswordCompareLdapConfig extends WebSecurityConfigurerAdapter {
static class PasswordCompareLdapConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.ldapAuthentication()

View File

@ -28,6 +28,16 @@ sn: Alex
uid: ben
userPassword: {SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=
dn: uid=otherben,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Other Ben Alex
sn: Alex
uid: otherben
userPassword: otherbenspassword
dn: uid=bcrypt,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
@ -75,6 +85,7 @@ cn: developers
ou: developer
member: uid=bcrypt,ou=people,dc=springframework,dc=org
member: uid=ben,ou=people,dc=springframework,dc=org
member: uid=otherben,ou=people,dc=springframework,dc=org
member: uid=bob,ou=people,dc=springframework,dc=org
dn: cn=managers,ou=groups,dc=springframework,dc=org
@ -83,6 +94,7 @@ objectclass: groupOfNames
cn: managers
ou: manager
member: uid=ben,ou=people,dc=springframework,dc=org
member: uid=otherben,ou=people,dc=springframework,dc=org
member: cn=mouse\, jerry,ou=people,dc=springframework,dc=org
dn: cn=submanagers,ou=subgroups,ou=groups,dc=springframework,dc=org
@ -91,3 +103,4 @@ objectclass: groupOfNames
cn: submanagers
ou: submanager
member: uid=ben,ou=people,dc=springframework,dc=org
member: uid=otherben,ou=people,dc=springframework,dc=org

View File

@ -20,6 +20,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@ -32,11 +33,17 @@ import org.springframework.security.authentication.DefaultAuthenticationEventPub
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.DefaultLoginPageConfigurer;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
@ -95,9 +102,8 @@ class HttpSecurityConfiguration {
@Bean(HTTPSECURITY_BEAN_NAME)
@Scope("prototype")
HttpSecurity httpSecurity() throws Exception {
WebSecurityConfigurerAdapter.LazyPasswordEncoder passwordEncoder = new WebSecurityConfigurerAdapter.LazyPasswordEncoder(
this.context);
AuthenticationManagerBuilder authenticationBuilder = new WebSecurityConfigurerAdapter.DefaultPasswordEncoderAuthenticationManagerBuilder(
LazyPasswordEncoder passwordEncoder = new LazyPasswordEncoder(this.context);
AuthenticationManagerBuilder authenticationBuilder = new DefaultPasswordEncoderAuthenticationManagerBuilder(
this.objectPostProcessor, passwordEncoder);
authenticationBuilder.parentAuthenticationManager(authenticationManager());
authenticationBuilder.authenticationEventPublisher(getAuthenticationEventPublisher());
@ -149,4 +155,90 @@ class HttpSecurityConfiguration {
return sharedObjects;
}
static class DefaultPasswordEncoderAuthenticationManagerBuilder extends AuthenticationManagerBuilder {
private PasswordEncoder defaultPasswordEncoder;
/**
* Creates a new instance
* @param objectPostProcessor the {@link ObjectPostProcessor} instance to use.
*/
DefaultPasswordEncoderAuthenticationManagerBuilder(ObjectPostProcessor<Object> objectPostProcessor,
PasswordEncoder defaultPasswordEncoder) {
super(objectPostProcessor);
this.defaultPasswordEncoder = defaultPasswordEncoder;
}
@Override
public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication()
throws Exception {
return super.inMemoryAuthentication().passwordEncoder(this.defaultPasswordEncoder);
}
@Override
public JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication() throws Exception {
return super.jdbcAuthentication().passwordEncoder(this.defaultPasswordEncoder);
}
@Override
public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder, T> userDetailsService(
T userDetailsService) throws Exception {
return super.userDetailsService(userDetailsService).passwordEncoder(this.defaultPasswordEncoder);
}
}
static class LazyPasswordEncoder implements PasswordEncoder {
private ApplicationContext applicationContext;
private PasswordEncoder passwordEncoder;
LazyPasswordEncoder(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public String encode(CharSequence rawPassword) {
return getPasswordEncoder().encode(rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return getPasswordEncoder().matches(rawPassword, encodedPassword);
}
@Override
public boolean upgradeEncoding(String encodedPassword) {
return getPasswordEncoder().upgradeEncoding(encodedPassword);
}
private PasswordEncoder getPasswordEncoder() {
if (this.passwordEncoder != null) {
return this.passwordEncoder;
}
PasswordEncoder passwordEncoder = getBeanOrNull(PasswordEncoder.class);
if (passwordEncoder == null) {
passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
this.passwordEncoder = passwordEncoder;
return passwordEncoder;
}
private <T> T getBeanOrNull(Class<T> type) {
try {
return this.applicationContext.getBean(type);
}
catch (NoSuchBeanDefinitionException ex) {
return null;
}
}
@Override
public String toString() {
return getPasswordEncoder().toString();
}
}
}

View File

@ -37,9 +37,11 @@ import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityConfigurer;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.crypto.RsaKeyConversionServicePostProcessor;
import org.springframework.security.context.DelegatingApplicationListener;
@ -48,7 +50,6 @@ import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
import org.springframework.util.Assert;
/**
* Uses a {@link WebSecurity} to create the {@link FilterChainProxy} that performs the web
@ -81,6 +82,9 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
@Autowired(required = false)
private ObjectPostProcessor<Object> objectObjectPostProcessor;
@Autowired(required = false)
private HttpSecurity httpSecurity;
@Bean
public static DelegatingApplicationListener delegatingApplicationListener() {
return new DelegatingApplicationListener();
@ -99,15 +103,14 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
*/
@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
public Filter springSecurityFilterChain() throws Exception {
boolean hasConfigurers = this.webSecurityConfigurers != null && !this.webSecurityConfigurers.isEmpty();
boolean hasFilterChain = !this.securityFilterChains.isEmpty();
Assert.state(!(hasConfigurers && hasFilterChain),
"Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.");
if (!hasConfigurers && !hasFilterChain) {
WebSecurityConfigurerAdapter adapter = this.objectObjectPostProcessor
.postProcess(new WebSecurityConfigurerAdapter() {
});
this.webSecurity.apply(adapter);
if (!hasFilterChain) {
this.webSecurity.addSecurityFilterChainBuilder(() -> {
this.httpSecurity.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated());
this.httpSecurity.formLogin(Customizer.withDefaults());
this.httpSecurity.httpBasic(Customizer.withDefaults());
return this.httpSecurity.build();
});
}
for (SecurityFilterChain securityFilterChain : this.securityFilterChains) {
this.webSecurity.addSecurityFilterChainBuilder(() -> securityFilterChain);

View File

@ -1,631 +0,0 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.target.LazyInitTargetSource;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.DefaultLoginPageConfigurer;
import org.springframework.security.config.annotation.web.configurers.SecurityContextConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
/**
* Provides a convenient base class for creating a {@link WebSecurityConfigurer} instance.
* The implementation allows customization by overriding methods.
*
* <p>
* Will automatically apply the result of looking up {@link AbstractHttpConfigurer} from
* {@link SpringFactoriesLoader} to allow developers to extend the defaults. To do this,
* you must create a class that extends AbstractHttpConfigurer and then create a file in
* the classpath at "META-INF/spring.factories" that looks something like:
* </p>
* <pre>
* org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyClassThatExtendsAbstractHttpConfigurer
* </pre> If you have multiple classes that should be added you can use "," to separate
* the values. For example:
*
* <pre>
* org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyClassThatExtendsAbstractHttpConfigurer, sample.OtherThatExtendsAbstractHttpConfigurer
* </pre>
*
* @author Rob Winch
* @see EnableWebSecurity
* @deprecated Use a {@link org.springframework.security.web.SecurityFilterChain} Bean to
* configure {@link HttpSecurity} or a {@link WebSecurityCustomizer} Bean to configure
* {@link WebSecurity}
*/
@Order(100)
@Deprecated
public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigurer<WebSecurity> {
private final Log logger = LogFactory.getLog(WebSecurityConfigurerAdapter.class);
private ApplicationContext context;
private ContentNegotiationStrategy contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
private ObjectPostProcessor<Object> objectPostProcessor = new ObjectPostProcessor<Object>() {
@Override
public <T> T postProcess(T object) {
throw new IllegalStateException(ObjectPostProcessor.class.getName()
+ " is a required bean. Ensure you have used @EnableWebSecurity and @Configuration");
}
};
private AuthenticationConfiguration authenticationConfiguration;
private AuthenticationManagerBuilder authenticationBuilder;
private AuthenticationManagerBuilder localConfigureAuthenticationBldr;
private boolean disableLocalConfigureAuthenticationBldr;
private boolean authenticationManagerInitialized;
private AuthenticationManager authenticationManager;
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private HttpSecurity http;
private boolean disableDefaults;
/**
* Creates an instance with the default configuration enabled.
*/
protected WebSecurityConfigurerAdapter() {
this(false);
}
/**
* Creates an instance which allows specifying if the default configuration should be
* enabled. Disabling the default configuration should be considered more advanced
* usage as it requires more understanding of how the framework is implemented.
* @param disableDefaults true if the default configuration should be disabled, else
* false
*/
protected WebSecurityConfigurerAdapter(boolean disableDefaults) {
this.disableDefaults = disableDefaults;
}
/**
* Used by the default implementation of {@link #authenticationManager()} to attempt
* to obtain an {@link AuthenticationManager}. If overridden, the
* {@link AuthenticationManagerBuilder} should be used to specify the
* {@link AuthenticationManager}.
*
* <p>
* The {@link #authenticationManagerBean()} method can be used to expose the resulting
* {@link AuthenticationManager} as a Bean. The {@link #userDetailsServiceBean()} can
* be used to expose the last populated {@link UserDetailsService} that is created
* with the {@link AuthenticationManagerBuilder} as a Bean. The
* {@link UserDetailsService} will also automatically be populated on
* {@link HttpSecurity#getSharedObject(Class)} for use with other
* {@link SecurityContextConfigurer} (i.e. RememberMeConfigurer )
* </p>
*
* <p>
* For example, the following configuration could be used to register in memory
* authentication that exposes an in memory {@link UserDetailsService}:
* </p>
*
* <pre>
* &#064;Override
* protected void configure(AuthenticationManagerBuilder auth) {
* auth
* // enable in memory based authentication with a user named
* // &quot;user&quot; and &quot;admin&quot;
* .inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;).and()
* .withUser(&quot;admin&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;, &quot;ADMIN&quot;);
* }
*
* // Expose the UserDetailsService as a Bean
* &#064;Bean
* &#064;Override
* public UserDetailsService userDetailsServiceBean() throws Exception {
* return super.userDetailsServiceBean();
* }
*
* </pre>
* @param auth the {@link AuthenticationManagerBuilder} to use
* @throws Exception
*/
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
this.disableLocalConfigureAuthenticationBldr = true;
}
/**
* Creates the {@link HttpSecurity} or returns the current instance
* @return the {@link HttpSecurity}
* @throws Exception
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected final HttpSecurity getHttp() throws Exception {
if (this.http != null) {
return this.http;
}
AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher();
this.localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher);
AuthenticationManager authenticationManager = authenticationManager();
this.authenticationBuilder.parentAuthenticationManager(authenticationManager);
Map<Class<?>, Object> sharedObjects = createSharedObjects();
this.http = new HttpSecurity(this.objectPostProcessor, this.authenticationBuilder, sharedObjects);
if (!this.disableDefaults) {
applyDefaultConfiguration(this.http);
ClassLoader classLoader = this.context.getClassLoader();
List<AbstractHttpConfigurer> defaultHttpConfigurers = SpringFactoriesLoader
.loadFactories(AbstractHttpConfigurer.class, classLoader);
for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
this.http.apply(configurer);
}
}
configure(this.http);
return this.http;
}
private void applyDefaultConfiguration(HttpSecurity http) throws Exception {
http.csrf();
http.addFilter(new WebAsyncManagerIntegrationFilter());
http.exceptionHandling();
http.headers();
http.sessionManagement();
http.securityContext();
http.requestCache();
http.anonymous();
http.servletApi();
http.apply(new DefaultLoginPageConfigurer<>());
http.logout();
}
/**
* Override this method to expose the {@link AuthenticationManager} from
* {@link #configure(AuthenticationManagerBuilder)} to be exposed as a Bean. For
* example:
*
* <pre>
* &#064;Bean(name name="myAuthenticationManager")
* &#064;Override
* public AuthenticationManager authenticationManagerBean() throws Exception {
* return super.authenticationManagerBean();
* }
* </pre>
* @return the {@link AuthenticationManager}
* @throws Exception
*/
public AuthenticationManager authenticationManagerBean() throws Exception {
return new AuthenticationManagerDelegator(this.authenticationBuilder, this.context);
}
/**
* Gets the {@link AuthenticationManager} to use. The default strategy is if
* {@link #configure(AuthenticationManagerBuilder)} method is overridden to use the
* {@link AuthenticationManagerBuilder} that was passed in. Otherwise, autowire the
* {@link AuthenticationManager} by type.
* @return the {@link AuthenticationManager} to use
* @throws Exception
*/
protected AuthenticationManager authenticationManager() throws Exception {
if (!this.authenticationManagerInitialized) {
configure(this.localConfigureAuthenticationBldr);
if (this.disableLocalConfigureAuthenticationBldr) {
this.authenticationManager = this.authenticationConfiguration.getAuthenticationManager();
}
else {
this.authenticationManager = this.localConfigureAuthenticationBldr.build();
}
this.authenticationManagerInitialized = true;
}
return this.authenticationManager;
}
/**
* Override this method to expose a {@link UserDetailsService} created from
* {@link #configure(AuthenticationManagerBuilder)} as a bean. In general only the
* following override should be done of this method:
*
* <pre>
* &#064;Bean(name = &quot;myUserDetailsService&quot;)
* // any or no name specified is allowed
* &#064;Override
* public UserDetailsService userDetailsServiceBean() throws Exception {
* return super.userDetailsServiceBean();
* }
* </pre>
*
* To change the instance returned, developers should change
* {@link #userDetailsService()} instead
* @return the {@link UserDetailsService}
* @throws Exception
* @see #userDetailsService()
*/
public UserDetailsService userDetailsServiceBean() throws Exception {
AuthenticationManagerBuilder globalAuthBuilder = this.context.getBean(AuthenticationManagerBuilder.class);
return new UserDetailsServiceDelegator(Arrays.asList(this.localConfigureAuthenticationBldr, globalAuthBuilder));
}
/**
* Allows modifying and accessing the {@link UserDetailsService} from
* {@link #userDetailsServiceBean()} without interacting with the
* {@link ApplicationContext}. Developers should override this method when changing
* the instance of {@link #userDetailsServiceBean()}.
* @return the {@link UserDetailsService} to use
*/
protected UserDetailsService userDetailsService() {
AuthenticationManagerBuilder globalAuthBuilder = this.context.getBean(AuthenticationManagerBuilder.class);
return new UserDetailsServiceDelegator(Arrays.asList(this.localConfigureAuthenticationBldr, globalAuthBuilder));
}
@Override
public void init(WebSecurity web) throws Exception {
HttpSecurity http = getHttp();
web.addSecurityFilterChainBuilder(http);
}
/**
* Override this method to configure {@link WebSecurity}. For example, if you wish to
* ignore certain requests.
*
* Endpoints specified in this method will be ignored by Spring Security, meaning it
* will not protect them from CSRF, XSS, Clickjacking, and so on.
*
* Instead, if you want to protect endpoints against common vulnerabilities, then see
* {@link #configure(HttpSecurity)} and the {@link HttpSecurity#authorizeRequests}
* configuration method.
*/
@Override
public void configure(WebSecurity web) throws Exception {
}
/**
* Override this method to configure the {@link HttpSecurity}. Typically subclasses
* should not invoke this method by calling super as it may override their
* configuration. The default configuration is:
*
* <pre>
* http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
* </pre>
*
* Any endpoint that requires defense against common vulnerabilities can be specified
* here, including public ones. See {@link HttpSecurity#authorizeRequests} and the
* `permitAll()` authorization rule for more details on public endpoints.
* @param http the {@link HttpSecurity} to modify
* @throws Exception if an error occurs
*/
protected void configure(HttpSecurity http) throws Exception {
this.logger.debug("Using default configure(HttpSecurity). "
+ "If subclassed this will potentially override subclass configure(HttpSecurity).");
http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
http.formLogin();
http.httpBasic();
}
/**
* Gets the ApplicationContext
* @return the context
*/
protected final ApplicationContext getApplicationContext() {
return this.context;
}
@Autowired
public void setApplicationContext(ApplicationContext context) {
this.context = context;
ObjectPostProcessor<Object> objectPostProcessor = context.getBean(ObjectPostProcessor.class);
LazyPasswordEncoder passwordEncoder = new LazyPasswordEncoder(context);
this.authenticationBuilder = new DefaultPasswordEncoderAuthenticationManagerBuilder(objectPostProcessor,
passwordEncoder);
this.localConfigureAuthenticationBldr = new DefaultPasswordEncoderAuthenticationManagerBuilder(
objectPostProcessor, passwordEncoder) {
@Override
public AuthenticationManagerBuilder eraseCredentials(boolean eraseCredentials) {
WebSecurityConfigurerAdapter.this.authenticationBuilder.eraseCredentials(eraseCredentials);
return super.eraseCredentials(eraseCredentials);
}
@Override
public AuthenticationManagerBuilder authenticationEventPublisher(
AuthenticationEventPublisher eventPublisher) {
WebSecurityConfigurerAdapter.this.authenticationBuilder.authenticationEventPublisher(eventPublisher);
return super.authenticationEventPublisher(eventPublisher);
}
};
}
@Autowired(required = false)
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
this.trustResolver = trustResolver;
}
@Autowired(required = false)
public void setContentNegotationStrategy(ContentNegotiationStrategy contentNegotiationStrategy) {
this.contentNegotiationStrategy = contentNegotiationStrategy;
}
@Autowired
public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) {
this.objectPostProcessor = objectPostProcessor;
}
@Autowired
public void setAuthenticationConfiguration(AuthenticationConfiguration authenticationConfiguration) {
this.authenticationConfiguration = authenticationConfiguration;
}
private AuthenticationEventPublisher getAuthenticationEventPublisher() {
if (this.context.getBeanNamesForType(AuthenticationEventPublisher.class).length > 0) {
return this.context.getBean(AuthenticationEventPublisher.class);
}
return this.objectPostProcessor.postProcess(new DefaultAuthenticationEventPublisher());
}
/**
* Creates the shared objects
* @return the shared Objects
*/
private Map<Class<?>, Object> createSharedObjects() {
Map<Class<?>, Object> sharedObjects = new HashMap<>();
sharedObjects.putAll(this.localConfigureAuthenticationBldr.getSharedObjects());
sharedObjects.put(UserDetailsService.class, userDetailsService());
sharedObjects.put(ApplicationContext.class, this.context);
sharedObjects.put(ContentNegotiationStrategy.class, this.contentNegotiationStrategy);
sharedObjects.put(AuthenticationTrustResolver.class, this.trustResolver);
return sharedObjects;
}
/**
* Delays the use of the {@link UserDetailsService} from the
* {@link AuthenticationManagerBuilder} to ensure that it has been fully configured.
*
* @author Rob Winch
* @since 3.2
*/
static final class UserDetailsServiceDelegator implements UserDetailsService {
private List<AuthenticationManagerBuilder> delegateBuilders;
private UserDetailsService delegate;
private final Object delegateMonitor = new Object();
UserDetailsServiceDelegator(List<AuthenticationManagerBuilder> delegateBuilders) {
Assert.isTrue(!delegateBuilders.contains(null),
() -> "delegateBuilders cannot contain null values. Got " + delegateBuilders);
this.delegateBuilders = delegateBuilders;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (this.delegate != null) {
return this.delegate.loadUserByUsername(username);
}
synchronized (this.delegateMonitor) {
if (this.delegate == null) {
for (AuthenticationManagerBuilder delegateBuilder : this.delegateBuilders) {
this.delegate = delegateBuilder.getDefaultUserDetailsService();
if (this.delegate != null) {
break;
}
}
if (this.delegate == null) {
throw new IllegalStateException("UserDetailsService is required.");
}
this.delegateBuilders = null;
}
}
return this.delegate.loadUserByUsername(username);
}
}
/**
* Delays the use of the {@link AuthenticationManager} build from the
* {@link AuthenticationManagerBuilder} to ensure that it has been fully configured.
*
* @author Rob Winch
* @since 3.2
*/
static final class AuthenticationManagerDelegator implements AuthenticationManager {
private AuthenticationManagerBuilder delegateBuilder;
private AuthenticationManager delegate;
private final Object delegateMonitor = new Object();
private Set<String> beanNames;
AuthenticationManagerDelegator(AuthenticationManagerBuilder delegateBuilder, ApplicationContext context) {
Assert.notNull(delegateBuilder, "delegateBuilder cannot be null");
Field parentAuthMgrField = ReflectionUtils.findField(AuthenticationManagerBuilder.class,
"parentAuthenticationManager");
ReflectionUtils.makeAccessible(parentAuthMgrField);
this.beanNames = getAuthenticationManagerBeanNames(context);
validateBeanCycle(ReflectionUtils.getField(parentAuthMgrField, delegateBuilder), this.beanNames);
this.delegateBuilder = delegateBuilder;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (this.delegate != null) {
return this.delegate.authenticate(authentication);
}
synchronized (this.delegateMonitor) {
if (this.delegate == null) {
this.delegate = this.delegateBuilder.getObject();
this.delegateBuilder = null;
}
}
return this.delegate.authenticate(authentication);
}
private static Set<String> getAuthenticationManagerBeanNames(ApplicationContext applicationContext) {
String[] beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext,
AuthenticationManager.class);
return new HashSet<>(Arrays.asList(beanNamesForType));
}
private static void validateBeanCycle(Object auth, Set<String> beanNames) {
if (auth == null || beanNames.isEmpty() || !(auth instanceof Advised)) {
return;
}
TargetSource targetSource = ((Advised) auth).getTargetSource();
if (!(targetSource instanceof LazyInitTargetSource)) {
return;
}
LazyInitTargetSource lits = (LazyInitTargetSource) targetSource;
if (beanNames.contains(lits.getTargetBeanName())) {
throw new FatalBeanException(
"A dependency cycle was detected when trying to resolve the AuthenticationManager. "
+ "Please ensure you have configured authentication.");
}
}
}
static class DefaultPasswordEncoderAuthenticationManagerBuilder extends AuthenticationManagerBuilder {
private PasswordEncoder defaultPasswordEncoder;
/**
* Creates a new instance
* @param objectPostProcessor the {@link ObjectPostProcessor} instance to use.
*/
DefaultPasswordEncoderAuthenticationManagerBuilder(ObjectPostProcessor<Object> objectPostProcessor,
PasswordEncoder defaultPasswordEncoder) {
super(objectPostProcessor);
this.defaultPasswordEncoder = defaultPasswordEncoder;
}
@Override
public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication()
throws Exception {
return super.inMemoryAuthentication().passwordEncoder(this.defaultPasswordEncoder);
}
@Override
public JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication() throws Exception {
return super.jdbcAuthentication().passwordEncoder(this.defaultPasswordEncoder);
}
@Override
public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder, T> userDetailsService(
T userDetailsService) throws Exception {
return super.userDetailsService(userDetailsService).passwordEncoder(this.defaultPasswordEncoder);
}
}
static class LazyPasswordEncoder implements PasswordEncoder {
private ApplicationContext applicationContext;
private PasswordEncoder passwordEncoder;
LazyPasswordEncoder(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public String encode(CharSequence rawPassword) {
return getPasswordEncoder().encode(rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return getPasswordEncoder().matches(rawPassword, encodedPassword);
}
@Override
public boolean upgradeEncoding(String encodedPassword) {
return getPasswordEncoder().upgradeEncoding(encodedPassword);
}
private PasswordEncoder getPasswordEncoder() {
if (this.passwordEncoder != null) {
return this.passwordEncoder;
}
PasswordEncoder passwordEncoder = getBeanOrNull(PasswordEncoder.class);
if (passwordEncoder == null) {
passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
this.passwordEncoder = passwordEncoder;
return passwordEncoder;
}
private <T> T getBeanOrNull(Class<T> type) {
try {
return this.applicationContext.getBean(type);
}
catch (NoSuchBeanDefinitionException ex) {
return null;
}
}
@Override
public String toString() {
return getPasswordEncoder().toString();
}
}
}

View File

@ -40,7 +40,6 @@ import org.springframework.security.config.annotation.authentication.configurati
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
@ -167,10 +166,10 @@ public class AuthenticationManagerBuilderTests {
@Configuration
@EnableWebSecurity
static class MultiAuthenticationProvidersConfig extends WebSecurityConfigurerAdapter {
static class MultiAuthenticationProvidersConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
@ -185,7 +184,7 @@ public class AuthenticationManagerBuilderTests {
@Configuration
@EnableWebSecurity
static class PasswordEncoderGlobalConfig extends WebSecurityConfigurerAdapter {
static class PasswordEncoderGlobalConfig {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
@ -205,10 +204,10 @@ public class AuthenticationManagerBuilderTests {
@Configuration
@EnableWebSecurity
static class PasswordEncoderConfig extends WebSecurityConfigurerAdapter {
static class PasswordEncoderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -23,7 +23,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
@ -76,7 +75,7 @@ public class NamespaceAuthenticationManagerTests {
@Configuration
@EnableWebSecurity
static class EraseCredentialsTrueDefaultConfig extends WebSecurityConfigurerAdapter {
static class EraseCredentialsTrueDefaultConfig {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
@ -91,10 +90,10 @@ public class NamespaceAuthenticationManagerTests {
@Configuration
@EnableWebSecurity
static class EraseCredentialsFalseConfig extends WebSecurityConfigurerAdapter {
static class EraseCredentialsFalseConfig {
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.eraseCredentials(false)
@ -107,7 +106,7 @@ public class NamespaceAuthenticationManagerTests {
@Configuration
@EnableWebSecurity
static class GlobalEraseCredentialsFalseConfig extends WebSecurityConfigurerAdapter {
static class GlobalEraseCredentialsFalseConfig {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,7 +25,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
@ -63,10 +62,10 @@ public class NamespaceAuthenticationProviderTests {
@Configuration
@EnableWebSecurity
static class AuthenticationProviderRefConfig extends WebSecurityConfigurerAdapter {
static class AuthenticationProviderRefConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) {
@Autowired
void configure(AuthenticationManagerBuilder auth) {
// @formatter:off
auth
.authenticationProvider(authenticationProvider());
@ -84,19 +83,18 @@ public class NamespaceAuthenticationProviderTests {
@Configuration
@EnableWebSecurity
static class UserServiceRefConfig extends WebSecurityConfigurerAdapter {
static class UserServiceRefConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.userDetailsService(userDetailsService());
// @formatter:on
}
@Override
@Bean
public UserDetailsService userDetailsService() {
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,7 +28,6 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
@ -72,19 +71,16 @@ public class NamespaceJdbcUserServiceTests {
@Configuration
@EnableWebSecurity
static class JdbcUserServiceConfig extends WebSecurityConfigurerAdapter {
static class JdbcUserServiceConfig {
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
void configure(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception {
// @formatter:off
auth
.jdbcAuthentication()
.withDefaultSchema()
.withUser(PasswordEncodedUser.user())
.dataSource(this.dataSource); // jdbc-user-service@data-source-ref
.dataSource(dataSource); // jdbc-user-service@data-source-ref
// @formatter:on
}
@ -103,18 +99,15 @@ public class NamespaceJdbcUserServiceTests {
@Configuration
@EnableWebSecurity
static class CustomJdbcUserServiceSampleConfig extends WebSecurityConfigurerAdapter {
static class CustomJdbcUserServiceSampleConfig {
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
void configure(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception {
// @formatter:off
auth
.jdbcAuthentication()
// jdbc-user-service@dataSource
.dataSource(this.dataSource)
.dataSource(dataSource)
// jdbc-user-service@cache-ref
.userCache(new CustomUserCache())
// jdbc-user-service@users-byusername-query

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,7 +28,6 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.User;
@ -71,10 +70,10 @@ public class NamespacePasswordEncoderTests {
@Configuration
@EnableWebSecurity
static class PasswordEncoderWithInMemoryConfig extends WebSecurityConfigurerAdapter {
static class PasswordEncoderWithInMemoryConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// @formatter:off
auth
@ -88,10 +87,10 @@ public class NamespacePasswordEncoderTests {
@Configuration
@EnableWebSecurity
static class PasswordEncoderWithJdbcConfig extends WebSecurityConfigurerAdapter {
static class PasswordEncoderWithJdbcConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// @formatter:off
auth
@ -113,10 +112,10 @@ public class NamespacePasswordEncoderTests {
@Configuration
@EnableWebSecurity
static class PasswordEncoderWithUserDetailsServiceConfig extends WebSecurityConfigurerAdapter {
static class PasswordEncoderWithUserDetailsServiceConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// @formatter:off
UserDetails user = User.withUsername("user")

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,10 +25,10 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
@ -58,21 +58,22 @@ public class PasswordEncoderConfigurerTests {
@Configuration
@EnableWebSecurity
static class PasswordEncoderConfig extends WebSecurityConfigurerAdapter {
static class PasswordEncoderConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = passwordEncoder();
// @formatter:off
auth
.inMemoryAuthentication()
.inMemoryAuthentication()
.withUser("user").password(encoder.encode("password")).roles("USER").and()
.passwordEncoder(encoder);
// @formatter:on
}
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
@Bean
@ -84,10 +85,10 @@ public class PasswordEncoderConfigurerTests {
@Configuration
@EnableWebSecurity
static class PasswordEncoderNoAuthManagerLoadsConfig extends WebSecurityConfigurerAdapter {
static class PasswordEncoderNoAuthManagerLoadsConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = passwordEncoder();
// @formatter:off
auth

View File

@ -48,7 +48,6 @@ import org.springframework.security.config.annotation.authentication.builders.Au
import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
@ -510,7 +509,7 @@ public class AuthenticationConfigurationTests {
@Configuration
@EnableWebSecurity
static class Sec2822WebSecurity extends WebSecurityConfigurerAdapter {
static class Sec2822WebSecurity {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -23,16 +23,15 @@ import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.issue50.domain.User;
import org.springframework.security.config.annotation.issue50.repo.UserRepository;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.util.Assert;
/**
@ -42,32 +41,26 @@ import org.springframework.util.Assert;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
public class SecurityConfig {
@Autowired
private UserRepository myUserRepository;
@Override
protected void configure(AuthenticationManagerBuilder auth) {
// @formatter:off
auth
.authenticationProvider(authenticationProvider());
// @formatter:on
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/*").permitAll();
.antMatchers("/*").permitAll()
.and()
.authenticationProvider(authenticationProvider());
// @formatter:on
return http.build();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
AuthenticationManager authenticationManager() {
return authenticationProvider()::authenticate;
}
@Bean

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -33,11 +33,11 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
@ -81,14 +81,15 @@ public class Sec2758Tests {
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
static class SecurityConfig extends WebSecurityConfigurerAdapter {
static class SecurityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().access("hasAnyRole('CUSTOM')");
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -19,11 +19,12 @@ package org.springframework.security.config.annotation.web;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
@ -76,15 +77,16 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
@Configuration
@EnableWebSecurity
static class AntMatchersAfterAnyRequestConfig extends WebSecurityConfigurerAdapter {
static class AntMatchersAfterAnyRequestConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.antMatchers("/demo/**").permitAll();
return http.build();
// @formatter:on
}
@ -92,15 +94,16 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
@Configuration
@EnableWebSecurity
static class MvcMatchersAfterAnyRequestConfig extends WebSecurityConfigurerAdapter {
static class MvcMatchersAfterAnyRequestConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.mvcMatchers("/demo/**").permitAll();
return http.build();
// @formatter:on
}
@ -108,15 +111,16 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
@Configuration
@EnableWebSecurity
static class RegexMatchersAfterAnyRequestConfig extends WebSecurityConfigurerAdapter {
static class RegexMatchersAfterAnyRequestConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.regexMatchers(".*").permitAll();
return http.build();
// @formatter:on
}
@ -124,15 +128,16 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
@Configuration
@EnableWebSecurity
static class AnyRequestAfterItselfConfig extends WebSecurityConfigurerAdapter {
static class AnyRequestAfterItselfConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.anyRequest().permitAll();
return http.build();
// @formatter:on
}
@ -140,15 +145,16 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
@Configuration
@EnableWebSecurity
static class RequestMatchersAfterAnyRequestConfig extends WebSecurityConfigurerAdapter {
static class RequestMatchersAfterAnyRequestConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.requestMatchers(new AntPathRequestMatcher("/**")).permitAll();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,11 +22,12 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
@ -88,10 +89,11 @@ public class HttpSecurityHeadersTests {
@Configuration
@EnableWebSecurity
static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
static class WebSecurityConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
}

View File

@ -1,397 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web;
import java.util.Base64;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Demonstrate the samples.
*
* @author Rob Winch
* @author Joe Grandja
*/
@ExtendWith(SpringTestContextExtension.class)
public class SampleWebSecurityConfigurerAdapterTests {
public final SpringTestContext spring = new SpringTestContext(this);
@Autowired
private FilterChainProxy springSecurityFilterChain;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockFilterChain chain;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "CSRF-TOKEN-TEST");
new HttpSessionCsrfTokenRepository().saveToken(csrfToken, this.request, this.response);
this.request.setParameter(csrfToken.getParameterName(), csrfToken.getToken());
}
@Test
public void helloWorldSampleWhenRequestSecureResourceThenRedirectToLogin() throws Exception {
this.spring.register(HelloWorldWebSecurityConfigurerAdapter.class).autowire();
this.request.addHeader("Accept", "text/html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("http://localhost/login");
}
@Test
public void helloWorldSampleWhenRequestLoginWithoutCredentialsThenRedirectToLogin() throws Exception {
this.spring.register(HelloWorldWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addHeader("Accept", "text/html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/login?error");
}
@Test
public void helloWorldSampleWhenRequestLoginWithValidCredentialsThenRedirectToIndex() throws Exception {
this.spring.register(HelloWorldWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addHeader("Accept", "text/html");
this.request.addParameter("username", "user");
this.request.addParameter("password", "password");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/");
}
@Test
public void readmeSampleWhenRequestSecureResourceThenRedirectToLogin() throws Exception {
this.spring.register(SampleWebSecurityConfigurerAdapter.class).autowire();
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("http://localhost/login");
}
@Test
public void readmeSampleWhenRequestLoginWithoutCredentialsThenRedirectToLogin() throws Exception {
this.spring.register(SampleWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/login?error");
}
@Test
public void readmeSampleWhenRequestLoginWithValidCredentialsThenRedirectToIndex() throws Exception {
this.spring.register(SampleWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addParameter("username", "user");
this.request.addParameter("password", "password");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/");
}
@Test
public void multiHttpSampleWhenRequestSecureResourceThenRedirectToLogin() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("http://localhost/login");
}
@Test
public void multiHttpSampleWhenRequestLoginWithoutCredentialsThenRedirectToLogin() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/login?error");
}
@Test
public void multiHttpSampleWhenRequestLoginWithValidCredentialsThenRedirectToIndex() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addParameter("username", "user");
this.request.addParameter("password", "password");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/");
}
@Test
public void multiHttpSampleWhenRequestProtectedResourceThenStatusUnauthorized() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/api/admin/test");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void multiHttpSampleWhenRequestAdminResourceWithRegularUserThenStatusForbidden() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/api/admin/test");
this.request.addHeader("Authorization",
"Basic " + Base64.getEncoder().encodeToString("user:password".getBytes()));
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@Test
public void multiHttpSampleWhenRequestAdminResourceWithAdminUserThenStatusOk() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/api/admin/test");
this.request.addHeader("Authorization",
"Basic " + Base64.getEncoder().encodeToString("admin:password".getBytes()));
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
/**
* <pre>
* &lt;http&gt;
* &lt;intercept-url pattern="/resources/**" access="permitAll"/&gt;
* &lt;intercept-url pattern="/**" access="authenticated"/&gt;
* &lt;logout
* logout-success-url="/login?logout"
* logout-url="/logout"
* &lt;form-login
* authentication-failure-url="/login?error"
* login-page="/login" &lt;!-- Except Spring Security renders the login page --&gt;
* login-processing-url="/login" &lt;!-- but only POST --&gt;
* password-parameter="password"
* username-parameter="username"
* /&gt;
* &lt;/http&gt;
* &lt;authentication-manager&gt;
* &lt;authentication-provider&gt;
* &lt;user-service&gt;
* &lt;user username="user" password="password" authorities="ROLE_USER"/&gt;
* &lt;/user-service&gt;
* &lt;/authentication-provider&gt;
* &lt;/authentication-manager&gt;
* </pre>
*
* @author Rob Winch
*/
@Configuration
@EnableWebSecurity
public static class HelloWorldWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
}
/**
* <pre>
* &lt;http security="none" pattern="/resources/**"/&gt;
* &lt;http&gt;
* &lt;intercept-url pattern="/logout" access="permitAll"/&gt;
* &lt;intercept-url pattern="/login" access="permitAll"/&gt;
* &lt;intercept-url pattern="/signup" access="permitAll"/&gt;
* &lt;intercept-url pattern="/about" access="permitAll"/&gt;
* &lt;intercept-url pattern="/**" access="hasRole('ROLE_USER')"/&gt;
* &lt;logout
* logout-success-url="/login?logout"
* logout-url="/logout"
* &lt;form-login
* authentication-failure-url="/login?error"
* login-page="/login"
* login-processing-url="/login" &lt;!-- but only POST --&gt;
* password-parameter="password"
* username-parameter="username"
* /&gt;
* &lt;/http&gt;
* &lt;authentication-manager&gt;
* &lt;authentication-provider&gt;
* &lt;user-service&gt;
* &lt;user username="user" password="password" authorities="ROLE_USER"/&gt;
* &lt;user username="admin" password="password" authorities=
"ROLE_USER,ROLE_ADMIN"/&gt;
* &lt;/user-service&gt;
* &lt;/authentication-provider&gt;
* &lt;/authentication-manager&gt;
* </pre>
*
* @author Rob Winch
*/
@Configuration
@EnableWebSecurity
public static class SampleWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/signup", "/about").permitAll()
.anyRequest().hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
// set permitAll for all URLs associated with Form Login
.permitAll();
// @formatter:on
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user())
.withUser(PasswordEncodedUser.admin());
// @formatter:on
}
}
/**
* <code>
* &lt;http security="none" pattern="/resources/**"/&gt;
* &lt;http pattern="/api/**"&gt;
* &lt;intercept-url pattern="/api/admin/**" access="hasRole('ROLE_ADMIN')"/&gt;
* &lt;intercept-url pattern="/api/**" access="hasRole('ROLE_USER')"/&gt;
* &lt;http-basic /&gt;
* &lt;/http&gt;
* &lt;http&gt;
* &lt;intercept-url pattern="/logout" access="permitAll"/&gt;
* &lt;intercept-url pattern="/login" access="permitAll"/&gt;
* &lt;intercept-url pattern="/signup" access="permitAll"/&gt;
* &lt;intercept-url pattern="/about" access="permitAll"/&gt;
* &lt;intercept-url pattern="/**" access="hasRole('ROLE_USER')"/&gt;
* &lt;logout
* logout-success-url="/login?logout"
* logout-url="/logout"
* &lt;form-login
* authentication-failure-url="/login?error"
* login-page="/login"
* login-processing-url="/login" &lt;!-- but only POST --&gt;
* password-parameter="password"
* username-parameter="username"
* /&gt;
* &lt;/http&gt;
* &lt;authentication-manager&gt;
* &lt;authentication-provider&gt;
* &lt;user-service&gt;
* &lt;user username="user" password="password" authorities="ROLE_USER"/&gt;
* &lt;user username="admin" password="password" authorities=
"ROLE_USER,ROLE_ADMIN"/&gt;
* &lt;/user-service&gt;
* &lt;/authentication-provider&gt;
* &lt;/authentication-manager&gt;
* </code>
*
* @author Rob Winch
*/
@Configuration
@EnableWebSecurity
public static class SampleMultiHttpSecurityConfig {
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user())
.withUser(PasswordEncodedUser.admin());
// @formatter:on
}
@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/api/**")
.authorizeRequests()
.antMatchers("/api/admin/**").hasRole("ADMIN")
.antMatchers("/api/**").hasRole("USER")
.and()
.httpBasic();
// @formatter:on
}
}
@Configuration
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/signup", "/about").permitAll()
.anyRequest().hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.permitAll();
// @formatter:on
}
}
}
}

View File

@ -1,161 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web;
import java.util.Arrays;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.web.context.request.async.SecurityContextCallableProcessingInterceptor;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.request.async.CallableProcessingInterceptor;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
/**
* @author Rob Winch
*
*/
@ExtendWith({ MockitoExtension.class, SpringTestContextExtension.class })
public class WebSecurityConfigurerAdapterMockitoTests {
ConfigurableWebApplicationContext context;
public final SpringTestContext spring = new SpringTestContext(this);
@Autowired
private MockMvc mockMvc;
@Mock
private MockedStatic<SpringFactoriesLoader> springFactoriesLoader;
@AfterEach
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() {
DefaultConfigurer configurer = new DefaultConfigurer();
this.springFactoriesLoader.when(
() -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
.thenReturn(Arrays.asList(configurer));
loadConfig(Config.class);
assertThat(configurer.init).isTrue();
assertThat(configurer.configure).isTrue();
}
@Test
public void loadConfigWhenDefaultConfigThenWebAsyncManagerIntegrationFilterAdded() throws Exception {
this.spring.register(WebAsyncPopulatedByDefaultConfig.class).autowire();
WebAsyncManager webAsyncManager = mock(WebAsyncManager.class);
this.mockMvc.perform(get("/").requestAttr(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, webAsyncManager));
ArgumentCaptor<CallableProcessingInterceptor> callableProcessingInterceptorArgCaptor = ArgumentCaptor
.forClass(CallableProcessingInterceptor.class);
verify(webAsyncManager, atLeastOnce()).registerCallableInterceptor(any(),
callableProcessingInterceptorArgCaptor.capture());
CallableProcessingInterceptor callableProcessingInterceptor = callableProcessingInterceptorArgCaptor
.getAllValues().stream()
.filter((e) -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
.findFirst().orElse(null);
assertThat(callableProcessingInterceptor).isNotNull();
}
private void loadConfig(Class<?>... classes) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setClassLoader(getClass().getClassLoader());
context.register(classes);
context.refresh();
this.context = context;
}
@Configuration
@EnableWebSecurity
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) {
}
}
static class DefaultConfigurer extends AbstractHttpConfigurer<DefaultConfigurer, HttpSecurity> {
boolean init;
boolean configure;
@Override
public void init(HttpSecurity builder) {
this.init = true;
}
@Override
public void configure(HttpSecurity builder) {
this.configure = true;
}
}
@Configuration
@EnableWebSecurity
static class WebAsyncPopulatedByDefaultConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
@Override
protected void configure(HttpSecurity http) {
}
}
}

View File

@ -1,450 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.filter.OncePerRequestFilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Tests for {@link WebSecurityConfigurerAdapter}.
*
* @author Rob Winch
* @author Joe Grandja
*/
@ExtendWith(SpringTestContextExtension.class)
public class WebSecurityConfigurerAdapterTests {
public final SpringTestContext spring = new SpringTestContext(this);
@Autowired
private MockMvc mockMvc;
@Test
public void loadConfigWhenRequestSecureThenDefaultSecurityHeadersReturned() throws Exception {
this.spring.register(HeadersArePopulatedByDefaultConfig.class).autowire();
// @formatter:off
this.mockMvc.perform(get("/").secure(true))
.andExpect(header().string("X-Content-Type-Options", "nosniff"))
.andExpect(header().string("X-Frame-Options", "DENY"))
.andExpect(header().string("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"))
.andExpect(header().string("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string("Pragma", "no-cache")).andExpect(header().string("Expires", "0"))
.andExpect(header().string("X-XSS-Protection", "1; mode=block"));
// @formatter:on
}
@Test
public void loadConfigWhenRequestAuthenticateThenAuthenticationEventPublished() throws Exception {
this.spring.register(InMemoryAuthWithWebSecurityConfigurerAdapter.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).isNotEmpty();
assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).hasSize(1);
}
@Test
public void loadConfigWhenInMemoryConfigureProtectedThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureProtectedConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
@Test
public void loadConfigWhenInMemoryConfigureGlobalThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureGlobalConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
@Test
public void loadConfigWhenCustomContentNegotiationStrategyBeanThenOverridesDefault() {
OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN = mock(
ContentNegotiationStrategy.class);
this.spring.register(OverrideContentNegotiationStrategySharedObjectConfig.class).autowire();
OverrideContentNegotiationStrategySharedObjectConfig securityConfig = this.spring.getContext()
.getBean(OverrideContentNegotiationStrategySharedObjectConfig.class);
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
assertThat(securityConfig.contentNegotiationStrategySharedObject)
.isSameAs(OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN);
}
@Test
public void loadConfigWhenDefaultContentNegotiationStrategyThenHeaderContentNegotiationStrategy() {
this.spring.register(ContentNegotiationStrategyDefaultSharedObjectConfig.class).autowire();
ContentNegotiationStrategyDefaultSharedObjectConfig securityConfig = this.spring.getContext()
.getBean(ContentNegotiationStrategyDefaultSharedObjectConfig.class);
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
assertThat(securityConfig.contentNegotiationStrategySharedObject)
.isInstanceOf(HeaderContentNegotiationStrategy.class);
}
@Test
public void loadConfigWhenUserDetailsServiceHasCircularReferenceThenStillLoads() {
this.spring.register(RequiresUserDetailsServiceConfig.class, UserDetailsServiceConfig.class).autowire();
MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
myFilter.userDetailsService.loadUserByUsername("user");
assertThatExceptionOfType(UsernameNotFoundException.class)
.isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
}
// SEC-2274: WebSecurityConfigurer adds ApplicationContext as a shared object
@Test
public void loadConfigWhenSharedObjectsCreatedThenApplicationContextAdded() {
this.spring.register(ApplicationContextSharedObjectConfig.class).autowire();
ApplicationContextSharedObjectConfig securityConfig = this.spring.getContext()
.getBean(ApplicationContextSharedObjectConfig.class);
assertThat(securityConfig.applicationContextSharedObject).isNotNull();
assertThat(securityConfig.applicationContextSharedObject).isSameAs(this.spring.getContext());
}
@Test
public void loadConfigWhenCustomAuthenticationTrustResolverBeanThenOverridesDefault() {
CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN = mock(AuthenticationTrustResolver.class);
this.spring.register(CustomTrustResolverConfig.class).autowire();
CustomTrustResolverConfig securityConfig = this.spring.getContext().getBean(CustomTrustResolverConfig.class);
assertThat(securityConfig.authenticationTrustResolverSharedObject).isNotNull();
assertThat(securityConfig.authenticationTrustResolverSharedObject)
.isSameAs(CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN);
}
@Test
public void compareOrderWebSecurityConfigurerAdapterWhenLowestOrderToDefaultOrderThenGreaterThanZero() {
AnnotationAwareOrderComparator comparator = new AnnotationAwareOrderComparator();
assertThat(comparator.compare(new LowestPriorityWebSecurityConfig(), new DefaultOrderWebSecurityConfig()))
.isGreaterThan(0);
}
// gh-7515
@Test
public void performWhenUsingAuthenticationEventPublisherBeanThenUses() throws Exception {
this.spring.register(CustomAuthenticationEventPublisherBean.class).autowire();
AuthenticationEventPublisher authenticationEventPublisher = this.spring.getContext()
.getBean(AuthenticationEventPublisher.class);
this.mockMvc.perform(get("/").with(httpBasic("user", "password")));
verify(authenticationEventPublisher).publishAuthenticationSuccess(any(Authentication.class));
}
// gh-4400
@Test
public void performWhenUsingAuthenticationEventPublisherInDslThenUses() throws Exception {
this.spring.register(CustomAuthenticationEventPublisherDsl.class).autowire();
AuthenticationEventPublisher authenticationEventPublisher = CustomAuthenticationEventPublisherDsl.EVENT_PUBLISHER;
MockHttpServletRequestBuilder userRequest = get("/").with(httpBasic("user", "password"));
// fails since no providers configured
this.mockMvc.perform(userRequest);
verify(authenticationEventPublisher).publishAuthenticationFailure(any(AuthenticationException.class),
any(Authentication.class));
}
@Configuration
@EnableWebSecurity
static class HeadersArePopulatedByDefaultConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
@Override
protected void configure(HttpSecurity http) {
}
}
@Configuration
@EnableWebSecurity
static class InMemoryAuthWithWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter
implements ApplicationListener<AuthenticationSuccessEvent> {
static List<AuthenticationSuccessEvent> EVENTS = new ArrayList<>();
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
EVENTS.add(event);
}
}
@Configuration
@EnableWebSecurity
static class InMemoryConfigureProtectedConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
}
@Configuration
@EnableWebSecurity
static class InMemoryConfigureGlobalConfig extends WebSecurityConfigurerAdapter {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
}
@Configuration
@EnableWebSecurity
static class OverrideContentNegotiationStrategySharedObjectConfig extends WebSecurityConfigurerAdapter {
static ContentNegotiationStrategy CONTENT_NEGOTIATION_STRATEGY_BEAN;
private ContentNegotiationStrategy contentNegotiationStrategySharedObject;
@Bean
ContentNegotiationStrategy contentNegotiationStrategy() {
return CONTENT_NEGOTIATION_STRATEGY_BEAN;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
this.contentNegotiationStrategySharedObject = http.getSharedObject(ContentNegotiationStrategy.class);
super.configure(http);
}
}
@Configuration
@EnableWebSecurity
static class ContentNegotiationStrategyDefaultSharedObjectConfig extends WebSecurityConfigurerAdapter {
private ContentNegotiationStrategy contentNegotiationStrategySharedObject;
@Override
protected void configure(HttpSecurity http) throws Exception {
this.contentNegotiationStrategySharedObject = http.getSharedObject(ContentNegotiationStrategy.class);
super.configure(http);
}
}
@Configuration
static class RequiresUserDetailsServiceConfig {
@Bean
MyFilter myFilter(UserDetailsService userDetailsService) {
return new MyFilter(userDetailsService);
}
}
@Configuration
@EnableWebSecurity
static class UserDetailsServiceConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilter myFilter;
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Override
public void configure(HttpSecurity http) {
http.addFilterBefore(this.myFilter, UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
}
static class MyFilter extends OncePerRequestFilter {
private UserDetailsService userDetailsService;
MyFilter(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(request, response);
}
}
@Configuration
@EnableWebSecurity
static class ApplicationContextSharedObjectConfig extends WebSecurityConfigurerAdapter {
private ApplicationContext applicationContextSharedObject;
@Override
protected void configure(HttpSecurity http) throws Exception {
this.applicationContextSharedObject = http.getSharedObject(ApplicationContext.class);
super.configure(http);
}
}
@Configuration
@EnableWebSecurity
static class CustomTrustResolverConfig extends WebSecurityConfigurerAdapter {
static AuthenticationTrustResolver AUTHENTICATION_TRUST_RESOLVER_BEAN;
private AuthenticationTrustResolver authenticationTrustResolverSharedObject;
@Bean
AuthenticationTrustResolver authenticationTrustResolver() {
return AUTHENTICATION_TRUST_RESOLVER_BEAN;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
this.authenticationTrustResolverSharedObject = http.getSharedObject(AuthenticationTrustResolver.class);
super.configure(http);
}
}
static class DefaultOrderWebSecurityConfig extends WebSecurityConfigurerAdapter {
}
@Order
static class LowestPriorityWebSecurityConfig extends WebSecurityConfigurerAdapter {
}
@Configuration
@EnableWebSecurity
static class CustomAuthenticationEventPublisherBean extends WebSecurityConfigurerAdapter {
@Bean
@Override
public UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@Bean
AuthenticationEventPublisher authenticationEventPublisher() {
return mock(AuthenticationEventPublisher.class);
}
}
@Configuration
@EnableWebSecurity
static class CustomAuthenticationEventPublisherDsl extends WebSecurityConfigurerAdapter {
static AuthenticationEventPublisher EVENT_PUBLISHER = mock(AuthenticationEventPublisher.class);
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationEventPublisher(EVENT_PUBLISHER);
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,13 +27,15 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.filter.OncePerRequestFilter;
@ -75,23 +77,20 @@ public class HttpConfigurationTests {
@Configuration
@EnableWebSecurity
static class UnregisteredFilterConfig extends WebSecurityConfigurerAdapter {
static class UnregisteredFilterConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilter(new UnregisteredFilter());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@ -108,10 +107,10 @@ public class HttpConfigurationTests {
@Configuration
@EnableWebSecurity
static class RequestMatcherRegistryConfigs extends WebSecurityConfigurerAdapter {
static class RequestMatcherRegistryConfigs {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers()
@ -122,6 +121,7 @@ public class HttpConfigurationTests {
.antMatchers("/**").hasRole("USER")
.and()
.httpBasic();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -32,7 +32,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.FilterChainProxy;
@ -154,14 +153,15 @@ public class HttpSecurityAddFilterTest {
@Configuration
@EnableWebSecurity
static class MyFilterMultipleAfterConfig extends WebSecurityConfigurerAdapter {
static class MyFilterMultipleAfterConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterAfter(new MyFilter(), WebAsyncManagerIntegrationFilter.class)
.addFilterAfter(new MyFilter(), ExceptionTranslationFilter.class);
return http.build();
// @formatter:on
}
@ -169,14 +169,15 @@ public class HttpSecurityAddFilterTest {
@Configuration
@EnableWebSecurity
static class MyFilterMultipleBeforeConfig extends WebSecurityConfigurerAdapter {
static class MyFilterMultipleBeforeConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterBefore(new MyFilter(), WebAsyncManagerIntegrationFilter.class)
.addFilterBefore(new MyFilter(), ExceptionTranslationFilter.class);
return http.build();
// @formatter:on
}
@ -184,14 +185,15 @@ public class HttpSecurityAddFilterTest {
@Configuration
@EnableWebSecurity
static class MyFilterMultipleAtConfig extends WebSecurityConfigurerAdapter {
static class MyFilterMultipleAtConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterAt(new MyFilter(), ChannelProcessingFilter.class)
.addFilterAt(new MyFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,15 +20,15 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.any;
@ -76,12 +76,12 @@ public class HttpSecurityAuthenticationManagerTests {
@Configuration
@EnableWebSecurity
static class AuthenticationManagerConfig extends WebSecurityConfigurerAdapter {
static class AuthenticationManagerConfig {
static final AuthenticationManager AUTHENTICATION_MANAGER = mock(AuthenticationManager.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authz) -> authz
@ -89,6 +89,7 @@ public class HttpSecurityAuthenticationManagerTests {
)
.httpBasic(withDefaults())
.authenticationManager(AUTHENTICATION_MANAGER);
return http.build();
// @formatter:on
}
@ -96,13 +97,13 @@ public class HttpSecurityAuthenticationManagerTests {
@Configuration
@EnableWebSecurity
static class AuthenticationManagerBuilderConfig extends WebSecurityConfigurerAdapter {
static class AuthenticationManagerBuilderConfig {
static final AuthenticationManager AUTHENTICATION_MANAGER = mock(AuthenticationManager.class);
static final UserDetailsService USER_DETAILS_SERVICE = mock(UserDetailsService.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authz) -> authz
@ -111,11 +112,12 @@ public class HttpSecurityAuthenticationManagerTests {
.httpBasic(withDefaults())
.authenticationManager(AUTHENTICATION_MANAGER);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(USER_DETAILS_SERVICE);
@Bean
UserDetailsService userDetailsService() {
return USER_DETAILS_SERVICE;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,23 +25,28 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.jaas.JaasAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.UrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
@ -278,17 +283,18 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class AccessDecisionManagerRefConfig extends WebSecurityConfigurerAdapter {
static class AccessDecisionManagerRefConfig {
static AccessDecisionManager ACCESS_DECISION_MANAGER;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().permitAll()
.accessDecisionManager(ACCESS_DECISION_MANAGER);
return http.build();
// @formatter:on
}
@ -296,10 +302,10 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class AccessDeniedPageConfig extends WebSecurityConfigurerAdapter {
static class AccessDeniedPageConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -308,6 +314,7 @@ public class NamespaceHttpTests {
.and()
.exceptionHandling()
.accessDeniedPage("/AccessDeniedPage");
return http.build();
// @formatter:on
}
@ -315,23 +322,24 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class AuthenticationManagerRefConfig extends WebSecurityConfigurerAdapter {
static class AuthenticationManagerRefConfig {
static AuthenticationManager AUTHENTICATION_MANAGER;
@Override
protected AuthenticationManager authenticationManager() {
@Bean
AuthenticationManager authenticationManager() {
return AUTHENTICATION_MANAGER;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -339,10 +347,10 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class CreateSessionAlwaysConfig extends WebSecurityConfigurerAdapter {
static class CreateSessionAlwaysConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -350,6 +358,7 @@ public class NamespaceHttpTests {
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
return http.build();
// @formatter:on
}
@ -357,10 +366,10 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class CreateSessionStatelessConfig extends WebSecurityConfigurerAdapter {
static class CreateSessionStatelessConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -368,6 +377,7 @@ public class NamespaceHttpTests {
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
// @formatter:on
}
@ -375,10 +385,10 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class IfRequiredConfig extends WebSecurityConfigurerAdapter {
static class IfRequiredConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -389,6 +399,7 @@ public class NamespaceHttpTests {
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -396,10 +407,10 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class CreateSessionNeverConfig extends WebSecurityConfigurerAdapter {
static class CreateSessionNeverConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -407,6 +418,7 @@ public class NamespaceHttpTests {
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER);
return http.build();
// @formatter:on
}
@ -414,10 +426,10 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class EntryPointRefConfig extends WebSecurityConfigurerAdapter {
static class EntryPointRefConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -427,6 +439,7 @@ public class NamespaceHttpTests {
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/entry-point"))
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -434,13 +447,14 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class JaasApiProvisionConfig extends WebSecurityConfigurerAdapter {
static class JaasApiProvisionConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilter(new JaasApiIntegrationFilter());
return http.build();
// @formatter:on
}
@ -448,10 +462,10 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class RealmConfig extends WebSecurityConfigurerAdapter {
static class RealmConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -459,6 +473,7 @@ public class NamespaceHttpTests {
.and()
.httpBasic()
.realmName("RealmConfig");
return http.build();
// @formatter:on
}
@ -466,13 +481,14 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class RequestMatcherAntConfig extends WebSecurityConfigurerAdapter {
static class RequestMatcherAntConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/api/**");
return http.build();
// @formatter:on
}
@ -480,13 +496,14 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class RequestMatcherRegexConfig extends WebSecurityConfigurerAdapter {
static class RequestMatcherRegexConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.regexMatcher("/regex/.*");
return http.build();
// @formatter:on
}
@ -494,13 +511,14 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class RequestMatcherRefConfig extends WebSecurityConfigurerAdapter {
static class RequestMatcherRefConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatcher(new MyRequestMatcher());
return http.build();
// @formatter:on
}
@ -517,25 +535,26 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class SecurityNoneConfig extends WebSecurityConfigurerAdapter {
static class SecurityNoneConfig {
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/resources/**", "/public/**");
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/resources/**", "/public/**");
}
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class SecurityContextRepoConfig extends WebSecurityConfigurerAdapter {
static class SecurityContextRepoConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -546,25 +565,22 @@ public class NamespaceHttpTests {
.and()
.formLogin();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class ServletApiProvisionConfig extends WebSecurityConfigurerAdapter {
static class ServletApiProvisionConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -572,6 +588,7 @@ public class NamespaceHttpTests {
.and()
.servletApi()
.disable();
return http.build();
// @formatter:on
}
@ -579,14 +596,15 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class ServletApiProvisionDefaultsConfig extends WebSecurityConfigurerAdapter {
static class ServletApiProvisionDefaultsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().permitAll();
return http.build();
// @formatter:on
}
@ -607,27 +625,31 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class UseExpressionsConfig extends WebSecurityConfigurerAdapter {
static class UseExpressionsConfig {
private Class<? extends FilterInvocationSecurityMetadataSource> filterInvocationSecurityMetadataSourceType;
@Override
protected void configure(HttpSecurity http) throws Exception {
private HttpSecurity httpSecurity;
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/users**", "/sessions/**").hasRole("USER")
.antMatchers("/signup").permitAll()
.anyRequest().hasRole("USER");
this.httpSecurity = http;
return http.build();
// @formatter:on
}
@Override
public void init(final WebSecurity web) throws Exception {
super.init(web);
final HttpSecurity http = this.getHttp();
web.postBuildAction(() -> {
FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class);
@Bean
@DependsOn("filterChain")
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.postBuildAction(() -> {
FilterSecurityInterceptor securityInterceptor = this.httpSecurity
.getSharedObject(FilterSecurityInterceptor.class);
UseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor
.getSecurityMetadataSource().getClass();
});
@ -637,27 +659,31 @@ public class NamespaceHttpTests {
@Configuration
@EnableWebSecurity
static class DisableUseExpressionsConfig extends WebSecurityConfigurerAdapter {
static class DisableUseExpressionsConfig {
private Class<? extends FilterInvocationSecurityMetadataSource> filterInvocationSecurityMetadataSourceType;
@Override
protected void configure(HttpSecurity http) throws Exception {
private HttpSecurity httpSecurity;
@Bean
SecurityFilterChain filterChain(HttpSecurity http, ApplicationContext context) throws Exception {
// @formatter:off
http
.apply(new UrlAuthorizationConfigurer<>(getApplicationContext())).getRegistry()
.apply(new UrlAuthorizationConfigurer<>(context)).getRegistry()
.antMatchers("/users**", "/sessions/**").hasRole("USER")
.antMatchers("/signup").hasRole("ANONYMOUS")
.anyRequest().hasRole("USER");
this.httpSecurity = http;
return http.build();
// @formatter:on
}
@Override
public void init(final WebSecurity web) throws Exception {
super.init(web);
final HttpSecurity http = this.getHttp();
web.postBuildAction(() -> {
FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class);
@Bean
@DependsOn("filterChain")
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.postBuildAction(() -> {
FilterSecurityInterceptor securityInterceptor = this.httpSecurity
.getSharedObject(FilterSecurityInterceptor.class);
DisableUseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor
.getSecurityMetadataSource().getClass();
});

View File

@ -0,0 +1,40 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.builders;
import java.util.List;
import org.springframework.security.config.annotation.web.configurers.DefaultLoginPageConfigurer;
import org.springframework.test.util.ReflectionTestUtils;
public final class TestHttpSecurity {
private TestHttpSecurity() {
}
public static void disableDefaults(HttpSecurity http) throws Exception {
List<Object> orderedFilters = (List<Object>) ReflectionTestUtils.getField(http, "filters");
orderedFilters.clear();
http.csrf((c) -> c.disable()).exceptionHandling((c) -> c.disable()).headers((c) -> c.disable())
.sessionManagement((c) -> c.disable()).securityContext((c) -> c.disable())
.requestCache((c) -> c.disable()).anonymous((c) -> c.disable()).servletApi((c) -> c.disable())
.removeConfigurer(DefaultLoginPageConfigurer.class);
http.logout((c) -> c.disable());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,16 +25,20 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.firewall.HttpStatusRequestRejectedHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@ -140,33 +144,27 @@ public class WebSecurityTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherConfig {
@Override
public void configure(WebSecurity web) {
// @formatter:off
web
.ignoring()
.mvcMatchers("/path");
// @formatter:on
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().mvcMatchers("/path");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic().and()
.authorizeRequests()
.anyRequest().denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@RestController
@ -184,34 +182,27 @@ public class WebSecurityTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherServletPathConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherServletPathConfig {
@Override
public void configure(WebSecurity web) {
// @formatter:off
web
.ignoring()
.mvcMatchers("/path").servletPath("/spring")
.mvcMatchers("/notused");
// @formatter:on
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().mvcMatchers("/path").servletPath("/spring").mvcMatchers("/notused");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic().and()
.authorizeRequests()
.anyRequest().denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@RestController
@ -239,11 +230,12 @@ public class WebSecurityTests {
@Configuration
@EnableWebSecurity
static class RequestRejectedHandlerConfig extends WebSecurityConfigurerAdapter {
static class RequestRejectedHandlerConfig {
@Override
public void configure(WebSecurity web) throws Exception {
web.requestRejectedHandler(new HttpStatusRequestRejectedHandler(HttpStatus.BAD_REQUEST.value()));
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web
.requestRejectedHandler(new HttpStatusRequestRejectedHandler(HttpStatus.BAD_REQUEST.value()));
}
}

View File

@ -24,12 +24,14 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
@ -81,28 +83,35 @@ public class AuthenticationPrincipalArgumentResolverTests {
@EnableWebMvc
static class Config {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:off
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@Bean
public UsernameExtractor usernameExtractor() {
return new UsernameExtractor();
}
@RestController
static class UserController {
@GetMapping("/users/self")
public String usersSelf(@AuthenticationPrincipal(expression = "@usernameExtractor.extract(#this)") String userName) {
public String usersSelf(
@AuthenticationPrincipal(expression = "@usernameExtractor.extract(#this)") String userName) {
return userName;
}
}
}
static class UsernameExtractor {
public String extract(User u) {
return "extracted-" + u.getUsername();
}
}
}

View File

@ -22,16 +22,11 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.debug.DebugFilter;
import org.springframework.test.web.servlet.MockMvc;
@ -55,15 +50,6 @@ public class EnableWebSecurityTests {
@Autowired
private MockMvc mockMvc;
@Test
public void configureWhenOverrideAuthenticationManagerBeanThenAuthenticationManagerBeanRegistered() {
this.spring.register(SecurityConfig.class).autowire();
AuthenticationManager authenticationManager = this.spring.getContext().getBean(AuthenticationManager.class);
Authentication authentication = authenticationManager
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThat(authentication.isAuthenticated()).isTrue();
}
@Test
public void loadConfigWhenChildConfigExtendsSecurityConfigThenSecurityConfigInherited() {
this.spring.register(ChildSecurityConfig.class).autowire();
@ -100,38 +86,6 @@ public class EnableWebSecurityTests {
assertThat(parentBean.getChild()).isNotSameAs(childBean);
}
@Configuration
@EnableWebSecurity
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/*").hasRole("USER")
.and()
.formLogin();
// @formatter:on
}
}
@Configuration
static class ChildSecurityConfig extends DebugSecurityConfig {
@ -139,17 +93,18 @@ public class EnableWebSecurityTests {
@Configuration
@EnableWebSecurity(debug = true)
static class DebugSecurityConfig extends WebSecurityConfigurerAdapter {
static class DebugSecurityConfig {
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class AuthenticationPrincipalConfig extends WebSecurityConfigurerAdapter {
static class AuthenticationPrincipalConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
@RestController
@ -188,7 +143,7 @@ public class EnableWebSecurityTests {
@Configuration
@EnableWebSecurity
static class BeanProxyEnabledByDefaultConfig extends WebSecurityConfigurerAdapter {
static class BeanProxyEnabledByDefaultConfig {
@Bean
Child child() {
@ -204,7 +159,7 @@ public class EnableWebSecurityTests {
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
static class BeanProxyDisabledConfig extends WebSecurityConfigurerAdapter {
static class BeanProxyDisabledConfig {
@Bean
Child child() {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -42,6 +42,7 @@ import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepo
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.web.bind.annotation.GetMapping;
@ -216,14 +217,15 @@ public class OAuth2ClientConfigurationTests {
@Configuration
@EnableWebMvc
@EnableWebSecurity
static class OAuth2AuthorizedClientArgumentResolverConfig extends WebSecurityConfigurerAdapter {
static class OAuth2AuthorizedClientArgumentResolverConfig {
static ClientRegistrationRepository CLIENT_REGISTRATION_REPOSITORY;
static OAuth2AuthorizedClientRepository AUTHORIZED_CLIENT_REPOSITORY;
static OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> ACCESS_TOKEN_RESPONSE_CLIENT;
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
@Bean
@ -257,16 +259,17 @@ public class OAuth2ClientConfigurationTests {
@Configuration
@EnableWebMvc
@EnableWebSecurity
static class OAuth2AuthorizedClientRepositoryRegisteredTwiceConfig extends WebSecurityConfigurerAdapter {
static class OAuth2AuthorizedClientRepositoryRegisteredTwiceConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
return http.build();
// @formatter:on
}
@ -295,16 +298,17 @@ public class OAuth2ClientConfigurationTests {
@Configuration
@EnableWebMvc
@EnableWebSecurity
static class ClientRegistrationRepositoryNotRegisteredConfig extends WebSecurityConfigurerAdapter {
static class ClientRegistrationRepositoryNotRegisteredConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
return http.build();
// @formatter:on
}
@ -313,16 +317,17 @@ public class OAuth2ClientConfigurationTests {
@Configuration
@EnableWebMvc
@EnableWebSecurity
static class ClientRegistrationRepositoryRegisteredTwiceConfig extends WebSecurityConfigurerAdapter {
static class ClientRegistrationRepositoryRegisteredTwiceConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
return http.build();
// @formatter:on
}
@ -351,16 +356,17 @@ public class OAuth2ClientConfigurationTests {
@Configuration
@EnableWebMvc
@EnableWebSecurity
static class AccessTokenResponseClientRegisteredTwiceConfig extends WebSecurityConfigurerAdapter {
static class AccessTokenResponseClientRegisteredTwiceConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
return http.build();
// @formatter:on
}
@ -389,14 +395,15 @@ public class OAuth2ClientConfigurationTests {
@Configuration
@EnableWebMvc
@EnableWebSecurity
static class OAuth2AuthorizedClientManagerRegisteredConfig extends WebSecurityConfigurerAdapter {
static class OAuth2AuthorizedClientManagerRegisteredConfig {
static ClientRegistrationRepository CLIENT_REGISTRATION_REPOSITORY;
static OAuth2AuthorizedClientRepository AUTHORIZED_CLIENT_REPOSITORY;
static OAuth2AuthorizedClientManager AUTHORIZED_CLIENT_MANAGER;
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
@Bean

View File

@ -1,131 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import java.net.URL;
import java.net.URLClassLoader;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.FatalBeanException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
/**
* @author Joe Grandja
*/
@ExtendWith(SpringTestContextExtension.class)
public class Sec2515Tests {
public final SpringTestContext spring = new SpringTestContext(this);
// SEC-2515
@Test
public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanThenThrowFatalBeanException() {
assertThatExceptionOfType(FatalBeanException.class)
.isThrownBy(() -> this.spring.register(StackOverflowSecurityConfig.class).autowire());
}
@Test
public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanCustomNameThenThrowFatalBeanException() {
assertThatExceptionOfType(FatalBeanException.class)
.isThrownBy(() -> this.spring.register(CustomBeanNameStackOverflowSecurityConfig.class).autowire());
}
// SEC-2549
@Test
public void loadConfigWhenChildClassLoaderSetThenContextLoads() {
CanLoadWithChildConfig.AUTHENTICATION_MANAGER = mock(AuthenticationManager.class);
this.spring.register(CanLoadWithChildConfig.class);
AnnotationConfigWebApplicationContext context = (AnnotationConfigWebApplicationContext) this.spring
.getContext();
context.setClassLoader(new URLClassLoader(new URL[0], context.getClassLoader()));
this.spring.autowire();
assertThat(this.spring.getContext().getBean(AuthenticationManager.class)).isNotNull();
} // SEC-2515
@Test
public void loadConfigWhenAuthenticationManagerConfiguredAndRegisterBeanThenContextLoads() {
this.spring.register(SecurityConfig.class).autowire();
}
@Configuration
@EnableWebSecurity
static class StackOverflowSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
@Configuration
@EnableWebSecurity
static class CustomBeanNameStackOverflowSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean(name = "custom")
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
@Configuration
@EnableWebSecurity
static class CanLoadWithChildConfig extends WebSecurityConfigurerAdapter {
static AuthenticationManager AUTHENTICATION_MANAGER;
@Override
@Bean
public AuthenticationManager authenticationManager() {
return AUTHENTICATION_MANAGER;
}
}
@Configuration
@EnableWebSecurity
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication();
}
}
}

View File

@ -36,6 +36,7 @@ import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;
import org.springframework.security.oauth2.server.resource.authentication.TestBearerTokenAuthentications;
import org.springframework.security.oauth2.server.resource.web.reactive.function.client.ServletBearerExchangeFilterFunction;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.web.bind.annotation.GetMapping;
@ -106,11 +107,12 @@ public class SecurityReactorContextConfigurationResourceServerTests {
@Configuration
@EnableWebSecurity
static class BearerFilterConfig extends WebSecurityConfigurerAdapter {
static class BearerFilterConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.securityContext().requireExplicitSave(false);
return http.build();
}
@Bean
@ -123,10 +125,11 @@ public class SecurityReactorContextConfigurationResourceServerTests {
@Configuration
@EnableWebSecurity
static class BearerFilterlessConfig extends WebSecurityConfigurerAdapter {
static class BearerFilterlessConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
@Bean

View File

@ -33,6 +33,7 @@ import reactor.core.publisher.Operators;
import reactor.test.StepVerifier;
import reactor.util.context.Context;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
@ -48,6 +49,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.oauth2.client.web.reactive.function.client.MockExchangeFunction;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@ -271,10 +273,11 @@ public class SecurityReactorContextConfigurationTests {
@Configuration
@EnableWebSecurity
static class SecurityConfig extends WebSecurityConfigurerAdapter {
static class SecurityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@ -45,20 +45,13 @@ import org.springframework.security.access.expression.AbstractSecurityExpression
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.config.users.AuthenticationTestConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.SecurityFilterChain;
@ -96,29 +89,6 @@ public class WebSecurityConfigurationTests {
@Autowired
private MockMvc mockMvc;
@Test
public void loadConfigWhenWebSecurityConfigurersHaveOrderThenFilterChainsOrdered() {
this.spring.register(SortedWebSecurityConfigurerAdaptersConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(6);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/ignore1");
assertThat(filterChains.get(0).matches(request)).isTrue();
assertThat(filterChains.get(0).getFilters()).isEmpty();
request.setServletPath("/ignore2");
assertThat(filterChains.get(1).matches(request)).isTrue();
assertThat(filterChains.get(1).getFilters()).isEmpty();
request.setServletPath("/role1/**");
assertThat(filterChains.get(2).matches(request)).isTrue();
request.setServletPath("/role2/**");
assertThat(filterChains.get(3).matches(request)).isTrue();
request.setServletPath("/role3/**");
assertThat(filterChains.get(4).matches(request)).isTrue();
request.setServletPath("/**");
assertThat(filterChains.get(5).matches(request)).isTrue();
}
@Test
public void loadConfigWhenSecurityFilterChainsHaveOrderThenFilterChainsOrdered() {
this.spring.register(SortedSecurityFilterChainConfig.class).autowire();
@ -149,15 +119,6 @@ public class WebSecurityConfigurationTests {
assertThat(filterChains.get(1).matches(request)).isTrue();
}
@Test
public void loadConfigWhenWebSecurityConfigurersHaveSameOrderThenThrowBeanCreationException() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(DuplicateOrderConfig.class).autowire()).havingRootCause()
.withMessageContaining("@Order on WebSecurityConfigurers must be unique")
.withMessageContaining(DuplicateOrderConfig.WebConfigurer1.class.getName())
.withMessageContaining(DuplicateOrderConfig.WebConfigurer2.class.getName());
}
@Test
public void loadConfigWhenWebInvocationPrivilegeEvaluatorSetThenIsRegistered() {
PrivilegeEvaluatorConfigurerAdapterConfig.PRIVILEGE_EVALUATOR = mock(WebInvocationPrivilegeEvaluator.class);
@ -261,23 +222,6 @@ public class WebSecurityConfigurationTests {
assertThat(Modifier.isStatic(method.getModifiers())).isTrue();
}
@Test
public void loadConfigWhenBeanProxyingEnabledAndSubclassThenFilterChainsCreated() {
this.spring.register(GlobalAuthenticationWebSecurityConfigurerAdaptersConfig.class, SubclassConfig.class)
.autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(4);
}
@Test
public void loadConfigWhenBothAdapterAndFilterChainConfiguredThenException() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(AdapterAndFilterChainConfig.class).autowire())
.withRootCauseExactlyInstanceOf(IllegalStateException.class)
.withMessageContaining("Found WebSecurityConfigurerAdapter as well as SecurityFilterChain.");
}
@Test
public void loadConfigWhenOnlyWebSecurityCustomizerThenDefaultFilterChainCreated() {
this.spring.register(WebSecurityCustomizerConfig.class).autowire();
@ -314,40 +258,6 @@ public class WebSecurityConfigurationTests {
assertThat(filterChains.get(2).matches(request)).isFalse();
}
@Test
public void loadConfigWhenWebSecurityCustomizerAndWebSecurityConfigurerAdapterThenFilterChainsOrdered() {
this.spring.register(CustomizerAndAdapterConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(3);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/ignore1");
assertThat(filterChains.get(0).matches(request)).isTrue();
assertThat(filterChains.get(0).getFilters()).isEmpty();
request.setServletPath("/ignore2");
assertThat(filterChains.get(1).matches(request)).isTrue();
assertThat(filterChains.get(1).getFilters()).isEmpty();
request.setServletPath("/role1/**");
assertThat(filterChains.get(2).matches(request)).isTrue();
request.setServletPath("/test/**");
assertThat(filterChains.get(2).matches(request)).isFalse();
}
@Test
public void loadConfigWhenCustomizerAndAdapterConfigureWebSecurityThenBothConfigurationsApplied() {
this.spring.register(CustomizerAndAdapterIgnoringConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(3);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/ignore1");
assertThat(filterChains.get(0).matches(request)).isTrue();
assertThat(filterChains.get(0).getFilters()).isEmpty();
request.setServletPath("/ignore2");
assertThat(filterChains.get(1).matches(request)).isTrue();
assertThat(filterChains.get(1).getFilters()).isEmpty();
}
@Test
public void loadConfigWhenCustomizersHaveOrderThenCustomizersOrdered() {
this.spring.register(OrderedCustomizerConfig.class).autowire();
@ -363,19 +273,6 @@ public class WebSecurityConfigurationTests {
assertThat(filterChains.get(1).getFilters()).isEmpty();
}
@Test
public void loadConfigWhenMultipleAuthenticationManagersAndWebSecurityConfigurerAdapterThenConfigurationApplied() {
this.spring.register(MultipleAuthenticationManagersConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(2);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/role1");
assertThat(filterChains.get(0).matches(request)).isTrue();
request.setServletPath("/role2");
assertThat(filterChains.get(1).matches(request)).isTrue();
}
@Test
public void loadConfigWhenTwoSecurityFilterChainsThenRequestMatcherDelegatingWebInvocationPrivilegeEvaluator() {
this.spring.register(TwoSecurityFilterChainConfig.class).autowire();
@ -439,80 +336,6 @@ public class WebSecurityConfigurationTests {
assertThat(privilegeEvaluator.isAllowed("/another", user)).isTrue();
}
@Configuration
@EnableWebSecurity
@Import(AuthenticationTestConfiguration.class)
static class SortedWebSecurityConfigurerAdaptersConfig {
@Configuration
@Order(1)
static class WebConfigurer1 extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/ignore1", "/ignore2");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/role1/**")
.authorizeRequests()
.anyRequest().hasRole("1");
// @formatter:on
}
}
@Configuration
@Order(2)
static class WebConfigurer2 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/role2/**")
.authorizeRequests()
.anyRequest().hasRole("2");
// @formatter:on
}
}
@Configuration
@Order(3)
static class WebConfigurer3 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/role3/**")
.authorizeRequests()
.anyRequest().hasRole("3");
// @formatter:on
}
}
@Configuration
static class WebConfigurer4 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("4");
// @formatter:on
}
}
}
@Configuration
@EnableWebSecurity
@Import(AuthenticationTestConfiguration.class)
@ -612,72 +435,36 @@ public class WebSecurityConfigurationTests {
@Configuration
@EnableWebSecurity
@Import(AuthenticationTestConfiguration.class)
static class DuplicateOrderConfig {
@Configuration
static class WebConfigurer1 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/role1/**")
.authorizeRequests()
.anyRequest().hasRole("1");
// @formatter:on
}
}
@Configuration
static class WebConfigurer2 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/role2/**")
.authorizeRequests()
.anyRequest().hasRole("2");
// @formatter:on
}
}
}
@Configuration
@EnableWebSecurity
static class PrivilegeEvaluatorConfigurerAdapterConfig extends WebSecurityConfigurerAdapter {
static class PrivilegeEvaluatorConfigurerAdapterConfig {
static WebInvocationPrivilegeEvaluator PRIVILEGE_EVALUATOR;
@Override
public void configure(WebSecurity web) {
web.privilegeEvaluator(PRIVILEGE_EVALUATOR);
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.privilegeEvaluator(PRIVILEGE_EVALUATOR);
}
}
@Configuration
@EnableWebSecurity
static class WebSecurityExpressionHandlerConfig extends WebSecurityConfigurerAdapter {
static class WebSecurityExpressionHandlerConfig {
static SecurityExpressionHandler EXPRESSION_HANDLER;
@Override
public void configure(WebSecurity web) {
web.expressionHandler(EXPRESSION_HANDLER);
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.expressionHandler(EXPRESSION_HANDLER);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.expressionHandler(EXPRESSION_HANDLER);
return http.build();
// @formatter:on
}
@ -685,25 +472,26 @@ public class WebSecurityConfigurationTests {
@Configuration
@EnableWebSecurity
static class NullWebSecurityExpressionHandlerConfig extends WebSecurityConfigurerAdapter {
static class NullWebSecurityExpressionHandlerConfig {
@Override
public void configure(WebSecurity web) {
web.expressionHandler(null);
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.expressionHandler(null);
}
}
@Configuration
@EnableWebSecurity
static class WebSecurityExpressionHandlerDefaultsConfig extends WebSecurityConfigurerAdapter {
static class WebSecurityExpressionHandlerDefaultsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated();
return http.build();
// @formatter:on
}
@ -711,7 +499,7 @@ public class WebSecurityConfigurationTests {
@Configuration
@EnableWebSecurity
static class WebSecurityExpressionHandlerRoleHierarchyBeanConfig extends WebSecurityConfigurerAdapter {
static class WebSecurityExpressionHandlerRoleHierarchyBeanConfig {
@Bean
RoleHierarchy roleHierarchy() {
@ -724,7 +512,7 @@ public class WebSecurityConfigurationTests {
@Configuration
@EnableWebSecurity
static class WebSecurityExpressionHandlerPermissionEvaluatorBeanConfig extends WebSecurityConfigurerAdapter {
static class WebSecurityExpressionHandlerPermissionEvaluatorBeanConfig {
static final PermissionEvaluator PERMIT_ALL_PERMISSION_EVALUATOR = new PermissionEvaluator() {
@Override
@ -748,14 +536,15 @@ public class WebSecurityConfigurationTests {
@Configuration
@EnableWebSecurity
static class WebInvocationPrivilegeEvaluatorDefaultsConfig extends WebSecurityConfigurerAdapter {
static class WebInvocationPrivilegeEvaluatorDefaultsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated();
return http.build();
// @formatter:on
}
@ -780,14 +569,15 @@ public class WebSecurityConfigurationTests {
@Configuration
@EnableWebSecurity
static class DefaultExpressionHandlerSetsBeanResolverConfig extends WebSecurityConfigurerAdapter {
static class DefaultExpressionHandlerSetsBeanResolverConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().access("request.method == 'GET' ? @b.grant() : @b.deny()");
return http.build();
// @formatter:on
}
@ -822,7 +612,7 @@ public class WebSecurityConfigurationTests {
@Configuration
@EnableWebSecurity
static class ParentConfig extends WebSecurityConfigurerAdapter {
static class ParentConfig {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
@ -833,7 +623,7 @@ public class WebSecurityConfigurationTests {
@Configuration
@EnableWebSecurity
static class ChildConfig extends WebSecurityConfigurerAdapter {
static class ChildConfig {
}
@ -842,85 +632,6 @@ public class WebSecurityConfigurationTests {
}
@Configuration
@Import(AuthenticationTestConfiguration.class)
@EnableGlobalAuthentication
static class GlobalAuthenticationWebSecurityConfigurerAdaptersConfig {
@Configuration
@Order(1)
static class WebConfigurer1 extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/ignore1", "/ignore2");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/anonymous/**")
.authorizeRequests()
.anyRequest().anonymous();
// @formatter:on
}
}
@Configuration
static class WebConfigurer2 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated();
// @formatter:on
}
}
}
@Configuration
@EnableWebSecurity
@Import(AuthenticationTestConfiguration.class)
static class AdapterAndFilterChainConfig {
@Order(2)
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
return http
.antMatcher("/filter/**")
.authorizeRequests((authorize) -> authorize
.anyRequest().authenticated()
)
.build();
// @formatter:on
}
@Order(1)
@Configuration
static class WebConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/config/**")
.authorizeRequests((authorize) -> authorize
.anyRequest().permitAll()
);
// @formatter:on
}
}
}
@Configuration
@EnableWebSecurity
@Import(AuthenticationTestConfiguration.class)
@ -957,56 +668,6 @@ public class WebSecurityConfigurationTests {
}
@Configuration
@EnableWebSecurity
@Import(AuthenticationTestConfiguration.class)
static class CustomizerAndAdapterConfig {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
}
@Configuration
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/role1/**")
.authorizeRequests((authorize) -> authorize
.anyRequest().hasRole("1")
);
// @formatter:on
}
}
}
@Configuration
@EnableWebSecurity
@Import(AuthenticationTestConfiguration.class)
static class CustomizerAndAdapterIgnoringConfig {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/ignore1");
}
@Configuration
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/ignore2");
}
}
}
@Configuration
@EnableWebSecurity
@Import(AuthenticationTestConfiguration.class)
@ -1026,75 +687,6 @@ public class WebSecurityConfigurationTests {
}
@Configuration
@EnableWebSecurity
static class MultipleAuthenticationManagersConfig {
@Bean("authManager1")
static AuthenticationManager authenticationManager1() {
return new ProviderManager(new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return UsernamePasswordAuthenticationToken.unauthenticated("user", "credentials");
}
@Override
public boolean supports(Class<?> authentication) {
return false;
}
});
}
@Bean("authManager2")
static AuthenticationManager authenticationManager2() {
return new ProviderManager(new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return UsernamePasswordAuthenticationToken.unauthenticated("subuser", "credentials");
}
@Override
public boolean supports(Class<?> authentication) {
return false;
}
});
}
@Configuration
@Order(1)
public static class SecurityConfig1 extends WebSecurityConfigurerAdapter {
@Override
protected AuthenticationManager authenticationManager() {
return authenticationManager1();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/role1/**")
.authorizeRequests((authorize) -> authorize
.anyRequest().hasRole("1")
);
// @formatter:on
}
}
@Configuration
@Order(2)
public static class SecurityConfig2 extends WebSecurityConfigurerAdapter {
@Override
protected AuthenticationManager authenticationManager() {
return authenticationManager2();
}
}
}
@Configuration
@EnableWebSecurity
static class TwoSecurityFilterChainConfig {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,10 +18,9 @@ package org.springframework.security.config.annotation.web.configuration.sec2377
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class Sec2377AConfig extends WebSecurityConfigurerAdapter {
public class Sec2377AConfig {
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,10 +18,9 @@ package org.springframework.security.config.annotation.web.configuration.sec2377
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class Sec2377BConfig extends WebSecurityConfigurerAdapter {
public class Sec2377BConfig {
}

View File

@ -20,18 +20,20 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.config.annotation.SecurityContextChangedListenerConfig;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextChangedListener;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@ -93,10 +95,10 @@ public class AnonymousConfigurerTests {
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
static class InvokeTwiceDoesNotOverride {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.anonymous()
@ -104,6 +106,7 @@ public class AnonymousConfigurerTests {
.principal("principal")
.and()
.anonymous();
return http.build();
// @formatter:on
}
@ -112,16 +115,17 @@ public class AnonymousConfigurerTests {
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class AnonymousPrincipalInLambdaConfig extends WebSecurityConfigurerAdapter {
static class AnonymousPrincipalInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.anonymous((anonymous) ->
anonymous
.principal("principal")
);
return http.build();
// @formatter:on
}
@ -129,10 +133,10 @@ public class AnonymousConfigurerTests {
@Configuration
@EnableWebSecurity
static class AnonymousDisabledInLambdaConfig extends WebSecurityConfigurerAdapter {
static class AnonymousDisabledInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -141,25 +145,22 @@ public class AnonymousConfigurerTests {
)
.anonymous(AbstractHttpConfigurer::disable);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class AnonymousWithDefaultsInLambdaConfig extends WebSecurityConfigurerAdapter {
static class AnonymousWithDefaultsInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -168,15 +169,12 @@ public class AnonymousConfigurerTests {
)
.anonymous(withDefaults());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}

View File

@ -32,14 +32,15 @@ import org.springframework.mock.web.MockServletContext;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
@ -281,33 +282,31 @@ public class AuthorizeRequestsTests {
@EnableWebSecurity
@Configuration
static class AntMatchersNoPatternsConfig extends WebSecurityConfigurerAdapter {
static class AntMatchersNoPatternsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers(HttpMethod.POST).denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@EnableWebSecurity
@Configuration
static class AntMatchersNoPatternsInLambdaConfig extends WebSecurityConfigurerAdapter {
static class AntMatchersNoPatternsInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -315,85 +314,77 @@ public class AuthorizeRequestsTests {
.antMatchers(HttpMethod.POST).denyAll()
);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@EnableWebSecurity
@Configuration
static class AntPatchersPathVariables extends WebSecurityConfigurerAdapter {
static class AntPatchersPathVariables {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers(new AntPathRequestMatcher("/user/{user}", null, false)).access("#user == 'user'")
.anyRequest().denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@EnableWebSecurity
@Configuration
static class AntMatchersPathVariablesCamelCaseVariables extends WebSecurityConfigurerAdapter {
static class AntMatchersPathVariablesCamelCaseVariables {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers(new AntPathRequestMatcher("/user/{userName}", null, false)).access("#userName == 'user'")
.anyRequest().denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@EnableWebSecurity
@Configuration
static class RoleHiearchyConfig extends WebSecurityConfigurerAdapter {
static class RoleHiearchyConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("ADMIN");
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@Bean
@ -408,24 +399,22 @@ public class AuthorizeRequestsTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic().and()
.authorizeRequests()
.mvcMatchers("/path").denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController
@ -443,10 +432,10 @@ public class AuthorizeRequestsTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherInLambdaConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic(withDefaults())
@ -455,14 +444,12 @@ public class AuthorizeRequestsTests {
.mvcMatchers("/path").denyAll()
);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController
@ -480,24 +467,22 @@ public class AuthorizeRequestsTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherServletPathConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherServletPathConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic().and()
.authorizeRequests()
.mvcMatchers("/path").servletPath("/spring").denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController
@ -515,10 +500,10 @@ public class AuthorizeRequestsTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherServletPathInLambdaConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherServletPathInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic(withDefaults())
@ -527,14 +512,12 @@ public class AuthorizeRequestsTests {
.mvcMatchers("/path").servletPath("/spring").denyAll()
);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController
@ -552,24 +535,22 @@ public class AuthorizeRequestsTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherPathVariablesConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherPathVariablesConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic().and()
.authorizeRequests()
.mvcMatchers("/user/{userName}").access("#userName == 'user'");
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController
@ -587,10 +568,10 @@ public class AuthorizeRequestsTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherPathVariablesInLambdaConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherPathVariablesInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic(withDefaults())
@ -599,14 +580,12 @@ public class AuthorizeRequestsTests {
.mvcMatchers("/user/{userName}").access("#userName == 'user'")
);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController
@ -624,24 +603,22 @@ public class AuthorizeRequestsTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherPathServletPathRequiredConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherPathServletPathRequiredConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic().and()
.authorizeRequests()
.mvcMatchers("/user").denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController

View File

@ -31,7 +31,6 @@ import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.PortMapperImpl;
@ -131,16 +130,17 @@ public class ChannelSecurityConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requiresChannel()
.anyRequest().requiresSecure();
return http.build();
// @formatter:on
}
@ -162,16 +162,17 @@ public class ChannelSecurityConfigurerTests {
@Configuration
@EnableWebSecurity
static class DuplicateInvocationsDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class DuplicateInvocationsDoesNotOverrideConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requiresChannel()
.anyRequest().requiresSecure()
.and()
.requiresChannel();
return http.build();
// @formatter:on
}
@ -179,16 +180,17 @@ public class ChannelSecurityConfigurerTests {
@Configuration
@EnableWebSecurity
static class RequiresChannelInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RequiresChannelInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requiresChannel((requiresChannel) ->
requiresChannel
.anyRequest().requiresSecure()
);
return http.build();
// @formatter:on
}
@ -196,10 +198,10 @@ public class ChannelSecurityConfigurerTests {
@Configuration
@EnableWebSecurity
static class RequiresChannelWithTestUrlRedirectStrategy extends WebSecurityConfigurerAdapter {
static class RequiresChannelWithTestUrlRedirectStrategy {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.portMapper()
@ -209,6 +211,7 @@ public class ChannelSecurityConfigurerTests {
.redirectStrategy(new TestUrlRedirectStrategy())
.anyRequest()
.requiresSecure();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -30,9 +30,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
@ -184,16 +184,17 @@ public class CorsConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultCorsConfig extends WebSecurityConfigurerAdapter {
static class DefaultCorsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.cors();
return http.build();
// @formatter:on
}
@ -202,16 +203,17 @@ public class CorsConfigurerTests {
@Configuration
@EnableWebMvc
@EnableWebSecurity
static class MvcCorsConfig extends WebSecurityConfigurerAdapter {
static class MvcCorsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.cors();
return http.build();
// @formatter:on
}
@ -231,10 +233,10 @@ public class CorsConfigurerTests {
@Configuration
@EnableWebMvc
@EnableWebSecurity
static class MvcCorsInLambdaConfig extends WebSecurityConfigurerAdapter {
static class MvcCorsInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -242,6 +244,7 @@ public class CorsConfigurerTests {
.anyRequest().authenticated()
)
.cors(withDefaults());
return http.build();
// @formatter:on
}
@ -260,16 +263,17 @@ public class CorsConfigurerTests {
@Configuration
@EnableWebSecurity
static class ConfigSourceConfig extends WebSecurityConfigurerAdapter {
static class ConfigSourceConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.cors();
return http.build();
// @formatter:on
}
@ -287,10 +291,10 @@ public class CorsConfigurerTests {
@Configuration
@EnableWebSecurity
static class ConfigSourceInLambdaConfig extends WebSecurityConfigurerAdapter {
static class ConfigSourceInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -298,6 +302,7 @@ public class CorsConfigurerTests {
.anyRequest().authenticated()
)
.cors(withDefaults());
return http.build();
// @formatter:on
}
@ -315,16 +320,17 @@ public class CorsConfigurerTests {
@Configuration
@EnableWebSecurity
static class CorsFilterConfig extends WebSecurityConfigurerAdapter {
static class CorsFilterConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.cors();
return http.build();
// @formatter:on
}
@ -342,10 +348,10 @@ public class CorsConfigurerTests {
@Configuration
@EnableWebSecurity
static class CorsFilterInLambdaConfig extends WebSecurityConfigurerAdapter {
static class CorsFilterInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -353,6 +359,7 @@ public class CorsConfigurerTests {
.anyRequest().authenticated()
)
.cors(withDefaults());
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,7 +25,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.SecurityFilterChain;
@ -101,17 +100,18 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@Configuration
@EnableWebSecurity
static class IgnoringRequestMatchers extends WebSecurityConfigurerAdapter {
static class IgnoringRequestMatchers {
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/path"))
.ignoringRequestMatchers(this.requestMatcher);
return http.build();
// @formatter:on
}
@ -119,12 +119,12 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@Configuration
@EnableWebSecurity
static class IgnoringRequestInLambdaMatchers extends WebSecurityConfigurerAdapter {
static class IgnoringRequestInLambdaMatchers {
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf((csrf) ->
@ -132,6 +132,7 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/path"))
.ignoringRequestMatchers(this.requestMatcher)
);
return http.build();
// @formatter:on
}
@ -139,17 +140,18 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@Configuration
@EnableWebSecurity
static class IgnoringPathsAndMatchers extends WebSecurityConfigurerAdapter {
static class IgnoringPathsAndMatchers {
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.ignoringAntMatchers("/no-csrf")
.ignoringRequestMatchers(this.requestMatcher);
return http.build();
// @formatter:on
}
@ -157,12 +159,12 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@Configuration
@EnableWebSecurity
static class IgnoringPathsAndMatchersInLambdaConfig extends WebSecurityConfigurerAdapter {
static class IgnoringPathsAndMatchersInLambdaConfig {
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf((csrf) ->
@ -170,6 +172,7 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
.ignoringAntMatchers("/no-csrf")
.ignoringRequestMatchers(this.requestMatcher)
);
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -26,7 +26,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
@ -76,10 +76,11 @@ public class CsrfConfigurerNoWebMvcTests {
@Configuration
@EnableWebSecurity
static class EnableWebConfig extends WebSecurityConfigurerAdapter {
static class EnableWebConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
}
@ -98,10 +99,11 @@ public class CsrfConfigurerNoWebMvcTests {
@Configuration
@EnableWebSecurity
static class EnableWebMvcConfig extends WebSecurityConfigurerAdapter {
static class EnableWebMvcConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
}

View File

@ -33,11 +33,12 @@ import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@ -479,24 +480,26 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class CsrfAppliedDefaultConfig extends WebSecurityConfigurerAdapter {
static class CsrfAppliedDefaultConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class DisableCsrfConfig extends WebSecurityConfigurerAdapter {
static class DisableCsrfConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.disable();
return http.build();
// @formatter:on
}
@ -504,13 +507,14 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class DisableCsrfInLambdaConfig extends WebSecurityConfigurerAdapter {
static class DisableCsrfInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf(AbstractHttpConfigurer::disable);
return http.build();
// @formatter:on
}
@ -518,10 +522,10 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class DisableCsrfEnablesRequestCacheConfig extends WebSecurityConfigurerAdapter {
static class DisableCsrfEnablesRequestCacheConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -532,27 +536,24 @@ public class CsrfConfigurerTests {
.csrf()
.disable();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class CsrfDisablesPostRequestFromRequestCacheConfig extends WebSecurityConfigurerAdapter {
static class CsrfDisablesPostRequestFromRequestCacheConfig {
static CsrfTokenRepository REPO;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -563,31 +564,29 @@ public class CsrfConfigurerTests {
.csrf()
.csrfTokenRepository(REPO);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class InvalidSessionUrlConfig extends WebSecurityConfigurerAdapter {
static class InvalidSessionUrlConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.and()
.sessionManagement()
.invalidSessionUrl("/error/sessionError");
return http.build();
// @formatter:on
}
@ -595,16 +594,17 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class RequireCsrfProtectionMatcherConfig extends WebSecurityConfigurerAdapter {
static class RequireCsrfProtectionMatcherConfig {
static RequestMatcher MATCHER;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.requireCsrfProtectionMatcher(MATCHER);
return http.build();
// @formatter:on
}
@ -612,15 +612,16 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class RequireCsrfProtectionMatcherInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RequireCsrfProtectionMatcherInLambdaConfig {
static RequestMatcher MATCHER;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf((csrf) -> csrf.requireCsrfProtectionMatcher(MATCHER));
return http.build();
// @formatter:on
}
@ -628,12 +629,12 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class CsrfTokenRepositoryConfig extends WebSecurityConfigurerAdapter {
static class CsrfTokenRepositoryConfig {
static CsrfTokenRepository REPO;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
@ -641,31 +642,29 @@ public class CsrfConfigurerTests {
.csrf()
.csrfTokenRepository(REPO);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class CsrfTokenRepositoryInLambdaConfig extends WebSecurityConfigurerAdapter {
static class CsrfTokenRepositoryInLambdaConfig {
static CsrfTokenRepository REPO;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin(withDefaults())
.csrf((csrf) -> csrf.csrfTokenRepository(REPO));
return http.build();
// @formatter:on
}
@ -673,16 +672,17 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class AccessDeniedHandlerConfig extends WebSecurityConfigurerAdapter {
static class AccessDeniedHandlerConfig {
static AccessDeniedHandler DENIED_HANDLER;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.exceptionHandling()
.accessDeniedHandler(DENIED_HANDLER);
return http.build();
// @formatter:on
}
@ -690,18 +690,19 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultAccessDeniedHandlerForConfig extends WebSecurityConfigurerAdapter {
static class DefaultAccessDeniedHandlerForConfig {
static AccessDeniedHandler DENIED_HANDLER;
static RequestMatcher MATCHER;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.exceptionHandling()
.defaultAccessDeniedHandlerFor(DENIED_HANDLER, MATCHER);
return http.build();
// @formatter:on
}
@ -709,13 +710,14 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class FormLoginConfig extends WebSecurityConfigurerAdapter {
static class FormLoginConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin();
return http.build();
// @formatter:on
}
@ -723,16 +725,17 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class LogoutAllowsGetConfig extends WebSecurityConfigurerAdapter {
static class LogoutAllowsGetConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
return http.build();
// @formatter:on
}
@ -740,14 +743,15 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class NullRequireCsrfProtectionMatcherConfig extends WebSecurityConfigurerAdapter {
static class NullRequireCsrfProtectionMatcherConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.requireCsrfProtectionMatcher(null);
return http.build();
// @formatter:on
}
@ -755,10 +759,10 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultDoesNotCreateSession extends WebSecurityConfigurerAdapter {
static class DefaultDoesNotCreateSession {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -768,29 +772,27 @@ public class CsrfConfigurerTests {
.and()
.httpBasic();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class NullAuthenticationStrategy extends WebSecurityConfigurerAdapter {
static class NullAuthenticationStrategy {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.sessionAuthenticationStrategy(null);
return http.build();
// @formatter:on
}
@ -798,12 +800,12 @@ public class CsrfConfigurerTests {
@Configuration
@EnableWebSecurity
static class CsrfAuthenticationStrategyConfig extends WebSecurityConfigurerAdapter {
static class CsrfAuthenticationStrategyConfig {
static SessionAuthenticationStrategy STRATEGY;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
@ -811,15 +813,12 @@ public class CsrfConfigurerTests {
.csrf()
.sessionAuthenticationStrategy(STRATEGY);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,17 +25,15 @@ import jakarta.servlet.ServletException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.builders.TestHttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
@ -133,13 +131,9 @@ public class DefaultFiltersTests {
@EnableWebSecurity
static class FilterChainProxyBuilderMissingConfig {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@ -156,38 +150,33 @@ public class DefaultFiltersTests {
@Configuration
@EnableWebSecurity
static class NullWebInvocationPrivilegeEvaluatorConfig extends WebSecurityConfigurerAdapter {
static class NullWebInvocationPrivilegeEvaluatorConfig {
NullWebInvocationPrivilegeEvaluatorConfig() {
super(true);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
TestHttpSecurity.disableDefaults(http);
http.formLogin();
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class FilterChainProxyBuilderIgnoringConfig extends WebSecurityConfigurerAdapter {
static class FilterChainProxyBuilderIgnoringConfig {
@Override
public void configure(WebSecurity web) {
// @formatter:off
web
.ignoring()
.antMatchers("/resources/**");
// @formatter:on
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER");
return http.build();
// @formatter:on
}
@ -195,10 +184,11 @@ public class DefaultFiltersTests {
@Configuration
@EnableWebSecurity
static class DefaultFiltersConfigPermitAll extends WebSecurityConfigurerAdapter {
static class DefaultFiltersConfigPermitAll {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -24,14 +24,15 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@ -313,10 +314,10 @@ public class DefaultLoginPageConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultLoginPageConfig extends WebSecurityConfigurerAdapter {
static class DefaultLoginPageConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -324,25 +325,22 @@ public class DefaultLoginPageConfigurerTests {
.and()
.formLogin();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class DefaultLoginPageCustomLogoutSuccessHandlerConfig extends WebSecurityConfigurerAdapter {
static class DefaultLoginPageCustomLogoutSuccessHandlerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -352,6 +350,7 @@ public class DefaultLoginPageConfigurerTests {
.logoutSuccessHandler(new SimpleUrlLogoutSuccessHandler())
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -359,10 +358,10 @@ public class DefaultLoginPageConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultLoginPageCustomLogoutSuccessUrlConfig extends WebSecurityConfigurerAdapter {
static class DefaultLoginPageCustomLogoutSuccessUrlConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -372,6 +371,7 @@ public class DefaultLoginPageConfigurerTests {
.logoutSuccessUrl("/login?logout")
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -379,10 +379,10 @@ public class DefaultLoginPageConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultLoginPageWithRememberMeConfig extends WebSecurityConfigurerAdapter {
static class DefaultLoginPageWithRememberMeConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -391,17 +391,23 @@ public class DefaultLoginPageConfigurerTests {
.formLogin()
.and()
.rememberMe();
return http.build();
// @formatter:on
}
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class DefaultLoginWithCustomAuthenticationEntryPointConfig extends WebSecurityConfigurerAdapter {
static class DefaultLoginWithCustomAuthenticationEntryPointConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.exceptionHandling()
@ -411,6 +417,7 @@ public class DefaultLoginPageConfigurerTests {
.anyRequest().hasRole("USER")
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -418,17 +425,18 @@ public class DefaultLoginPageConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.exceptionHandling()
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -441,16 +449,17 @@ public class DefaultLoginPageConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultLogoutPageConfig extends WebSecurityConfigurerAdapter {
static class DefaultLogoutPageConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorize) -> authorize
.anyRequest().authenticated()
)
.formLogin(withDefaults());
return http.build();
// @formatter:on
}
@ -458,10 +467,10 @@ public class DefaultLoginPageConfigurerTests {
@Configuration
@EnableWebSecurity
static class LogoutDisabledConfig extends WebSecurityConfigurerAdapter {
static class LogoutDisabledConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorize) -> authorize
@ -471,6 +480,7 @@ public class DefaultLoginPageConfigurerTests {
.logout((logout) -> logout
.disable()
);
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,15 +20,16 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@ -77,13 +78,13 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
@Configuration
@EnableWebSecurity
static class RequestMatcherBasedAccessDeniedHandlerConfig extends WebSecurityConfigurerAdapter {
static class RequestMatcherBasedAccessDeniedHandlerConfig {
AccessDeniedHandler teapotDeniedHandler = (request, response, exception) -> response
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -96,6 +97,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
.defaultAccessDeniedHandlerFor(
new AccessDeniedHandlerImpl(),
AnyRequestMatcher.INSTANCE);
return http.build();
// @formatter:on
}
@ -103,13 +105,13 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
@Configuration
@EnableWebSecurity
static class RequestMatcherBasedAccessDeniedHandlerInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RequestMatcherBasedAccessDeniedHandlerInLambdaConfig {
AccessDeniedHandler teapotDeniedHandler = (request, response, exception) -> response
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -127,6 +129,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
AnyRequestMatcher.INSTANCE
)
);
return http.build();
// @formatter:on
}
@ -134,13 +137,13 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
@Configuration
@EnableWebSecurity
static class SingleRequestMatcherAccessDeniedHandlerConfig extends WebSecurityConfigurerAdapter {
static class SingleRequestMatcherAccessDeniedHandlerConfig {
AccessDeniedHandler teapotDeniedHandler = (request, response, exception) -> response
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -150,6 +153,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
.defaultAccessDeniedHandlerFor(
this.teapotDeniedHandler,
new AntPathRequestMatcher("/hello/**"));
return http.build();
// @formatter:on
}

View File

@ -29,18 +29,19 @@ import org.springframework.http.MediaType;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityContextChangedListenerConfig;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextChangedListener;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.accept.ContentNegotiationStrategy;
@ -231,15 +232,16 @@ public class ExceptionHandlingConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.exceptionHandling();
return http.build();
// @formatter:on
}
@ -277,15 +279,15 @@ public class ExceptionHandlingConfigurerTests {
}
@Configuration
@EnableWebSecurity
static class HttpBasicAndFormLoginEntryPointsConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
static class HttpBasicAndFormLoginEntryPointsConfig {
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -295,13 +297,14 @@ public class ExceptionHandlingConfigurerTests {
.and()
.formLogin();
// @formatter:on
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class OverrideContentNegotiationStrategySharedObjectConfig extends WebSecurityConfigurerAdapter {
static class OverrideContentNegotiationStrategySharedObjectConfig {
static ContentNegotiationStrategy CNS = mock(ContentNegotiationStrategy.class);
@ -314,16 +317,16 @@ public class ExceptionHandlingConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultHttpConfig extends WebSecurityConfigurerAdapter {
static class DefaultHttpConfig {
}
@Configuration
@EnableWebSecurity
static class BasicAuthenticationEntryPointBeforeFormLoginConfig extends WebSecurityConfigurerAdapter {
static class BasicAuthenticationEntryPointBeforeFormLoginConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -332,6 +335,7 @@ public class ExceptionHandlingConfigurerTests {
.httpBasic()
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -339,12 +343,12 @@ public class ExceptionHandlingConfigurerTests {
@Configuration
@EnableWebSecurity
static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class InvokeTwiceDoesNotOverrideConfig {
static AuthenticationEntryPoint AEP = mock(AuthenticationEntryPoint.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -353,6 +357,7 @@ public class ExceptionHandlingConfigurerTests {
.exceptionHandling()
.authenticationEntryPoint(AEP).and()
.exceptionHandling();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -17,7 +17,9 @@
package org.springframework.security.config.annotation.web.configurers;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -38,17 +40,19 @@ import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.access.expression.WebExpressionVoter;
import org.springframework.security.web.access.expression.WebSecurityExpressionRoot;
@ -60,9 +64,9 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
@ -439,9 +443,10 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenApplicationListenerInvokedOnAuthorizedEvent()
throws Exception {
AuthorizedEventApplicationListener.clearEvents();
this.spring.register(AuthorizedRequestsWithPostProcessorConfig.class).autowire();
this.mvc.perform(get("/"));
verify(AuthorizedRequestsWithPostProcessorConfig.AL).onApplicationEvent(any(AuthorizedEvent.class));
assertThat(AuthorizedEventApplicationListener.EVENTS).isNotEmpty();
}
@Test
@ -552,14 +557,15 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class HasRoleStartingWithRoleConfig extends WebSecurityConfigurerAdapter {
static class HasRoleStartingWithRoleConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("ROLE_USER");
return http.build();
// @formatter:on
}
@ -567,16 +573,17 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class NoSpecificAccessDecisionManagerConfig extends WebSecurityConfigurerAdapter {
static class NoSpecificAccessDecisionManagerConfig {
static ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER");
return http.build();
// @formatter:on
}
@ -589,13 +596,14 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class NoRequestsConfig extends WebSecurityConfigurerAdapter {
static class NoRequestsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests();
return http.build();
// @formatter:on
}
@ -603,15 +611,16 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class IncompleteMappingConfig extends WebSecurityConfigurerAdapter {
static class IncompleteMappingConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/a").authenticated()
.anyRequest();
return http.build();
// @formatter:on
}
@ -619,16 +628,17 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleUserAnyAuthorityConfig extends WebSecurityConfigurerAdapter {
static class RoleUserAnyAuthorityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.and()
.authorizeRequests()
.anyRequest().hasAnyAuthority("ROLE_USER");
return http.build();
// @formatter:on
}
@ -636,16 +646,17 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleUserAuthorityConfig extends WebSecurityConfigurerAdapter {
static class RoleUserAuthorityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.and()
.authorizeRequests()
.anyRequest().hasAuthority("ROLE_USER");
return http.build();
// @formatter:on
}
@ -653,16 +664,17 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleUserOrRoleAdminAuthorityConfig extends WebSecurityConfigurerAdapter {
static class RoleUserOrRoleAdminAuthorityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.and()
.authorizeRequests()
.anyRequest().hasAnyAuthority("ROLE_USER", "ROLE_ADMIN");
return http.build();
// @formatter:on
}
@ -670,14 +682,15 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleUserConfig extends WebSecurityConfigurerAdapter {
static class RoleUserConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasAnyRole("USER");
return http.build();
// @formatter:on
}
@ -685,14 +698,15 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleUserWithTestRolePrefixConfig extends WebSecurityConfigurerAdapter {
static class RoleUserWithTestRolePrefixConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasAnyRole("USER");
return http.build();
// @formatter:on
}
@ -705,14 +719,15 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleUserWithEmptyRolePrefixConfig extends WebSecurityConfigurerAdapter {
static class RoleUserWithEmptyRolePrefixConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasAnyRole("USER");
return http.build();
// @formatter:on
}
@ -725,14 +740,15 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleUserOrAdminConfig extends WebSecurityConfigurerAdapter {
static class RoleUserOrAdminConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasAnyRole("USER", "ADMIN");
return http.build();
// @formatter:on
}
@ -740,14 +756,15 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleUserOrAdminWithTestRolePrefixConfig extends WebSecurityConfigurerAdapter {
static class RoleUserOrAdminWithTestRolePrefixConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasAnyRole("USER", "ADMIN");
return http.build();
// @formatter:on
}
@ -760,14 +777,15 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleUserOrAdminWithEmptyRolePrefixConfig extends WebSecurityConfigurerAdapter {
static class RoleUserOrAdminWithEmptyRolePrefixConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasAnyRole("USER", "ADMIN");
return http.build();
// @formatter:on
}
@ -780,16 +798,17 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class HasIpAddressConfig extends WebSecurityConfigurerAdapter {
static class HasIpAddressConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.and()
.authorizeRequests()
.anyRequest().hasIpAddress("192.168.1.0");
return http.build();
// @formatter:on
}
@ -797,16 +816,17 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class AnonymousConfig extends WebSecurityConfigurerAdapter {
static class AnonymousConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.and()
.authorizeRequests()
.anyRequest().anonymous();
return http.build();
// @formatter:on
}
@ -814,10 +834,10 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RememberMeConfig extends WebSecurityConfigurerAdapter {
static class RememberMeConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.rememberMe()
@ -827,31 +847,29 @@ public class ExpressionUrlAuthorizationConfigurerTests {
.authorizeRequests()
.anyRequest().rememberMe();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class DenyAllConfig extends WebSecurityConfigurerAdapter {
static class DenyAllConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.and()
.authorizeRequests()
.anyRequest().denyAll();
return http.build();
// @formatter:on
}
@ -859,16 +877,17 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class NotDenyAllConfig extends WebSecurityConfigurerAdapter {
static class NotDenyAllConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.and()
.authorizeRequests()
.anyRequest().not().denyAll();
return http.build();
// @formatter:on
}
@ -876,10 +895,10 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class FullyAuthenticatedConfig extends WebSecurityConfigurerAdapter {
static class FullyAuthenticatedConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.rememberMe()
@ -888,17 +907,23 @@ public class ExpressionUrlAuthorizationConfigurerTests {
.and()
.authorizeRequests()
.anyRequest().fullyAuthenticated();
return http.build();
// @formatter:on
}
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class AccessConfig extends WebSecurityConfigurerAdapter {
static class AccessConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.rememberMe()
@ -907,17 +932,23 @@ public class ExpressionUrlAuthorizationConfigurerTests {
.and()
.authorizeRequests()
.anyRequest().access("hasRole('ROLE_USER') or request.method == 'GET'");
return http.build();
// @formatter:on
}
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class InvokeTwiceDoesNotResetConfig extends WebSecurityConfigurerAdapter {
static class InvokeTwiceDoesNotResetConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
@ -926,6 +957,7 @@ public class ExpressionUrlAuthorizationConfigurerTests {
.anyRequest().authenticated()
.and()
.authorizeRequests();
return http.build();
// @formatter:on
}
@ -933,10 +965,10 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class AllPropertiesWorkConfig extends WebSecurityConfigurerAdapter {
static class AllPropertiesWorkConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SecurityExpressionHandler<FilterInvocation> handler = new DefaultWebSecurityExpressionHandler();
WebExpressionVoter expressionVoter = new WebExpressionVoter();
AffirmativeBased adm = new AffirmativeBased(Collections.singletonList(expressionVoter));
@ -950,6 +982,7 @@ public class ExpressionUrlAuthorizationConfigurerTests {
.anyRequest().permitAll()
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -957,12 +990,10 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class AuthorizedRequestsWithPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class AuthorizedRequestsWithPostProcessorConfig {
static ApplicationListener<AuthorizedEvent> AL = mock(ApplicationListener.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -975,22 +1006,38 @@ public class ExpressionUrlAuthorizationConfigurerTests {
return fsi;
}
});
return http.build();
// @formatter:on
}
@Bean
ApplicationListener<AuthorizedEvent> applicationListener() {
return AL;
return new AuthorizedEventApplicationListener();
}
}
static class AuthorizedEventApplicationListener implements ApplicationListener<AuthorizedEvent> {
static final List<AuthorizedEvent> EVENTS = new ArrayList<>();
@Override
public void onApplicationEvent(AuthorizedEvent event) {
EVENTS.add(event);
}
static void clearEvents() {
EVENTS.clear();
}
}
@Configuration
@EnableWebSecurity
static class UseBeansInExpressions extends WebSecurityConfigurerAdapter {
static class UseBeansInExpressions {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -998,6 +1045,7 @@ public class ExpressionUrlAuthorizationConfigurerTests {
.antMatchers("/user").hasRole("USER")
.antMatchers("/allow").access("@permission.check(authentication,'user')")
.anyRequest().access("@permission.check(authentication,'admin')");
return http.build();
// @formatter:on
}
@ -1018,10 +1066,10 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class CustomExpressionRootConfig extends WebSecurityConfigurerAdapter {
static class CustomExpressionRootConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1030,6 +1078,7 @@ public class ExpressionUrlAuthorizationConfigurerTests {
.antMatchers("/user").hasRole("USER")
.antMatchers("/allow").access("check('user')")
.anyRequest().access("check('admin')");
return http.build();
// @formatter:on
}
@ -1067,27 +1116,25 @@ public class ExpressionUrlAuthorizationConfigurerTests {
}
@Configuration
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
static class Sec3011Config extends WebSecurityConfigurerAdapter {
static class Sec3011Config {
static ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@Bean
@ -1099,10 +1146,10 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class PermissionEvaluatorConfig extends WebSecurityConfigurerAdapter {
static class PermissionEvaluatorConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1111,6 +1158,7 @@ public class ExpressionUrlAuthorizationConfigurerTests {
.antMatchers("/deny").access("hasPermission('ID', 'TYPE', 'NO PERMISSION')")
.antMatchers("/denyObject").access("hasPermission('TESTOBJ', 'NO PERMISSION')")
.anyRequest().permitAll();
return http.build();
// @formatter:on
}
@ -1135,16 +1183,17 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Configuration
@EnableWebSecurity
static class RoleHierarchyConfig extends WebSecurityConfigurerAdapter {
static class RoleHierarchyConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/allow").access("hasRole('MEMBER')")
.antMatchers("/deny").access("hasRole('ADMIN')")
.anyRequest().permitAll();
return http.build();
// @formatter:on
}

View File

@ -25,19 +25,20 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityContextChangedListenerConfig;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.config.users.AuthenticationTestConfiguration;
import org.springframework.security.core.context.SecurityContextChangedListener;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders;
import org.springframework.security.web.PortMapper;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
@ -378,17 +379,18 @@ public class FormLoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class RequestCacheConfig extends WebSecurityConfigurerAdapter {
static class RequestCacheConfig {
private RequestCache requestCache = mock(RequestCache.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin().and()
.requestCache()
.requestCache(this.requestCache);
return http.build();
// @formatter:on
}
@ -407,19 +409,15 @@ public class FormLoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class FormLoginConfig extends WebSecurityConfigurerAdapter {
static class FormLoginConfig {
@Override
public void configure(WebSecurity web) {
// @formatter:off
web
.ignoring()
.antMatchers("/resources/**");
// @formatter:on
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -428,25 +426,22 @@ public class FormLoginConfigurerTests {
.formLogin()
.loginPage("/login");
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class FormLoginInLambdaConfig extends WebSecurityConfigurerAdapter {
static class FormLoginInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -455,25 +450,22 @@ public class FormLoginConfigurerTests {
)
.formLogin(withDefaults());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class FormLoginConfigPermitAll extends WebSecurityConfigurerAdapter {
static class FormLoginConfigPermitAll {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -481,6 +473,7 @@ public class FormLoginConfigurerTests {
.and()
.formLogin()
.permitAll();
return http.build();
// @formatter:on
}
@ -488,10 +481,10 @@ public class FormLoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class FormLoginDefaultsConfig extends WebSecurityConfigurerAdapter {
static class FormLoginDefaultsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -503,6 +496,7 @@ public class FormLoginConfigurerTests {
.and()
.logout()
.permitAll();
return http.build();
// @formatter:on
}
@ -510,10 +504,10 @@ public class FormLoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class FormLoginDefaultsInLambdaConfig extends WebSecurityConfigurerAdapter {
static class FormLoginDefaultsInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -526,6 +520,7 @@ public class FormLoginConfigurerTests {
.permitAll()
)
.logout(LogoutConfigurer::permitAll);
return http.build();
// @formatter:on
}
@ -533,10 +528,10 @@ public class FormLoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class FormLoginLoginProcessingUrlConfig extends WebSecurityConfigurerAdapter {
static class FormLoginLoginProcessingUrlConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -555,25 +550,22 @@ public class FormLoginConfigurerTests {
.logoutUrl("/logout")
.deleteCookies("JSESSIONID");
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class FormLoginLoginProcessingUrlInLambdaConfig extends WebSecurityConfigurerAdapter {
static class FormLoginLoginProcessingUrlInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -594,27 +586,24 @@ public class FormLoginConfigurerTests {
.deleteCookies("JSESSIONID")
);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class FormLoginUsesPortMapperConfig extends WebSecurityConfigurerAdapter {
static class FormLoginUsesPortMapperConfig {
static PortMapper PORT_MAPPER;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -629,18 +618,19 @@ public class FormLoginConfigurerTests {
LoginUrlAuthenticationEntryPoint authenticationEntryPoint = (LoginUrlAuthenticationEntryPoint) http
.getConfigurer(FormLoginConfigurer.class).getAuthenticationEntryPoint();
authenticationEntryPoint.setForceHttps(true);
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class PermitAllIgnoresFailureHandlerConfig extends WebSecurityConfigurerAdapter {
static class PermitAllIgnoresFailureHandlerConfig {
static AuthenticationFailureHandler FAILURE_HANDLER = mock(AuthenticationFailureHandler.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -649,6 +639,7 @@ public class FormLoginConfigurerTests {
.formLogin()
.failureHandler(FAILURE_HANDLER)
.permitAll();
return http.build();
// @formatter:on
}
@ -656,10 +647,10 @@ public class FormLoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class DuplicateInvocationsDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class DuplicateInvocationsDoesNotOverrideConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
@ -667,25 +658,22 @@ public class FormLoginConfigurerTests {
.and()
.formLogin();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class FormLoginUserForwardAuthenticationSuccessAndFailureConfig extends WebSecurityConfigurerAdapter {
static class FormLoginUserForwardAuthenticationSuccessAndFailureConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
@ -698,32 +686,30 @@ public class FormLoginConfigurerTests {
.successForwardUrl("/success_forward_url")
.permitAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.exceptionHandling()
.and()
.formLogin();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,14 +20,15 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.HeaderWriterFilter;
import org.springframework.test.web.servlet.MockMvc;
@ -61,10 +62,10 @@ public class HeadersConfigurerEagerHeadersTests {
@Configuration
@EnableWebSecurity
public static class HeadersAtTheBeginningOfRequestConfig extends WebSecurityConfigurerAdapter {
public static class HeadersAtTheBeginningOfRequestConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -75,6 +76,7 @@ public class HeadersConfigurerEagerHeadersTests {
return filter;
}
});
return http.build();
// @formatter:on
}

View File

@ -30,7 +30,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.SecurityFilterChain;
@ -567,13 +566,14 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HeadersConfig extends WebSecurityConfigurerAdapter {
static class HeadersConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers();
return http.build();
// @formatter:on
}
@ -581,13 +581,14 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HeadersInLambdaConfig extends WebSecurityConfigurerAdapter {
static class HeadersInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(withDefaults());
return http.build();
// @formatter:on
}
@ -595,15 +596,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ContentTypeOptionsConfig extends WebSecurityConfigurerAdapter {
static class ContentTypeOptionsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.contentTypeOptions();
return http.build();
// @formatter:on
}
@ -611,10 +613,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ContentTypeOptionsInLambdaConfig extends WebSecurityConfigurerAdapter {
static class ContentTypeOptionsInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -622,6 +624,7 @@ public class HeadersConfigurerTests {
.defaultsDisabled()
.contentTypeOptions(withDefaults())
);
return http.build();
// @formatter:on
}
@ -629,15 +632,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class FrameOptionsConfig extends WebSecurityConfigurerAdapter {
static class FrameOptionsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.frameOptions();
return http.build();
// @formatter:on
}
@ -645,15 +649,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HstsConfig extends WebSecurityConfigurerAdapter {
static class HstsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.httpStrictTransportSecurity();
return http.build();
// @formatter:on
}
@ -661,15 +666,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class CacheControlConfig extends WebSecurityConfigurerAdapter {
static class CacheControlConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.cacheControl();
return http.build();
// @formatter:on
}
@ -677,10 +683,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class CacheControlInLambdaConfig extends WebSecurityConfigurerAdapter {
static class CacheControlInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -688,6 +694,7 @@ public class HeadersConfigurerTests {
.defaultsDisabled()
.cacheControl(withDefaults())
);
return http.build();
// @formatter:on
}
@ -695,15 +702,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class XssProtectionConfig extends WebSecurityConfigurerAdapter {
static class XssProtectionConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.xssProtection();
return http.build();
// @formatter:on
}
@ -711,10 +719,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class XssProtectionValueDisabledConfig extends WebSecurityConfigurerAdapter {
static class XssProtectionValueDisabledConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -722,15 +730,16 @@ public class HeadersConfigurerTests {
.xssProtection()
.headerValue(XXssProtectionHeaderWriter.HeaderValue.DISABLED);
// @formatter:on
return http.build();
}
}
@EnableWebSecurity
static class XssProtectionInLambdaConfig extends WebSecurityConfigurerAdapter {
static class XssProtectionInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -738,6 +747,7 @@ public class HeadersConfigurerTests {
.defaultsDisabled()
.xssProtection(withDefaults())
);
return http.build();
// @formatter:on
}
@ -745,10 +755,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class XssProtectionValueDisabledInLambdaConfig extends WebSecurityConfigurerAdapter {
static class XssProtectionValueDisabledInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -759,19 +769,21 @@ public class HeadersConfigurerTests {
)
);
// @formatter:on
return http.build();
}
}
@EnableWebSecurity
static class HeadersCustomSameOriginConfig extends WebSecurityConfigurerAdapter {
static class HeadersCustomSameOriginConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.frameOptions().sameOrigin();
return http.build();
// @formatter:on
}
@ -779,16 +791,17 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HeadersCustomSameOriginInLambdaConfig extends WebSecurityConfigurerAdapter {
static class HeadersCustomSameOriginInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
headers
.frameOptions((frameOptionsConfig) -> frameOptionsConfig.sameOrigin())
);
return http.build();
// @formatter:on
}
@ -796,15 +809,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HpkpConfigNoPins extends WebSecurityConfigurerAdapter {
static class HpkpConfigNoPins {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.httpPublicKeyPinning();
return http.build();
// @formatter:on
}
@ -812,16 +826,17 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HpkpConfig extends WebSecurityConfigurerAdapter {
static class HpkpConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.httpPublicKeyPinning()
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=");
return http.build();
// @formatter:on
}
@ -829,10 +844,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HpkpConfigWithPins extends WebSecurityConfigurerAdapter {
static class HpkpConfigWithPins {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
Map<String, String> pins = new LinkedHashMap<>();
pins.put("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "sha256");
pins.put("E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=", "sha256");
@ -842,6 +857,7 @@ public class HeadersConfigurerTests {
.defaultsDisabled()
.httpPublicKeyPinning()
.withPins(pins);
return http.build();
// @formatter:on
}
@ -849,10 +865,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HpkpConfigCustomAge extends WebSecurityConfigurerAdapter {
static class HpkpConfigCustomAge {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -860,6 +876,7 @@ public class HeadersConfigurerTests {
.httpPublicKeyPinning()
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
.maxAgeInSeconds(604800);
return http.build();
// @formatter:on
}
@ -867,10 +884,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HpkpConfigTerminateConnection extends WebSecurityConfigurerAdapter {
static class HpkpConfigTerminateConnection {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -878,6 +895,7 @@ public class HeadersConfigurerTests {
.httpPublicKeyPinning()
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
.reportOnly(false);
return http.build();
// @formatter:on
}
@ -885,10 +903,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HpkpConfigIncludeSubDomains extends WebSecurityConfigurerAdapter {
static class HpkpConfigIncludeSubDomains {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -896,6 +914,7 @@ public class HeadersConfigurerTests {
.httpPublicKeyPinning()
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
.includeSubDomains(true);
return http.build();
// @formatter:on
}
@ -903,10 +922,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HpkpConfigWithReportURI extends WebSecurityConfigurerAdapter {
static class HpkpConfigWithReportURI {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -914,6 +933,7 @@ public class HeadersConfigurerTests {
.httpPublicKeyPinning()
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
.reportUri(new URI("https://example.net/pkp-report"));
return http.build();
// @formatter:on
}
@ -921,10 +941,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HpkpConfigWithReportURIAsString extends WebSecurityConfigurerAdapter {
static class HpkpConfigWithReportURIAsString {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -932,6 +952,7 @@ public class HeadersConfigurerTests {
.httpPublicKeyPinning()
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
.reportUri("https://example.net/pkp-report");
return http.build();
// @formatter:on
}
@ -939,10 +960,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HpkpWithReportUriInLambdaConfig extends WebSecurityConfigurerAdapter {
static class HpkpWithReportUriInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -954,6 +975,7 @@ public class HeadersConfigurerTests {
.reportUri("https://example.net/pkp-report")
)
);
return http.build();
// @formatter:on
}
@ -961,15 +983,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ContentSecurityPolicyDefaultConfig extends WebSecurityConfigurerAdapter {
static class ContentSecurityPolicyDefaultConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.contentSecurityPolicy("default-src 'self'");
return http.build();
// @formatter:on
}
@ -977,16 +1000,17 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ContentSecurityPolicyReportOnlyConfig extends WebSecurityConfigurerAdapter {
static class ContentSecurityPolicyReportOnlyConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.contentSecurityPolicy("default-src 'self'; script-src trustedscripts.example.com")
.reportOnly();
return http.build();
// @formatter:on
}
@ -994,10 +1018,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ContentSecurityPolicyReportOnlyInLambdaConfig extends WebSecurityConfigurerAdapter {
static class ContentSecurityPolicyReportOnlyInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -1009,6 +1033,7 @@ public class HeadersConfigurerTests {
.reportOnly()
)
);
return http.build();
// @formatter:on
}
@ -1016,15 +1041,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ContentSecurityPolicyInvalidConfig extends WebSecurityConfigurerAdapter {
static class ContentSecurityPolicyInvalidConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.contentSecurityPolicy("");
return http.build();
// @formatter:on
}
@ -1032,10 +1058,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ContentSecurityPolicyInvalidInLambdaConfig extends WebSecurityConfigurerAdapter {
static class ContentSecurityPolicyInvalidInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -1045,6 +1071,7 @@ public class HeadersConfigurerTests {
csp.policyDirectives("")
)
);
return http.build();
// @formatter:on
}
@ -1052,10 +1079,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ContentSecurityPolicyNoDirectivesInLambdaConfig extends WebSecurityConfigurerAdapter {
static class ContentSecurityPolicyNoDirectivesInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -1063,6 +1090,7 @@ public class HeadersConfigurerTests {
.defaultsDisabled()
.contentSecurityPolicy(withDefaults())
);
return http.build();
// @formatter:on
}
@ -1070,15 +1098,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ReferrerPolicyDefaultConfig extends WebSecurityConfigurerAdapter {
static class ReferrerPolicyDefaultConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.referrerPolicy();
return http.build();
// @formatter:on
}
@ -1086,10 +1115,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ReferrerPolicyDefaultInLambdaConfig extends WebSecurityConfigurerAdapter {
static class ReferrerPolicyDefaultInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -1097,6 +1126,7 @@ public class HeadersConfigurerTests {
.defaultsDisabled()
.referrerPolicy()
);
return http.build();
// @formatter:on
}
@ -1104,15 +1134,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ReferrerPolicyCustomConfig extends WebSecurityConfigurerAdapter {
static class ReferrerPolicyCustomConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.referrerPolicy(ReferrerPolicy.SAME_ORIGIN);
return http.build();
// @formatter:on
}
@ -1120,10 +1151,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class ReferrerPolicyCustomInLambdaConfig extends WebSecurityConfigurerAdapter {
static class ReferrerPolicyCustomInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -1133,6 +1164,7 @@ public class HeadersConfigurerTests {
referrerPolicy.policy(ReferrerPolicy.SAME_ORIGIN)
)
);
return http.build();
// @formatter:on
}
@ -1140,15 +1172,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class FeaturePolicyConfig extends WebSecurityConfigurerAdapter {
static class FeaturePolicyConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.featurePolicy("geolocation 'self'");
return http.build();
// @formatter:on
}
@ -1156,15 +1189,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class FeaturePolicyInvalidConfig extends WebSecurityConfigurerAdapter {
static class FeaturePolicyInvalidConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.featurePolicy("");
return http.build();
// @formatter:on
}
@ -1172,15 +1206,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class PermissionsPolicyConfig extends WebSecurityConfigurerAdapter {
static class PermissionsPolicyConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.permissionsPolicy((permissionsPolicy) -> permissionsPolicy.policy("geolocation=(self)"));
return http.build();
// @formatter:on
}
@ -1188,16 +1223,17 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class PermissionsPolicyStringConfig extends WebSecurityConfigurerAdapter {
static class PermissionsPolicyStringConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.permissionsPolicy()
.policy("geolocation=(self)");
return http.build();
// @formatter:on
}
@ -1205,15 +1241,16 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class PermissionsPolicyInvalidConfig extends WebSecurityConfigurerAdapter {
static class PermissionsPolicyInvalidConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.permissionsPolicy((permissionsPolicy) -> permissionsPolicy.policy(null));
return http.build();
// @formatter:on
}
@ -1221,16 +1258,17 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class PermissionsPolicyInvalidStringConfig extends WebSecurityConfigurerAdapter {
static class PermissionsPolicyInvalidStringConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.permissionsPolicy()
.policy("");
return http.build();
// @formatter:on
}
@ -1238,16 +1276,17 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HstsWithPreloadConfig extends WebSecurityConfigurerAdapter {
static class HstsWithPreloadConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.httpStrictTransportSecurity()
.preload(true);
return http.build();
// @formatter:on
}
@ -1255,10 +1294,10 @@ public class HeadersConfigurerTests {
@Configuration
@EnableWebSecurity
static class HstsWithPreloadInLambdaConfig extends WebSecurityConfigurerAdapter {
static class HstsWithPreloadInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers((headers) ->
@ -1266,6 +1305,7 @@ public class HeadersConfigurerTests {
.defaultsDisabled()
.httpStrictTransportSecurity((hstsConfig) -> hstsConfig.preload(true))
);
return http.build();
// @formatter:on
}

View File

@ -28,10 +28,8 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityContextChangedListenerConfig;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.AuthenticationException;
@ -149,15 +147,16 @@ public class HttpBasicConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic();
return http.build();
// @formatter:on
}
@ -179,10 +178,10 @@ public class HttpBasicConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultsLambdaEntryPointConfig extends WebSecurityConfigurerAdapter {
static class DefaultsLambdaEntryPointConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -191,24 +190,22 @@ public class HttpBasicConfigurerTests {
)
.httpBasic(withDefaults());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@Configuration
@EnableWebSecurity
static class DefaultsEntryPointConfig extends WebSecurityConfigurerAdapter {
static class DefaultsEntryPointConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -216,26 +213,24 @@ public class HttpBasicConfigurerTests {
.and()
.httpBasic();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@Configuration
@EnableWebSecurity
static class CustomAuthenticationEntryPointConfig extends WebSecurityConfigurerAdapter {
static class CustomAuthenticationEntryPointConfig {
static AuthenticationEntryPoint ENTRY_POINT = mock(AuthenticationEntryPoint.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -244,26 +239,24 @@ public class HttpBasicConfigurerTests {
.httpBasic()
.authenticationEntryPoint(ENTRY_POINT);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@Configuration
@EnableWebSecurity
static class DuplicateDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class DuplicateDoesNotOverrideConfig {
static AuthenticationEntryPoint ENTRY_POINT = mock(AuthenticationEntryPoint.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -274,35 +267,33 @@ public class HttpBasicConfigurerTests {
.and()
.httpBasic();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@EnableWebSecurity
@Configuration
static class BasicUsesRememberMeConfig extends WebSecurityConfigurerAdapter {
static class BasicUsesRememberMeConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.and()
.rememberMe();
return http.build();
// @formatter:on
}
@Override
@Bean
public UserDetailsService userDetailsService() {
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
// @formatter:off
org.springframework.security.core.userdetails.User.withDefaultPasswordEncoder()

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,16 +22,18 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
@ -94,10 +96,10 @@ public class HttpSecurityAntMatchersTests {
@EnableWebSecurity
@Configuration
static class AntMatchersNoPatternsConfig extends WebSecurityConfigurerAdapter {
static class AntMatchersNoPatternsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers()
@ -106,24 +108,22 @@ public class HttpSecurityAntMatchersTests {
.authorizeRequests()
.anyRequest().denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@EnableWebSecurity
@Configuration
static class AntMatchersEmptyPatternsConfig extends WebSecurityConfigurerAdapter {
static class AntMatchersEmptyPatternsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers()
@ -133,14 +133,12 @@ public class HttpSecurityAntMatchersTests {
.authorizeRequests()
.anyRequest().denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -21,18 +21,20 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
@ -92,24 +94,22 @@ public class HttpSecurityLogoutTests {
@EnableWebSecurity
@Configuration
static class ClearAuthenticationFalseConfig extends WebSecurityConfigurerAdapter {
static class ClearAuthenticationFalseConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable()
.logout()
.clearAuthentication(false);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}

View File

@ -30,10 +30,10 @@ import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.RequestMapping;
@ -308,10 +308,10 @@ public class HttpSecurityRequestMatchersTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.mvcMatcher("/path")
@ -319,14 +319,12 @@ public class HttpSecurityRequestMatchersTests {
.authorizeRequests()
.anyRequest().denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController
@ -344,10 +342,10 @@ public class HttpSecurityRequestMatchersTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class RequestMatchersMvcMatcherConfig extends WebSecurityConfigurerAdapter {
static class RequestMatchersMvcMatcherConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers()
@ -357,14 +355,12 @@ public class HttpSecurityRequestMatchersTests {
.authorizeRequests()
.anyRequest().denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController
@ -382,10 +378,10 @@ public class HttpSecurityRequestMatchersTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class RequestMatchersMvcMatcherInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RequestMatchersMvcMatcherInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers((requestMatchers) ->
@ -397,6 +393,7 @@ public class HttpSecurityRequestMatchersTests {
authorizeRequests
.anyRequest().denyAll()
);
return http.build();
// @formatter:on
}
@ -415,10 +412,10 @@ public class HttpSecurityRequestMatchersTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class RequestMatchersMvcMatcherServeltPathConfig extends WebSecurityConfigurerAdapter {
static class RequestMatchersMvcMatcherServeltPathConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers()
@ -429,14 +426,12 @@ public class HttpSecurityRequestMatchersTests {
.authorizeRequests()
.anyRequest().denyAll();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@RestController
@ -454,10 +449,10 @@ public class HttpSecurityRequestMatchersTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class RequestMatchersMvcMatcherServletPathInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RequestMatchersMvcMatcherServletPathInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers((requestMatchers) ->
@ -470,6 +465,7 @@ public class HttpSecurityRequestMatchersTests {
authorizeRequests
.anyRequest().denyAll()
);
return http.build();
// @formatter:on
}

View File

@ -1,177 +0,0 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import jakarta.servlet.Filter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.stereotype.Component;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
* @author Konstantin Volivach
*/
@ExtendWith(SpringTestContextExtension.class)
public class Issue55Tests {
public final SpringTestContext spring = new SpringTestContext(this);
@Test
public void webSecurityConfigurerAdapterDefaultToAutowired() {
TestingAuthenticationToken token = new TestingAuthenticationToken("test", "this");
this.spring.register(WebSecurityConfigurerAdapterDefaultsAuthManagerConfig.class);
this.spring.getContext().getBean(FilterChainProxy.class);
FilterSecurityInterceptor filter = (FilterSecurityInterceptor) findFilter(FilterSecurityInterceptor.class, 0);
assertThat(filter.getAuthenticationManager().authenticate(token)).isEqualTo(CustomAuthenticationManager.RESULT);
}
@Test
public void multiHttpWebSecurityConfigurerAdapterDefaultsToAutowired()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
TestingAuthenticationToken token = new TestingAuthenticationToken("test", "this");
this.spring.register(MultiWebSecurityConfigurerAdapterDefaultsAuthManagerConfig.class);
this.spring.getContext().getBean(FilterChainProxy.class);
FilterSecurityInterceptor filter = (FilterSecurityInterceptor) findFilter(FilterSecurityInterceptor.class, 0);
assertThat(filter.getAuthenticationManager().authenticate(token)).isEqualTo(CustomAuthenticationManager.RESULT);
FilterSecurityInterceptor secondFilter = (FilterSecurityInterceptor) findFilter(FilterSecurityInterceptor.class,
1);
assertThat(secondFilter.getAuthenticationManager().authenticate(token))
.isEqualTo(CustomAuthenticationManager.RESULT);
}
Filter findFilter(Class<?> filter, int index) {
List<Filter> filters = filterChain(index).getFilters();
for (Filter it : filters) {
if (filter.isAssignableFrom(it.getClass())) {
return it;
}
}
return null;
}
SecurityFilterChain filterChain(int index) {
return this.spring.getContext().getBean(FilterChainProxy.class).getFilterChains().get(index);
}
@Configuration
@EnableWebSecurity
static class WebSecurityConfigurerAdapterDefaultsAuthManagerConfig {
@Component
public static class WebSecurityAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER");
// @formatter:on
}
}
@Configuration
public static class AuthenticationManagerConfiguration {
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return new CustomAuthenticationManager();
}
}
}
@Configuration
@EnableWebSecurity
static class MultiWebSecurityConfigurerAdapterDefaultsAuthManagerConfig {
@Component
@Order(1)
public static class ApiWebSecurityAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().hasRole("USER");
// @formatter:on
}
}
@Component
public static class WebSecurityAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER");
// @formatter:on
}
}
@Configuration
public static class AuthenticationManagerConfiguration {
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return new CustomAuthenticationManager();
}
}
}
static class CustomAuthenticationManager implements AuthenticationManager {
static Authentication RESULT = new TestingAuthenticationToken("test", "this", "ROLE_USER");
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return RESULT;
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,13 +27,13 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.preauth.j2ee.J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthenticatedProcessingFilter;
import org.springframework.test.web.servlet.MockMvc;
@ -154,15 +154,16 @@ public class JeeConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.jee();
return http.build();
// @formatter:on
}
@ -184,16 +185,17 @@ public class JeeConfigurerTests {
@Configuration
@EnableWebSecurity
static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
static class InvokeTwiceDoesNotOverride {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.jee()
.mappableRoles("USER")
.and()
.jee();
return http.build();
// @formatter:on
}
@ -201,10 +203,10 @@ public class JeeConfigurerTests {
@Configuration
@EnableWebSecurity
public static class JeeMappableRolesConfig extends WebSecurityConfigurerAdapter {
public static class JeeMappableRolesConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -215,6 +217,7 @@ public class JeeConfigurerTests {
jee
.mappableRoles("USER")
);
return http.build();
// @formatter:on
}
@ -222,10 +225,10 @@ public class JeeConfigurerTests {
@Configuration
@EnableWebSecurity
public static class JeeMappableAuthoritiesConfig extends WebSecurityConfigurerAdapter {
public static class JeeMappableAuthoritiesConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -236,6 +239,7 @@ public class JeeConfigurerTests {
jee
.mappableAuthorities("ROLE_USER")
);
return http.build();
// @formatter:on
}
@ -243,13 +247,13 @@ public class JeeConfigurerTests {
@Configuration
@EnableWebSecurity
public static class JeeCustomAuthenticatedUserDetailsServiceConfig extends WebSecurityConfigurerAdapter {
public static class JeeCustomAuthenticatedUserDetailsServiceConfig {
static AuthenticationUserDetailsService authenticationUserDetailsService = mock(
AuthenticationUserDetailsService.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -260,6 +264,7 @@ public class JeeConfigurerTests {
jee
.authenticatedUserDetailsService(authenticationUserDetailsService)
);
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,14 +20,15 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler;
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter;
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive;
@ -90,14 +91,15 @@ public class LogoutConfigurerClearSiteDataTests {
@Configuration
@EnableWebSecurity
static class HttpLogoutConfig extends WebSecurityConfigurerAdapter {
static class HttpLogoutConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE)));
return http.build();
// @formatter:on
}

View File

@ -27,13 +27,15 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityContextChangedListenerConfig;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
@ -324,14 +326,15 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class NullLogoutSuccessHandlerConfig extends WebSecurityConfigurerAdapter {
static class NullLogoutSuccessHandlerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
.defaultLogoutSuccessHandlerFor(null, mock(RequestMatcher.class));
return http.build();
// @formatter:on
}
@ -339,15 +342,16 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class NullLogoutSuccessHandlerInLambdaConfig extends WebSecurityConfigurerAdapter {
static class NullLogoutSuccessHandlerInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout((logout) ->
logout.defaultLogoutSuccessHandlerFor(null, mock(RequestMatcher.class))
);
return http.build();
// @formatter:on
}
@ -355,14 +359,15 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class NullMatcherConfig extends WebSecurityConfigurerAdapter {
static class NullMatcherConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
.defaultLogoutSuccessHandlerFor(mock(LogoutSuccessHandler.class), null);
return http.build();
// @formatter:on
}
@ -370,15 +375,16 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class NullMatcherInLambdaConfig extends WebSecurityConfigurerAdapter {
static class NullMatcherInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout((logout) ->
logout.defaultLogoutSuccessHandlerFor(mock(LogoutSuccessHandler.class), null)
);
return http.build();
// @formatter:on
}
@ -386,15 +392,16 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout();
return http.build();
// @formatter:on
}
@ -416,10 +423,10 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class DuplicateDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class DuplicateDoesNotOverrideConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
@ -427,29 +434,28 @@ public class LogoutConfigurerTests {
.and()
.logout();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class CsrfDisabledConfig extends WebSecurityConfigurerAdapter {
static class CsrfDisabledConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.disable()
.logout();
return http.build();
// @formatter:on
}
@ -457,16 +463,17 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class CsrfDisabledAndCustomLogoutConfig extends WebSecurityConfigurerAdapter {
static class CsrfDisabledAndCustomLogoutConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.disable()
.logout()
.logoutUrl("/custom/logout");
return http.build();
// @formatter:on
}
@ -474,15 +481,16 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class CsrfDisabledAndCustomLogoutInLambdaConfig extends WebSecurityConfigurerAdapter {
static class CsrfDisabledAndCustomLogoutInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.disable()
.logout((logout) -> logout.logoutUrl("/custom/logout"));
return http.build();
// @formatter:on
}
@ -490,14 +498,15 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class NullLogoutHandlerConfig extends WebSecurityConfigurerAdapter {
static class NullLogoutHandlerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
.addLogoutHandler(null);
return http.build();
// @formatter:on
}
@ -505,13 +514,14 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class NullLogoutHandlerInLambdaConfig extends WebSecurityConfigurerAdapter {
static class NullLogoutHandlerInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout((logout) -> logout.addLogoutHandler(null));
return http.build();
// @formatter:on
}
@ -519,16 +529,17 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class RememberMeNoLogoutHandler extends WebSecurityConfigurerAdapter {
static class RememberMeNoLogoutHandler {
static RememberMeServices REMEMBER_ME = mock(RememberMeServices.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.rememberMe()
.rememberMeServices(REMEMBER_ME);
return http.build();
// @formatter:on
}
@ -536,20 +547,21 @@ public class LogoutConfigurerTests {
@Configuration
@EnableWebSecurity
static class BasicSecurityConfig extends WebSecurityConfigurerAdapter {
static class BasicSecurityConfig {
}
@Configuration
@EnableWebSecurity
static class LogoutDisabledConfig extends WebSecurityConfigurerAdapter {
static class LogoutDisabledConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
.disable();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,7 +27,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.debug.DebugFilter;
@ -87,13 +86,13 @@ public class NamespaceDebugTests {
@Configuration
@EnableWebSecurity(debug = true)
static class DebugWebSecurity extends WebSecurityConfigurerAdapter {
static class DebugWebSecurity {
}
@Configuration
@EnableWebSecurity
static class NoDebugWebSecurity extends WebSecurityConfigurerAdapter {
static class NoDebugWebSecurity {
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,17 +22,19 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@ -89,15 +91,16 @@ public class NamespaceHttpAnonymousTests {
@Configuration
@EnableWebSecurity
static class AnonymousConfig extends WebSecurityConfigurerAdapter {
static class AnonymousConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/type").anonymous()
.anyRequest().denyAll();
return http.build();
// @formatter:on
}
@ -105,10 +108,10 @@ public class NamespaceHttpAnonymousTests {
@Configuration
@EnableWebSecurity
static class AnonymousDisabledConfig extends WebSecurityConfigurerAdapter {
static class AnonymousDisabledConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -116,26 +119,22 @@ public class NamespaceHttpAnonymousTests {
.and()
.anonymous().disable();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user())
.withUser(PasswordEncodedUser.admin());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user(), PasswordEncodedUser.admin());
}
}
@Configuration
@EnableWebSecurity
static class AnonymousGrantedAuthorityConfig extends WebSecurityConfigurerAdapter {
static class AnonymousGrantedAuthorityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -144,6 +143,7 @@ public class NamespaceHttpAnonymousTests {
.and()
.anonymous()
.authorities("ROLE_ANON");
return http.build();
// @formatter:on
}
@ -151,10 +151,10 @@ public class NamespaceHttpAnonymousTests {
@Configuration
@EnableWebSecurity
static class AnonymousKeyConfig extends WebSecurityConfigurerAdapter {
static class AnonymousKeyConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -162,6 +162,7 @@ public class NamespaceHttpAnonymousTests {
.anyRequest().denyAll()
.and()
.anonymous().key("AnonymousKeyConfig");
return http.build();
// @formatter:on
}
@ -169,10 +170,10 @@ public class NamespaceHttpAnonymousTests {
@Configuration
@EnableWebSecurity
static class AnonymousUsernameConfig extends WebSecurityConfigurerAdapter {
static class AnonymousUsernameConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -180,6 +181,7 @@ public class NamespaceHttpAnonymousTests {
.anyRequest().denyAll()
.and()
.anonymous().principal("AnonymousUsernameConfig");
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,13 +27,13 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
@ -177,16 +177,17 @@ public class NamespaceHttpBasicTests {
@Configuration
@EnableWebSecurity
static class HttpBasicConfig extends WebSecurityConfigurerAdapter {
static class HttpBasicConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
.httpBasic();
return http.build();
// @formatter:on
}
@ -194,10 +195,10 @@ public class NamespaceHttpBasicTests {
@Configuration
@EnableWebSecurity
static class HttpBasicLambdaConfig extends WebSecurityConfigurerAdapter {
static class HttpBasicLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -205,6 +206,7 @@ public class NamespaceHttpBasicTests {
.anyRequest().hasRole("USER")
)
.httpBasic(withDefaults());
return http.build();
// @formatter:on
}
@ -212,16 +214,17 @@ public class NamespaceHttpBasicTests {
@Configuration
@EnableWebSecurity
static class CustomHttpBasicConfig extends WebSecurityConfigurerAdapter {
static class CustomHttpBasicConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
.httpBasic().realmName("Custom Realm");
return http.build();
// @formatter:on
}
@ -229,10 +232,10 @@ public class NamespaceHttpBasicTests {
@Configuration
@EnableWebSecurity
static class CustomHttpBasicLambdaConfig extends WebSecurityConfigurerAdapter {
static class CustomHttpBasicLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -240,6 +243,7 @@ public class NamespaceHttpBasicTests {
.anyRequest().hasRole("USER")
)
.httpBasic((httpBasicConfig) -> httpBasicConfig.realmName("Custom Realm"));
return http.build();
// @formatter:on
}
@ -247,17 +251,18 @@ public class NamespaceHttpBasicTests {
@Configuration
@EnableWebSecurity
static class AuthenticationDetailsSourceHttpBasicConfig extends WebSecurityConfigurerAdapter {
static class AuthenticationDetailsSourceHttpBasicConfig {
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = mock(
AuthenticationDetailsSource.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.authenticationDetailsSource(this.authenticationDetailsSource);
return http.build();
// @formatter:on
}
@ -270,17 +275,18 @@ public class NamespaceHttpBasicTests {
@Configuration
@EnableWebSecurity
static class AuthenticationDetailsSourceHttpBasicLambdaConfig extends WebSecurityConfigurerAdapter {
static class AuthenticationDetailsSourceHttpBasicLambdaConfig {
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = mock(
AuthenticationDetailsSource.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic((httpBasicConfig) ->
httpBasicConfig.authenticationDetailsSource(this.authenticationDetailsSource));
return http.build();
// @formatter:on
}
@ -293,12 +299,12 @@ public class NamespaceHttpBasicTests {
@Configuration
@EnableWebSecurity
static class EntryPointRefHttpBasicConfig extends WebSecurityConfigurerAdapter {
static class EntryPointRefHttpBasicConfig {
AuthenticationEntryPoint authenticationEntryPoint = (request, response, ex) -> response.setStatus(999);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -306,6 +312,7 @@ public class NamespaceHttpBasicTests {
.and()
.httpBasic()
.authenticationEntryPoint(this.authenticationEntryPoint);
return http.build();
// @formatter:on
}
@ -313,12 +320,12 @@ public class NamespaceHttpBasicTests {
@Configuration
@EnableWebSecurity
static class EntryPointRefHttpBasicLambdaConfig extends WebSecurityConfigurerAdapter {
static class EntryPointRefHttpBasicLambdaConfig {
AuthenticationEntryPoint authenticationEntryPoint = (request, response, ex) -> response.setStatus(999);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -327,6 +334,7 @@ public class NamespaceHttpBasicTests {
)
.httpBasic((httpBasicConfig) ->
httpBasicConfig.authenticationEntryPoint(this.authenticationEntryPoint));
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -32,8 +32,8 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.TestHttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
@ -43,6 +43,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;
@ -100,14 +101,15 @@ public class NamespaceHttpCustomFilterTests {
@Configuration
@EnableWebSecurity
static class CustomFilterBeforeConfig extends WebSecurityConfigurerAdapter {
static class CustomFilterBeforeConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
.formLogin();
return http.build();
// @formatter:on
}
@ -115,14 +117,15 @@ public class NamespaceHttpCustomFilterTests {
@Configuration
@EnableWebSecurity
static class CustomFilterAfterConfig extends WebSecurityConfigurerAdapter {
static class CustomFilterAfterConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterAfter(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
.formLogin();
return http.build();
// @formatter:on
}
@ -130,20 +133,17 @@ public class NamespaceHttpCustomFilterTests {
@Configuration
@EnableWebSecurity
static class CustomFilterPositionConfig extends WebSecurityConfigurerAdapter {
static class CustomFilterPositionConfig {
CustomFilterPositionConfig() {
// do not add the default filters to make testing easier
super(true);
}
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
TestHttpSecurity.disableDefaults(http);
http
// this works so long as the CustomFilter extends one of the standard filters
// if not, use addFilterBefore or addFilterAfter
.addFilter(new CustomFilter());
return http.build();
// @formatter:on
}
@ -151,18 +151,15 @@ public class NamespaceHttpCustomFilterTests {
@Configuration
@EnableWebSecurity
static class CustomFilterPositionAtConfig extends WebSecurityConfigurerAdapter {
static class CustomFilterPositionAtConfig {
CustomFilterPositionAtConfig() {
// do not add the default filters to make testing easier
super(true);
}
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
TestHttpSecurity.disableDefaults(http);
http
.addFilterAt(new OtherCustomFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
// @formatter:on
}
@ -170,25 +167,23 @@ public class NamespaceHttpCustomFilterTests {
@Configuration
@EnableWebSecurity
static class NoAuthenticationManagerInHttpConfigurationConfig extends WebSecurityConfigurerAdapter {
static class NoAuthenticationManagerInHttpConfigurationConfig {
NoAuthenticationManagerInHttpConfigurationConfig() {
super(true);
}
@Override
protected AuthenticationManager authenticationManager() {
@Bean
AuthenticationManager authenticationManager() {
return new CustomAuthenticationManager();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
TestHttpSecurity.disableDefaults(http);
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
.addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -26,14 +26,17 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
@ -78,22 +81,17 @@ public class NamespaceHttpExpressionHandlerTests {
@Configuration
@EnableWebMvc
@EnableWebSecurity
private static class ExpressionHandlerConfig extends WebSecurityConfigurerAdapter {
static class ExpressionHandlerConfig {
ExpressionHandlerConfig() {
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod").password("password").roles("USER", "ADMIN");
// @formatter:on
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
handler.setExpressionParser(expressionParser());
// @formatter:off
@ -102,6 +100,7 @@ public class NamespaceHttpExpressionHandlerTests {
.expressionHandler(handler)
.anyRequest().access("hasRole('USER')");
// @formatter:on
return http.build();
}
@Bean

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -23,9 +23,8 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
@ -78,11 +77,11 @@ public class NamespaceHttpFirewallTests {
@Configuration
@EnableWebSecurity
static class CustomHttpFirewallConfig extends WebSecurityConfigurerAdapter {
static class CustomHttpFirewallConfig {
@Override
public void configure(WebSecurity web) {
web.httpFirewall(new CustomHttpFirewall());
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.httpFirewall(new CustomHttpFirewall());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -24,14 +24,14 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
@ -111,21 +111,22 @@ public class NamespaceHttpFormLoginTests {
@Configuration
@EnableWebSecurity
static class FormLoginConfig extends WebSecurityConfigurerAdapter {
static class FormLoginConfig {
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/resources/**");
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -133,10 +134,10 @@ public class NamespaceHttpFormLoginTests {
@Configuration
@EnableWebSecurity
static class FormLoginCustomConfig extends WebSecurityConfigurerAdapter {
static class FormLoginCustomConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
boolean alwaysUseDefaultSuccess = true;
// @formatter:off
http
@ -149,7 +150,8 @@ public class NamespaceHttpFormLoginTests {
.loginPage("/authentication/login") // form-login@login-page
.failureUrl("/authentication/login?failed") // form-login@authentication-failure-url
.loginProcessingUrl("/authentication/login/process") // form-login@login-processing-url
.defaultSuccessUrl("/default", alwaysUseDefaultSuccess); // form-login@default-target-url / form-login@always-use-default-target
.defaultSuccessUrl("/default", alwaysUseDefaultSuccess);
return http.build(); // form-login@default-target-url / form-login@always-use-default-target
// @formatter:on
}
@ -157,10 +159,10 @@ public class NamespaceHttpFormLoginTests {
@Configuration
@EnableWebSecurity
static class FormLoginCustomRefsConfig extends WebSecurityConfigurerAdapter {
static class FormLoginCustomRefsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setDefaultTargetUrl("/custom/targetUrl");
// @formatter:off
@ -174,6 +176,7 @@ public class NamespaceHttpFormLoginTests {
.successHandler(successHandler) // form-login@authentication-success-handler-ref
.authenticationDetailsSource(authenticationDetailsSource()) // form-login@authentication-details-source-ref
.and();
return http.build();
// @formatter:on
}

View File

@ -25,12 +25,13 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter;
import org.springframework.security.web.header.writers.frameoptions.StaticAllowFromStrategy;
@ -154,13 +155,14 @@ public class NamespaceHttpHeadersTests {
@Configuration
@EnableWebSecurity
static class HeadersDefaultConfig extends WebSecurityConfigurerAdapter {
static class HeadersDefaultConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers();
return http.build();
// @formatter:on
}
@ -168,15 +170,16 @@ public class NamespaceHttpHeadersTests {
@Configuration
@EnableWebSecurity
static class HeadersCacheControlConfig extends WebSecurityConfigurerAdapter {
static class HeadersCacheControlConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.cacheControl();
return http.build();
// @formatter:on
}
@ -184,15 +187,16 @@ public class NamespaceHttpHeadersTests {
@Configuration
@EnableWebSecurity
static class HstsConfig extends WebSecurityConfigurerAdapter {
static class HstsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.httpStrictTransportSecurity();
return http.build();
// @formatter:on
}
@ -200,10 +204,10 @@ public class NamespaceHttpHeadersTests {
@Configuration
@EnableWebSecurity
static class HstsCustomConfig extends WebSecurityConfigurerAdapter {
static class HstsCustomConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -213,6 +217,7 @@ public class NamespaceHttpHeadersTests {
.requestMatcher(AnyRequestMatcher.INSTANCE)
.maxAgeInSeconds(15768000)
.includeSubDomains(false);
return http.build();
// @formatter:on
}
@ -220,10 +225,10 @@ public class NamespaceHttpHeadersTests {
@Configuration
@EnableWebSecurity
static class FrameOptionsSameOriginConfig extends WebSecurityConfigurerAdapter {
static class FrameOptionsSameOriginConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -231,6 +236,7 @@ public class NamespaceHttpHeadersTests {
.defaultsDisabled()
.frameOptions()
.sameOrigin();
return http.build();
// @formatter:on
}
@ -238,10 +244,10 @@ public class NamespaceHttpHeadersTests {
@Configuration
@EnableWebSecurity
static class FrameOptionsAllowFromConfig extends WebSecurityConfigurerAdapter {
static class FrameOptionsAllowFromConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -249,6 +255,7 @@ public class NamespaceHttpHeadersTests {
.defaultsDisabled()
.addHeaderWriter(new XFrameOptionsHeaderWriter(
new StaticAllowFromStrategy(URI.create("https://example.com"))));
return http.build();
// @formatter:on
}
@ -256,16 +263,17 @@ public class NamespaceHttpHeadersTests {
@Configuration
@EnableWebSecurity
static class XssProtectionConfig extends WebSecurityConfigurerAdapter {
static class XssProtectionConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
// xss-protection
.defaultsDisabled()
.xssProtection();
return http.build();
// @formatter:on
}
@ -273,10 +281,10 @@ public class NamespaceHttpHeadersTests {
@Configuration
@EnableWebSecurity
static class XssProtectionCustomConfig extends WebSecurityConfigurerAdapter {
static class XssProtectionCustomConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
@ -285,22 +293,24 @@ public class NamespaceHttpHeadersTests {
.xssProtection()
.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED);
// @formatter:on
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class ContentTypeOptionsConfig extends WebSecurityConfigurerAdapter {
static class ContentTypeOptionsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
// content-type-options
.defaultsDisabled()
.contentTypeOptions();
return http.build();
// @formatter:on
}
@ -308,15 +318,16 @@ public class NamespaceHttpHeadersTests {
@Configuration
@EnableWebSecurity
static class HeaderRefConfig extends WebSecurityConfigurerAdapter {
static class HeaderRefConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers()
.defaultsDisabled()
.addHeaderWriter(new StaticHeadersWriter("customHeaderName", "customHeaderValue"));
return http.build();
// @formatter:on
}

View File

@ -20,17 +20,20 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.web.bind.annotation.GetMapping;
@ -107,10 +110,10 @@ public class NamespaceHttpInterceptUrlTests {
@Configuration
@EnableWebSecurity
static class HttpInterceptUrlConfig extends WebSecurityConfigurerAdapter {
static class HttpInterceptUrlConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests().antMatchers(
@ -132,16 +135,12 @@ HttpMethod.POST, "/admin/post", "/admin/another-post/**").hasRole("ADMIN")
//" requires-channel="https"/>
.requiresSecure().anyRequest().requiresInsecure();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user(), PasswordEncodedUser.admin());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,13 +27,13 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@ -97,10 +97,10 @@ public class NamespaceHttpJeeTests {
@Configuration
@EnableWebSecurity
public static class JeeMappableRolesConfig extends WebSecurityConfigurerAdapter {
public static class JeeMappableRolesConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -108,6 +108,7 @@ public class NamespaceHttpJeeTests {
.and()
.jee()
.mappableRoles("user", "admin");
return http.build();
// @formatter:on
}
@ -115,13 +116,13 @@ public class NamespaceHttpJeeTests {
@Configuration
@EnableWebSecurity
public static class JeeUserServiceRefConfig extends WebSecurityConfigurerAdapter {
public static class JeeUserServiceRefConfig {
private final AuthenticationUserDetailsService authenticationUserDetailsService = mock(
AuthenticationUserDetailsService.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -130,6 +131,7 @@ public class NamespaceHttpJeeTests {
.jee()
.mappableAuthorities("ROLE_user", "ROLE_admin")
.authenticatedUserDetailsService(this.authenticationUserDetailsService);
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -26,16 +26,17 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
@ -165,38 +166,41 @@ public class NamespaceHttpLogoutTests {
@Configuration
@EnableWebSecurity
static class HttpLogoutConfig extends WebSecurityConfigurerAdapter {
static class HttpLogoutConfig {
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class HttpLogoutDisabledInLambdaConfig extends WebSecurityConfigurerAdapter {
static class HttpLogoutDisabledInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.logout(AbstractHttpConfigurer::disable);
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class CustomHttpLogoutConfig extends WebSecurityConfigurerAdapter {
static class CustomHttpLogoutConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
.deleteCookies("remove") // logout@delete-cookies
.invalidateHttpSession(false) // logout@invalidate-session=false (default is true)
.logoutUrl("/custom-logout") // logout@logout-url (default is /logout)
.logoutSuccessUrl("/logout-success"); // logout@success-url (default is /login?logout)
.logoutSuccessUrl("/logout-success");
return http.build(); // logout@success-url (default is /login?logout)
// @formatter:on
}
@ -204,10 +208,10 @@ public class NamespaceHttpLogoutTests {
@Configuration
@EnableWebSecurity
static class CustomHttpLogoutInLambdaConfig extends WebSecurityConfigurerAdapter {
static class CustomHttpLogoutInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout((logout) ->
@ -216,6 +220,7 @@ public class NamespaceHttpLogoutTests {
.logoutUrl("/custom-logout")
.logoutSuccessUrl("/logout-success")
);
return http.build();
// @formatter:on
}
@ -223,16 +228,17 @@ public class NamespaceHttpLogoutTests {
@Configuration
@EnableWebSecurity
static class SuccessHandlerRefHttpLogoutConfig extends WebSecurityConfigurerAdapter {
static class SuccessHandlerRefHttpLogoutConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
logoutSuccessHandler.setDefaultTargetUrl("/SuccessHandlerRefHttpLogoutConfig");
// @formatter:off
http
.logout()
.logoutSuccessHandler(logoutSuccessHandler);
return http.build();
// @formatter:on
}
@ -240,15 +246,16 @@ public class NamespaceHttpLogoutTests {
@Configuration
@EnableWebSecurity
static class SuccessHandlerRefHttpLogoutInLambdaConfig extends WebSecurityConfigurerAdapter {
static class SuccessHandlerRefHttpLogoutInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
logoutSuccessHandler.setDefaultTargetUrl("/SuccessHandlerRefHttpLogoutConfig");
// @formatter:off
http
.logout((logout) -> logout.logoutSuccessHandler(logoutSuccessHandler));
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,13 +20,16 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@ -59,10 +62,10 @@ public class NamespaceHttpPortMappingsTests {
@Configuration
@EnableWebSecurity
static class HttpInterceptUrlWithPortMapperConfig extends WebSecurityConfigurerAdapter {
static class HttpInterceptUrlWithPortMapperConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -75,16 +78,12 @@ public class NamespaceHttpPortMappingsTests {
.antMatchers("/login", "/secured/**").requiresSecure()
.anyRequest().requiresInsecure();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user(), PasswordEncodedUser.admin());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,13 +25,14 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
@ -81,10 +82,10 @@ public class NamespaceHttpRequestCacheTests {
@Configuration
@EnableWebSecurity
static class RequestCacheRefConfig extends WebSecurityConfigurerAdapter {
static class RequestCacheRefConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -93,16 +94,12 @@ public class NamespaceHttpRequestCacheTests {
.requestCache()
.requestCache(requestCache());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user())
.withUser(PasswordEncodedUser.admin());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user(), PasswordEncodedUser.admin());
}
@Bean
@ -114,25 +111,21 @@ public class NamespaceHttpRequestCacheTests {
@Configuration
@EnableWebSecurity
static class DefaultRequestCacheRefConfig extends WebSecurityConfigurerAdapter {
static class DefaultRequestCacheRefConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user())
.withUser(PasswordEncodedUser.admin());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user(), PasswordEncodedUser.admin());
}
}

View File

@ -28,11 +28,11 @@ import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.test.web.servlet.MockMvc;
@ -106,10 +106,10 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
@Configuration
@EnableWebSecurity
static class AccessDeniedPageConfig extends WebSecurityConfigurerAdapter {
static class AccessDeniedPageConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -117,6 +117,7 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
.and()
.exceptionHandling()
.accessDeniedPage("/AccessDeniedPageConfig");
return http.build();
// @formatter:on
}
@ -124,10 +125,10 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
@Configuration
@EnableWebSecurity
static class AccessDeniedPageInLambdaConfig extends WebSecurityConfigurerAdapter {
static class AccessDeniedPageInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -137,6 +138,7 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
.exceptionHandling((exceptionHandling) ->
exceptionHandling.accessDeniedPage("/AccessDeniedPageConfig")
);
return http.build();
// @formatter:on
}
@ -144,10 +146,10 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
@Configuration
@EnableWebSecurity
static class AccessDeniedHandlerRefConfig extends WebSecurityConfigurerAdapter {
static class AccessDeniedHandlerRefConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -155,6 +157,7 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler());
return http.build();
// @formatter:on
}
@ -167,12 +170,12 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
@Configuration
@EnableWebSecurity
static class AccessDeniedHandlerRefInLambdaConfig extends WebSecurityConfigurerAdapter {
static class AccessDeniedHandlerRefInLambdaConfig {
static AccessDeniedHandler accessDeniedHandler = mock(AccessDeniedHandler.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -182,6 +185,7 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
.exceptionHandling((exceptionHandling) ->
exceptionHandling.accessDeniedHandler(accessDeniedHandler())
);
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -34,15 +34,17 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
@ -135,19 +137,17 @@ public class NamespaceHttpX509Tests {
@Configuration
@EnableWebSecurity
@EnableWebMvc
public static class X509Config extends WebSecurityConfigurerAdapter {
public static class X509Config {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -155,6 +155,7 @@ public class NamespaceHttpX509Tests {
.and()
.x509();
// @formatter:on
return http.build();
}
}
@ -162,19 +163,17 @@ public class NamespaceHttpX509Tests {
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class AuthenticationDetailsSourceRefConfig extends WebSecurityConfigurerAdapter {
static class AuthenticationDetailsSourceRefConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -183,6 +182,7 @@ public class NamespaceHttpX509Tests {
.x509()
.authenticationDetailsSource(authenticationDetailsSource());
// @formatter:on
return http.build();
}
@Bean
@ -195,19 +195,17 @@ public class NamespaceHttpX509Tests {
@EnableWebMvc
@Configuration
@EnableWebSecurity
public static class SubjectPrincipalRegexConfig extends WebSecurityConfigurerAdapter {
public static class SubjectPrincipalRegexConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -216,6 +214,7 @@ public class NamespaceHttpX509Tests {
.x509()
.subjectPrincipalRegex("CN=(.*?)@example.com(?:,|$)");
// @formatter:on
return http.build();
}
}
@ -223,19 +222,17 @@ public class NamespaceHttpX509Tests {
@EnableWebMvc
@Configuration
@EnableWebSecurity
public static class CustomPrincipalExtractorConfig extends WebSecurityConfigurerAdapter {
public static class CustomPrincipalExtractorConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod@example.com").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod@example.com").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -244,6 +241,7 @@ public class NamespaceHttpX509Tests {
.x509()
.x509PrincipalExtractor(this::extractCommonName);
// @formatter:on
return http.build();
}
private String extractCommonName(X509Certificate certificate) {
@ -256,19 +254,17 @@ public class NamespaceHttpX509Tests {
@EnableWebMvc
@Configuration
@EnableWebSecurity
public static class UserDetailsServiceRefConfig extends WebSecurityConfigurerAdapter {
public static class UserDetailsServiceRefConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -277,6 +273,7 @@ public class NamespaceHttpX509Tests {
.x509()
.userDetailsService((username) -> USER);
// @formatter:on
return http.build();
}
}
@ -284,19 +281,17 @@ public class NamespaceHttpX509Tests {
@EnableWebMvc
@Configuration
@EnableWebSecurity
public static class AuthenticationUserDetailsServiceConfig extends WebSecurityConfigurerAdapter {
public static class AuthenticationUserDetailsServiceConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -305,6 +300,7 @@ public class NamespaceHttpX509Tests {
.x509()
.authenticationUserDetailsService((authentication) -> USER);
// @formatter:on
return http.build();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,10 +28,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
@ -39,6 +37,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
@ -138,11 +137,10 @@ public class NamespaceRememberMeTests {
@Test
public void rememberMeLoginWhenKeyDeclaredThenMatchesNamespace() throws Exception {
this.spring.register(WithoutKeyConfig.class, KeyConfig.class, SecurityController.class).autowire();
this.spring.register(WithoutKeyConfig.class, SecurityController.class).autowire();
MockHttpServletRequestBuilder requestWithRememberme = post("/without-key/login").with(rememberMeLogin());
// @formatter:off
Cookie withoutKey = this.mvc.perform(requestWithRememberme)
.andExpect(redirectedUrl("/"))
.andReturn()
.getResponse()
.getCookie("remember-me");
@ -284,8 +282,8 @@ public class NamespaceRememberMeTests {
@EnableWebSecurity
static class RememberMeConfig extends UsersConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -294,6 +292,7 @@ public class NamespaceRememberMeTests {
.formLogin()
.and()
.rememberMe();
return http.build();
// @formatter:on
}
@ -305,18 +304,19 @@ public class NamespaceRememberMeTests {
@Configuration
@EnableWebSecurity
static class RememberMeServicesRefConfig extends WebSecurityConfigurerAdapter {
static class RememberMeServicesRefConfig {
static RememberMeServices REMEMBER_ME_SERVICES;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.and()
.rememberMe()
.rememberMeServices(REMEMBER_ME_SERVICES);
return http.build();
// @formatter:on
}
@ -328,14 +328,15 @@ public class NamespaceRememberMeTests {
static AuthenticationSuccessHandler SUCCESS_HANDLER;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.and()
.rememberMe()
.authenticationSuccessHandler(SUCCESS_HANDLER);
return http.build();
// @formatter:on
}
@ -343,29 +344,26 @@ public class NamespaceRememberMeTests {
@Configuration
@EnableWebSecurity
@Order(0)
static class WithoutKeyConfig extends UsersConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
@Order(0)
SecurityFilterChain withoutKeyFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.antMatcher("/without-key/**")
.formLogin()
.loginProcessingUrl("/without-key/login")
.and()
.rememberMe();
.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated())
.formLogin()
.loginProcessingUrl("/without-key/login")
.and()
.rememberMe();
return http.build();
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
static class KeyConfig extends UsersConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
@Order(1)
SecurityFilterChain keyFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -375,6 +373,7 @@ public class NamespaceRememberMeTests {
.and()
.rememberMe()
.key("KeyConfig");
return http.build();
// @formatter:on
}
@ -386,8 +385,8 @@ public class NamespaceRememberMeTests {
static PersistentTokenRepository TOKEN_REPOSITORY;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl()
// tokenRepository.setDataSource(dataSource);
// @formatter:off
@ -396,6 +395,7 @@ public class NamespaceRememberMeTests {
.and()
.rememberMe()
.tokenRepository(TOKEN_REPOSITORY);
return http.build();
// @formatter:on
}
@ -405,8 +405,8 @@ public class NamespaceRememberMeTests {
@EnableWebSecurity
static class TokenValiditySecondsConfig extends UsersConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -416,6 +416,7 @@ public class NamespaceRememberMeTests {
.and()
.rememberMe()
.tokenValiditySeconds(314);
return http.build();
// @formatter:on
}
@ -425,14 +426,15 @@ public class NamespaceRememberMeTests {
@EnableWebSecurity
static class UseSecureCookieConfig extends UsersConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.and()
.rememberMe()
.useSecureCookie(true);
return http.build();
// @formatter:on
}
@ -442,14 +444,15 @@ public class NamespaceRememberMeTests {
@EnableWebSecurity
static class RememberMeParameterConfig extends UsersConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.and()
.rememberMe()
.rememberMeParameter("rememberMe");
return http.build();
// @formatter:on
}
@ -459,14 +462,15 @@ public class NamespaceRememberMeTests {
@EnableWebSecurity
static class RememberMeCookieNameConfig extends UsersConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.and()
.rememberMe()
.rememberMeCookieName("rememberMe");
return http.build();
// @formatter:on
}
@ -474,26 +478,24 @@ public class NamespaceRememberMeTests {
@EnableWebSecurity
@Configuration
static class DefaultsUserDetailsServiceWithDaoConfig extends WebSecurityConfigurerAdapter {
static class DefaultsUserDetailsServiceWithDaoConfig {
static UserDetailsService USERDETAILS_SERVICE;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.and()
.rememberMe();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.userDetailsService(USERDETAILS_SERVICE);
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return USERDETAILS_SERVICE;
}
}
@ -504,24 +506,24 @@ public class NamespaceRememberMeTests {
static UserDetailsService USERDETAILS_SERVICE;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.and()
.rememberMe()
.userDetailsService(USERDETAILS_SERVICE);
return http.build();
// @formatter:on
}
}
static class UsersConfig extends WebSecurityConfigurerAdapter {
static class UsersConfig {
@Override
@Bean
public UserDetailsService userDetailsService() {
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
// @formatter:off
User.withDefaultPasswordEncoder()

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -32,9 +32,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
@ -44,6 +44,7 @@ import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@ -256,29 +257,33 @@ public class NamespaceSessionManagementTests {
@Configuration
@EnableWebSecurity
static class SessionManagementConfig extends WebSecurityConfigurerAdapter {
static class SessionManagementConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
super.configure(http);
http
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().authenticated()
)
.sessionManagement((sessions) -> sessions
.requireExplicitAuthenticationStrategy(false)
);
)
.httpBasic(Customizer.withDefaults());
// @formatter:on
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class CustomSessionManagementConfig extends WebSecurityConfigurerAdapter {
static class CustomSessionManagementConfig {
SessionRegistry sessionRegistry = spy(SessionRegistryImpl.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -292,7 +297,8 @@ public class NamespaceSessionManagementTests {
.maximumSessions(1) // session-management/concurrency-control@max-sessions
.maxSessionsPreventsLogin(true) // session-management/concurrency-control@error-if-maximum-exceeded
.expiredUrl("/expired-session") // session-management/concurrency-control@expired-url
.sessionRegistry(sessionRegistry()); // session-management/concurrency-control@session-registry-ref
.sessionRegistry(sessionRegistry());
return http.build(); // session-management/concurrency-control@session-registry-ref
// @formatter:on
}
@ -305,16 +311,17 @@ public class NamespaceSessionManagementTests {
@Configuration
@EnableWebSecurity
static class InvalidSessionStrategyConfig extends WebSecurityConfigurerAdapter {
static class InvalidSessionStrategyConfig {
InvalidSessionStrategy invalidSessionStrategy = mock(InvalidSessionStrategy.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.invalidSessionStrategy(invalidSessionStrategy());
return http.build();
// @formatter:on
}
@ -327,18 +334,19 @@ public class NamespaceSessionManagementTests {
@Configuration
@EnableWebSecurity
static class RefsSessionManagementConfig extends WebSecurityConfigurerAdapter {
static class RefsSessionManagementConfig {
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.sessionAuthenticationStrategy(sessionAuthenticationStrategy()) // session-management@session-authentication-strategy-ref
.and()
.httpBasic();
return http.build();
// @formatter:on
}
@ -351,16 +359,17 @@ public class NamespaceSessionManagementTests {
@Configuration
@EnableWebSecurity
static class SFPNoneSessionManagementConfig extends WebSecurityConfigurerAdapter {
static class SFPNoneSessionManagementConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy())
.and()
.httpBasic();
return http.build();
// @formatter:on
}
@ -368,16 +377,17 @@ public class NamespaceSessionManagementTests {
@Configuration
@EnableWebSecurity
static class SFPMigrateSessionManagementConfig extends WebSecurityConfigurerAdapter {
static class SFPMigrateSessionManagementConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.requireExplicitAuthenticationStrategy(false)
.and()
.httpBasic();
return http.build();
// @formatter:on
}
@ -385,16 +395,17 @@ public class NamespaceSessionManagementTests {
@Configuration
@EnableWebSecurity
static class SFPPostProcessedConfig extends WebSecurityConfigurerAdapter {
static class SFPPostProcessedConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement((sessions) -> sessions
.requireExplicitAuthenticationStrategy(false)
)
.httpBasic();
return http.build();
// @formatter:on
}
@ -407,10 +418,10 @@ public class NamespaceSessionManagementTests {
@Configuration
@EnableWebSecurity
static class SFPNewSessionSessionManagementConfig extends WebSecurityConfigurerAdapter {
static class SFPNewSessionSessionManagementConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement((sessions) -> sessions
@ -418,6 +429,7 @@ public class NamespaceSessionManagementTests {
.requireExplicitAuthenticationStrategy(false)
)
.httpBasic();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -21,12 +21,13 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
@ -92,10 +93,10 @@ public class PermitAllSupportTests {
@Configuration
@EnableWebSecurity
static class PermitAllConfig extends WebSecurityConfigurerAdapter {
static class PermitAllConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -104,6 +105,7 @@ public class PermitAllSupportTests {
.formLogin()
.loginPage("/xyz").permitAll()
.loginProcessingUrl("/abc?def").permitAll();
return http.build();
// @formatter:on
}
@ -111,10 +113,10 @@ public class PermitAllSupportTests {
@Configuration
@EnableWebSecurity
static class PermitAllConfigAuthorizeHttpRequests extends WebSecurityConfigurerAdapter {
static class PermitAllConfigAuthorizeHttpRequests {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests()
@ -123,6 +125,7 @@ public class PermitAllSupportTests {
.formLogin()
.loginPage("/xyz").permitAll()
.loginProcessingUrl("/abc?def").permitAll();
return http.build();
// @formatter:on
}
@ -130,10 +133,10 @@ public class PermitAllSupportTests {
@Configuration
@EnableWebSecurity
static class PermitAllConfigWithBothConfigs extends WebSecurityConfigurerAdapter {
static class PermitAllConfigWithBothConfigs {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -145,6 +148,7 @@ public class PermitAllSupportTests {
.formLogin()
.loginPage("/xyz").permitAll()
.loginProcessingUrl("/abc?def").permitAll();
return http.build();
// @formatter:on
}
@ -152,14 +156,15 @@ public class PermitAllSupportTests {
@Configuration
@EnableWebSecurity
static class NoAuthorizedUrlsConfig extends WebSecurityConfigurerAdapter {
static class NoAuthorizedUrlsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.permitAll();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,13 +22,14 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.PortMapperImpl;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@ -66,10 +67,10 @@ public class PortMapperConfigurerTests {
@Configuration
@EnableWebSecurity
static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
static class InvokeTwiceDoesNotOverride {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requiresChannel()
@ -79,6 +80,7 @@ public class PortMapperConfigurerTests {
.http(543).mapsTo(123)
.and()
.portMapper();
return http.build();
// @formatter:on
}
@ -86,10 +88,10 @@ public class PortMapperConfigurerTests {
@Configuration
@EnableWebSecurity
static class HttpMapsToInLambdaConfig extends WebSecurityConfigurerAdapter {
static class HttpMapsToInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requiresChannel((requiresChannel) ->
@ -100,6 +102,7 @@ public class PortMapperConfigurerTests {
portMapper
.http(543).mapsTo(123)
);
return http.build();
// @formatter:on
}
@ -107,10 +110,10 @@ public class PortMapperConfigurerTests {
@Configuration
@EnableWebSecurity
static class CustomPortMapperInLambdaConfig extends WebSecurityConfigurerAdapter {
static class CustomPortMapperInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
PortMapperImpl customPortMapper = new PortMapperImpl();
customPortMapper.setPortMappings(Collections.singletonMap("543", "123"));
// @formatter:off
@ -123,6 +126,7 @@ public class PortMapperConfigurerTests {
portMapper
.portMapper(customPortMapper)
);
return http.build();
// @formatter:on
}

View File

@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -35,7 +36,6 @@ import org.springframework.security.config.annotation.SecurityContextChangedList
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
@ -54,7 +54,6 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilde
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
@ -88,17 +87,9 @@ public class RememberMeConfigurerTests {
@Test
public void postWhenNoUserDetailsServiceThenException() {
this.spring.register(NullUserDetailsConfig.class).autowire();
assertThatIllegalStateException().isThrownBy(() -> {
// @formatter:off
MockHttpServletRequestBuilder request = post("/login")
.param("username", "user")
.param("password", "password")
.param("remember-me", "true")
.with(csrf());
// @formatter:on
this.mvc.perform(request);
}).withMessageContaining("UserDetailsService is required");
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(() -> this.spring.register(NullUserDetailsConfig.class).autowire())
.withMessageContaining("userDetailsService cannot be null");
}
@Test
@ -305,10 +296,10 @@ public class RememberMeConfigurerTests {
@Configuration
@EnableWebSecurity
static class NullUserDetailsConfig extends WebSecurityConfigurerAdapter {
static class NullUserDetailsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -318,10 +309,11 @@ public class RememberMeConfigurerTests {
.and()
.rememberMe();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
@Autowired
void configure(AuthenticationManagerBuilder auth) {
User user = (User) PasswordEncodedUser.user();
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(new InMemoryUserDetailsManager(Collections.singletonList(user)));
@ -335,25 +327,23 @@ public class RememberMeConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.rememberMe()
.userDetailsService(new AuthenticationManagerBuilder(this.objectPostProcessor).getDefaultUserDetailsService());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@Bean
@ -374,12 +364,12 @@ public class RememberMeConfigurerTests {
@Configuration
@EnableWebSecurity
static class DuplicateDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class DuplicateDoesNotOverrideConfig {
static UserDetailsService userDetailsService = mock(UserDetailsService.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
@ -388,12 +378,12 @@ public class RememberMeConfigurerTests {
.userDetailsService(userDetailsService)
.and()
.rememberMe();
return http.build();
// @formatter:on
}
@Override
@Bean
public UserDetailsService userDetailsService() {
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
// @formatter:off
User.withDefaultPasswordEncoder()
@ -430,10 +420,10 @@ public class RememberMeConfigurerTests {
@Configuration
@EnableWebSecurity
static class RememberMeConfig extends WebSecurityConfigurerAdapter {
static class RememberMeConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -442,26 +432,23 @@ public class RememberMeConfigurerTests {
.formLogin()
.and()
.rememberMe();
return http.build();
// @formatter:on
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class RememberMeInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RememberMeInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -470,26 +457,23 @@ public class RememberMeConfigurerTests {
)
.formLogin(withDefaults())
.rememberMe(withDefaults());
return http.build();
// @formatter:on
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class RememberMeCookieDomainConfig extends WebSecurityConfigurerAdapter {
static class RememberMeCookieDomainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -499,26 +483,23 @@ public class RememberMeConfigurerTests {
.and()
.rememberMe()
.rememberMeCookieDomain("spring.io");
return http.build();
// @formatter:on
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class RememberMeCookieDomainInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RememberMeCookieDomainInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -530,28 +511,25 @@ public class RememberMeConfigurerTests {
rememberMe
.rememberMeCookieDomain("spring.io")
);
return http.build();
// @formatter:on
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class RememberMeCookieNameAndRememberMeServicesConfig extends WebSecurityConfigurerAdapter {
static class RememberMeCookieNameAndRememberMeServicesConfig {
static RememberMeServices REMEMBER_ME = mock(RememberMeServices.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -563,6 +541,7 @@ public class RememberMeConfigurerTests {
.rememberMeCookieName("SPRING_COOKIE_DOMAIN")
.rememberMeCookieDomain("spring.io")
.rememberMeServices(REMEMBER_ME);
return http.build();
// @formatter:on
}
@ -581,12 +560,18 @@ public class RememberMeConfigurerTests {
@EnableWebSecurity
static class FallbackRememberMeKeyConfig extends RememberMeConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http.rememberMe()
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
.formLogin()
.and()
.rememberMe()
.rememberMeServices(new TokenBasedRememberMeServices("key", userDetailsService()));
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,15 +28,16 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.test.web.servlet.RequestCacheResultMatcher;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter;
@ -228,8 +229,7 @@ public class RequestCacheConfigurerTests {
// gh-6102
@Test
public void getWhenRequestCacheIsDisabledThenExceptionTranslationFilterDoesNotStoreRequest() throws Exception {
this.spring.register(RequestCacheDisabledConfig.class,
ExceptionHandlingConfigurerTests.DefaultSecurityConfig.class).autowire();
this.spring.register(RequestCacheDisabledConfig.class, DefaultSecurityConfig.class).autowire();
// @formatter:off
MockHttpSession session = (MockHttpSession) this.mvc.perform(get("/bob"))
.andReturn()
@ -303,15 +303,16 @@ public class RequestCacheConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestCache();
return http.build();
// @formatter:on
}
@ -333,18 +334,19 @@ public class RequestCacheConfigurerTests {
@Configuration
@EnableWebSecurity
static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class InvokeTwiceDoesNotOverrideConfig {
static RequestCache requestCache = mock(RequestCache.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestCache()
.requestCache(requestCache)
.and()
.requestCache();
return http.build();
// @formatter:on
}
@ -352,16 +354,17 @@ public class RequestCacheConfigurerTests {
@Configuration
@EnableWebSecurity
static class RequestCacheDefaultsConfig extends WebSecurityConfigurerAdapter {
static class RequestCacheDefaultsConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
return http.build();
// @formatter:on
}
@ -369,22 +372,29 @@ public class RequestCacheConfigurerTests {
@Configuration
@EnableWebSecurity
static class RequestCacheDisabledConfig extends WebSecurityConfigurerAdapter {
static class RequestCacheDisabledConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.requestCache().disable();
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((requests) -> requests
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults())
.requestCache((cache) -> cache.disable());
// @formatter:on
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class RequestCacheDisabledInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RequestCacheDisabledInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -393,6 +403,7 @@ public class RequestCacheConfigurerTests {
)
.formLogin(withDefaults())
.requestCache(RequestCacheConfigurer::disable);
return http.build();
// @formatter:on
}
@ -400,10 +411,10 @@ public class RequestCacheConfigurerTests {
@Configuration
@EnableWebSecurity
static class RequestCacheInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RequestCacheInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -412,6 +423,7 @@ public class RequestCacheConfigurerTests {
)
.formLogin(withDefaults())
.requestCache(withDefaults());
return http.build();
// @formatter:on
}
@ -419,10 +431,10 @@ public class RequestCacheConfigurerTests {
@Configuration
@EnableWebSecurity
static class CustomRequestCacheInLambdaConfig extends WebSecurityConfigurerAdapter {
static class CustomRequestCacheInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -434,6 +446,7 @@ public class RequestCacheConfigurerTests {
requestCache
.requestCache(new NullRequestCache())
);
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,12 +20,13 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@ -70,10 +71,10 @@ public class RequestMatcherConfigurerTests {
@Configuration
@EnableWebSecurity
static class Sec2908Config extends WebSecurityConfigurerAdapter {
static class Sec2908Config {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers()
@ -84,6 +85,7 @@ public class RequestMatcherConfigurerTests {
.and()
.authorizeRequests()
.anyRequest().denyAll();
return http.build();
// @formatter:on
}
@ -91,10 +93,10 @@ public class RequestMatcherConfigurerTests {
@Configuration
@EnableWebSecurity
static class AuthorizeRequestInLambdaConfig extends WebSecurityConfigurerAdapter {
static class AuthorizeRequestInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers((requestMatchers) ->
@ -109,6 +111,7 @@ public class RequestMatcherConfigurerTests {
authorizeRequests
.anyRequest().denyAll()
);
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -29,15 +29,17 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.TestHttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.NullSecurityContextRepository;
@ -139,17 +141,18 @@ public class SecurityContextConfigurerTests {
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Configuration
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.securityContext();
return http.build();
// @formatter:on
}
@ -171,18 +174,19 @@ public class SecurityContextConfigurerTests {
@Configuration
@EnableWebSecurity
static class DuplicateDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class DuplicateDoesNotOverrideConfig {
static SecurityContextRepository SCR = mock(SecurityContextRepository.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.securityContext()
.securityContextRepository(SCR)
.and()
.securityContext();
return http.build();
// @formatter:on
}
@ -190,14 +194,11 @@ public class SecurityContextConfigurerTests {
@Configuration
@EnableWebSecurity
static class SecurityContextRepositoryDefaultsSecurityContextRepositoryConfig extends WebSecurityConfigurerAdapter {
static class SecurityContextRepositoryDefaultsSecurityContextRepositoryConfig {
SecurityContextRepositoryDefaultsSecurityContextRepositoryConfig() {
super(true);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
TestHttpSecurity.disableDefaults(http);
// @formatter:off
http
.addFilter(new WebAsyncManagerIntegrationFilter())
@ -210,73 +211,64 @@ public class SecurityContextConfigurerTests {
.and()
.httpBasic();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class SecurityContextWithDefaultsInLambdaConfig extends WebSecurityConfigurerAdapter {
static class SecurityContextWithDefaultsInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin(withDefaults())
.securityContext(withDefaults());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class SecurityContextDisabledInLambdaConfig extends WebSecurityConfigurerAdapter {
static class SecurityContextDisabledInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin(withDefaults())
.securityContext(AbstractHttpConfigurer::disable);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class NullSecurityContextRepositoryInLambdaConfig extends WebSecurityConfigurerAdapter {
static class NullSecurityContextRepositoryInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin(withDefaults())
@ -285,25 +277,22 @@ public class SecurityContextConfigurerTests {
.securityContextRepository(new NullSecurityContextRepository())
);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class RequireExplicitSaveConfig extends WebSecurityConfigurerAdapter {
static class RequireExplicitSaveConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin(withDefaults())
@ -311,15 +300,12 @@ public class SecurityContextConfigurerTests {
.requireExplicitSave(true)
);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -32,20 +32,23 @@ import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.security.util.FieldUtils;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.CompositeLogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
@ -213,15 +216,16 @@ public class ServletApiConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi();
return http.build();
// @formatter:on
}
@ -243,32 +247,43 @@ public class ServletApiConfigurerTests {
@Configuration
@EnableWebSecurity
static class ServletApiConfig extends WebSecurityConfigurerAdapter {
static class ServletApiConfig {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
http
.authorizeHttpRequests((requests) -> requests
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.formLogin(Customizer.withDefaults());
// @formatter:on
return http.build();
}
@Bean
AuthenticationManager customAuthenticationManager() throws Exception {
return super.authenticationManagerBean();
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@Bean
AuthenticationManager customAuthenticationManager(UserDetailsService userDetailsService) {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
return provider::authenticate;
}
}
@Configuration
@EnableWebSecurity
static class CustomEntryPointConfig extends WebSecurityConfigurerAdapter {
static class CustomEntryPointConfig {
static AuthenticationEntryPoint ENTRYPOINT = spy(AuthenticationEntryPoint.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -279,31 +294,29 @@ public class ServletApiConfigurerTests {
.and()
.formLogin();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class DuplicateInvocationsDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class DuplicateInvocationsDoesNotOverrideConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi()
.rolePrefix("PERMISSION_")
.and()
.servletApi();
return http.build();
// @formatter:on
}
@ -311,15 +324,16 @@ public class ServletApiConfigurerTests {
@Configuration
@EnableWebSecurity
static class SharedTrustResolverConfig extends WebSecurityConfigurerAdapter {
static class SharedTrustResolverConfig {
static AuthenticationTrustResolver TR = spy(AuthenticationTrustResolver.class);
@Override
protected void configure(HttpSecurity http) {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.setSharedObject(AuthenticationTrustResolver.class, TR);
return http.build();
// @formatter:on
}
@ -327,13 +341,14 @@ public class ServletApiConfigurerTests {
@Configuration
@EnableWebSecurity
static class ServletApiWithDefaultsInLambdaConfig extends WebSecurityConfigurerAdapter {
static class ServletApiWithDefaultsInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi(withDefaults());
return http.build();
// @formatter:on
}
@ -341,16 +356,17 @@ public class ServletApiConfigurerTests {
@Configuration
@EnableWebSecurity
static class RolePrefixInLambdaConfig extends WebSecurityConfigurerAdapter {
static class RolePrefixInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi((servletApi) ->
servletApi
.rolePrefix("PERMISSION_")
);
return http.build();
// @formatter:on
}
@ -370,14 +386,15 @@ public class ServletApiConfigurerTests {
@Configuration
@EnableWebSecurity
static class ServletApiWithLogoutConfig extends WebSecurityConfigurerAdapter {
static class ServletApiWithLogoutConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi().and()
.logout();
return http.build();
// @formatter:on
}
@ -385,13 +402,14 @@ public class ServletApiConfigurerTests {
@Configuration
@EnableWebSecurity
static class CsrfDisabledConfig extends WebSecurityConfigurerAdapter {
static class CsrfDisabledConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -23,17 +23,19 @@ import org.junit.jupiter.api.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.csrf.CsrfToken;
@ -109,25 +111,22 @@ public class SessionManagementConfigurerServlet31Tests {
@Configuration
@EnableWebSecurity
static class SessionManagementDefaultSessionFixationServlet31Config extends WebSecurityConfigurerAdapter {
static class SessionManagementDefaultSessionFixationServlet31Config {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
.and()
.sessionManagement();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,15 +22,17 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.test.web.servlet.MockMvc;
@ -61,13 +63,13 @@ public class SessionManagementConfigurerSessionAuthenticationStrategyTests {
@Configuration
@EnableWebSecurity
static class CustomSessionAuthenticationStrategyConfig extends WebSecurityConfigurerAdapter {
static class CustomSessionAuthenticationStrategyConfig {
static SessionAuthenticationStrategy customSessionAuthenticationStrategy = mock(
SessionAuthenticationStrategy.class);
@Override
public void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
@ -75,15 +77,12 @@ public class SessionManagementConfigurerSessionAuthenticationStrategyTests {
.sessionManagement()
.sessionAuthenticationStrategy(customSessionAuthenticationStrategy);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,13 +20,14 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.bind.annotation.GetMapping;
@ -74,35 +75,35 @@ public class SessionManagementConfigurerSessionCreationPolicyTests {
@Configuration
@EnableWebSecurity
static class StatelessCreateSessionSharedObjectConfig extends WebSecurityConfigurerAdapter {
static class StatelessCreateSessionSharedObjectConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.setSharedObject(SessionCreationPolicy.class, SessionCreationPolicy.STATELESS);
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class StatelessCreateSessionUserConfig extends WebSecurityConfigurerAdapter {
static class StatelessCreateSessionUserConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// @formatter:on
http.setSharedObject(SessionCreationPolicy.class, SessionCreationPolicy.ALWAYS);
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class DefaultConfig extends WebSecurityConfigurerAdapter {
static class DefaultConfig {
}

View File

@ -28,17 +28,18 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy;
import org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
@ -359,12 +360,12 @@ public class SessionManagementConfigurerTests {
@Configuration
@EnableWebSecurity
static class SessionManagementRequestCacheConfig extends WebSecurityConfigurerAdapter {
static class SessionManagementRequestCacheConfig {
static RequestCache REQUEST_CACHE;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestCache()
@ -372,6 +373,7 @@ public class SessionManagementConfigurerTests {
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
// @formatter:on
}
@ -379,12 +381,12 @@ public class SessionManagementConfigurerTests {
@Configuration
@EnableWebSecurity
static class SessionManagementSecurityContextRepositoryConfig extends WebSecurityConfigurerAdapter {
static class SessionManagementSecurityContextRepositoryConfig {
static SecurityContextRepository SECURITY_CONTEXT_REPO;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.securityContext()
@ -392,6 +394,7 @@ public class SessionManagementConfigurerTests {
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
// @formatter:on
}
@ -399,16 +402,17 @@ public class SessionManagementConfigurerTests {
@Configuration
@EnableWebSecurity
static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
static class InvokeTwiceDoesNotOverride {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.sessionManagement();
return http.build();
// @formatter:on
}
@ -416,10 +420,10 @@ public class SessionManagementConfigurerTests {
@Configuration
@EnableWebSecurity
static class DisableSessionFixationEnableConcurrencyControlConfig extends WebSecurityConfigurerAdapter {
static class DisableSessionFixationEnableConcurrencyControlConfig {
@Override
public void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
@ -428,25 +432,22 @@ public class SessionManagementConfigurerTests {
.sessionFixation().none()
.maximumSessions(1);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class SFPNewSessionInLambdaConfig extends WebSecurityConfigurerAdapter {
static class SFPNewSessionInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement((sessionManagement) ->
@ -458,25 +459,22 @@ public class SessionManagementConfigurerTests {
)
.httpBasic(withDefaults());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class ConcurrencyControlConfig extends WebSecurityConfigurerAdapter {
static class ConcurrencyControlConfig {
@Override
public void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin()
@ -485,25 +483,22 @@ public class SessionManagementConfigurerTests {
.maximumSessions(1)
.maxSessionsPreventsLogin(true);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class ConcurrencyControlInLambdaConfig extends WebSecurityConfigurerAdapter {
static class ConcurrencyControlInLambdaConfig {
@Override
public void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.formLogin(withDefaults())
@ -516,31 +511,29 @@ public class SessionManagementConfigurerTests {
)
);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static class SessionCreationPolicyStateLessInLambdaConfig extends WebSecurityConfigurerAdapter {
static class SessionCreationPolicyStateLessInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement((sessionManagement) ->
sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
// @formatter:on
}
@ -548,16 +541,17 @@ public class SessionManagementConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.maximumSessions(1);
return http.build();
// @formatter:on
}
@ -579,18 +573,19 @@ public class SessionManagementConfigurerTests {
@Configuration
@EnableWebSecurity
static class SharedTrustResolverConfig extends WebSecurityConfigurerAdapter {
static class SharedTrustResolverConfig {
static AuthenticationTrustResolver TR;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement((sessions) -> sessions
.requireExplicitAuthenticationStrategy(false)
)
.setSharedObject(AuthenticationTrustResolver.class, TR);
return http.build();
// @formatter:on
}
@ -598,16 +593,17 @@ public class SessionManagementConfigurerTests {
@Configuration
@EnableWebSecurity
static class SessionRegistryOneBeanConfig extends WebSecurityConfigurerAdapter {
static class SessionRegistryOneBeanConfig {
private static SessionRegistry SESSION_REGISTRY;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.maximumSessions(1);
return http.build();
// @formatter:on
}
@ -620,18 +616,19 @@ public class SessionManagementConfigurerTests {
@Configuration
@EnableWebSecurity
static class SessionRegistryTwoBeansConfig extends WebSecurityConfigurerAdapter {
static class SessionRegistryTwoBeansConfig {
private static SessionRegistry SESSION_REGISTRY_ONE;
private static SessionRegistry SESSION_REGISTRY_TWO;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.maximumSessions(1);
return http.build();
// @formatter:on
}
@ -682,10 +679,10 @@ public class SessionManagementConfigurerTests {
@Configuration
@EnableWebSecurity
static class HttpBasicSessionCreationPolicyStatelessConfig extends WebSecurityConfigurerAdapter {
static class HttpBasicSessionCreationPolicyStatelessConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement((sessionManagement) ->
@ -694,15 +691,12 @@ public class SessionManagementConfigurerTests {
)
.httpBasic(withDefaults());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@Bean

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,19 +20,19 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.Transient;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
@ -66,36 +66,30 @@ public class SessionManagementConfigurerTransientAuthenticationTests {
@Configuration
@EnableWebSecurity
static class WithTransientAuthenticationConfig extends WebSecurityConfigurerAdapter {
static class WithTransientAuthenticationConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable();
// @formatter:on
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
// @formatter:off
auth
.csrf().disable()
.authenticationProvider(new TransientAuthenticationProvider());
// @formatter:on
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class AlwaysCreateSessionConfig extends WithTransientAuthenticationConfig {
static class AlwaysCreateSessionConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
return http.build();
// @formatter:on
}

View File

@ -32,10 +32,9 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
@ -174,24 +173,22 @@ public class UrlAuthorizationConfigurerTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http, ApplicationContext context) throws Exception {
// @formatter:off
http
.httpBasic().and()
.apply(new UrlAuthorizationConfigurer(getApplicationContext())).getRegistry()
.apply(new UrlAuthorizationConfigurer(context)).getRegistry()
.mvcMatchers("/path").hasRole("ADMIN");
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@RestController
@ -209,24 +206,22 @@ public class UrlAuthorizationConfigurerTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class MvcMatcherServletPathConfig extends WebSecurityConfigurerAdapter {
static class MvcMatcherServletPathConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http, ApplicationContext context) throws Exception {
// @formatter:off
http
.httpBasic().and()
.apply(new UrlAuthorizationConfigurer(getApplicationContext())).getRegistry()
.apply(new UrlAuthorizationConfigurer(context)).getRegistry()
.mvcMatchers("/path").servletPath("/spring").hasRole("ADMIN");
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication();
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
@RestController
@ -243,14 +238,15 @@ public class UrlAuthorizationConfigurerTests {
@EnableWebSecurity
@Configuration
static class AnonymousUrlAuthorizationConfig extends WebSecurityConfigurerAdapter {
static class AnonymousUrlAuthorizationConfig {
@Override
public void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.apply(new UrlAuthorizationConfigurer<>(null)).getRegistry()
.anyRequest().anonymous();
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -24,16 +24,17 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
@ -132,10 +133,10 @@ public class UrlAuthorizationsTests {
@Configuration
@EnableWebSecurity
static class RoleConfig extends WebSecurityConfigurerAdapter {
static class RoleConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -145,6 +146,7 @@ public class UrlAuthorizationsTests {
.antMatchers("/role-user").hasAnyRole("USER")
.antMatchers("/role-admin").hasAnyRole("ADMIN")
.antMatchers("/role-user-admin").hasAnyRole("USER", "ADMIN");
return http.build();
// @formatter:on
}
@ -152,17 +154,17 @@ public class UrlAuthorizationsTests {
@Configuration
@EnableWebSecurity
static class NoSpecificAccessDecisionManagerConfig extends WebSecurityConfigurerAdapter {
static class NoSpecificAccessDecisionManagerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
ApplicationContext context = getApplicationContext();
@Bean
SecurityFilterChain filterChain(HttpSecurity http, ApplicationContext context) throws Exception {
UrlAuthorizationConfigurer<HttpSecurity>.StandardInterceptUrlRegistry registry = http
.apply(new UrlAuthorizationConfigurer(context)).getRegistry();
// @formatter:off
registry
.antMatchers("/a").hasRole("ADMIN")
.anyRequest().hasRole("USER");
return http.build();
// @formatter:on
}

View File

@ -30,15 +30,14 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityContextChangedListenerConfig;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.context.SecurityContextChangedListener;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@ -154,15 +153,16 @@ public class X509ConfigurerTests {
@Configuration
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static class ObjectPostProcessorConfig {
static ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.x509();
return http.build();
// @formatter:on
}
@ -184,10 +184,10 @@ public class X509ConfigurerTests {
@Configuration
@EnableWebSecurity
static class DuplicateDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
static class DuplicateDoesNotOverrideConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.x509()
@ -195,48 +195,46 @@ public class X509ConfigurerTests {
.and()
.x509();
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
}
@Configuration
@EnableWebSecurity
static class DefaultsInLambdaConfig extends WebSecurityConfigurerAdapter {
static class DefaultsInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.x509(withDefaults());
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
}
@Configuration
@EnableWebSecurity
static class SubjectPrincipalRegexInLambdaConfig extends WebSecurityConfigurerAdapter {
static class SubjectPrincipalRegexInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.x509((x509) ->
@ -244,15 +242,14 @@ public class X509ConfigurerTests {
.subjectPrincipalRegex("CN=(.*?)@example.com(?:,|$)")
);
// @formatter:on
return http.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("rod").password("password").roles("USER", "ADMIN");
// @formatter:on
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
.roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -34,7 +34,6 @@ import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
@ -61,6 +60,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequ
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
@ -284,10 +284,10 @@ public class OAuth2ClientConfigurerTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class OAuth2ClientConfig extends WebSecurityConfigurerAdapter {
static class OAuth2ClientConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -301,6 +301,7 @@ public class OAuth2ClientConfigurerTests {
.authorizationRequestResolver(authorizationRequestResolver)
.authorizationRedirectStrategy(authorizationRedirectStrategy)
.accessTokenResponseClient(accessTokenResponseClient);
return http.build();
// @formatter:on
}
@ -330,10 +331,10 @@ public class OAuth2ClientConfigurerTests {
@EnableWebSecurity
@Configuration
@EnableWebMvc
static class OAuth2ClientInLambdaConfig extends WebSecurityConfigurerAdapter {
static class OAuth2ClientInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -341,6 +342,7 @@ public class OAuth2ClientConfigurerTests {
.anyRequest().authenticated()
)
.oauth2Client(withDefaults());
return http.build();
// @formatter:on
}

View File

@ -44,7 +44,6 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.oauth2.client.CommonOAuth2Provider;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
@ -88,6 +87,7 @@ import org.springframework.security.oauth2.jwt.JwtDecoderFactory;
import org.springframework.security.oauth2.jwt.TestJwts;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
@ -660,20 +660,20 @@ public class OAuth2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfig extends CommonWebSecurityConfigurerAdapter
static class OAuth2LoginConfig extends CommonSecurityFilterChainConfig
implements ApplicationListener<AuthenticationSuccessEvent> {
static List<AuthenticationSuccessEvent> EVENTS = new ArrayList<>();
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
.clientRegistrationRepository(
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION));
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
@Override
@ -685,13 +685,13 @@ public class OAuth2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigFormLogin extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigFormLogin extends CommonSecurityFilterChainConfig {
private final InMemoryClientRegistrationRepository clientRegistrationRepository = new InMemoryClientRegistrationRepository(
GOOGLE_CLIENT_REGISTRATION);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
@ -699,20 +699,20 @@ public class OAuth2LoginConfigurerTests {
.and()
.formLogin();
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginInLambdaConfig extends CommonLambdaWebSecurityConfigurerAdapter
static class OAuth2LoginInLambdaConfig extends CommonLambdaSecurityFilterChainConfig
implements ApplicationListener<AuthenticationSuccessEvent> {
static List<AuthenticationSuccessEvent> EVENTS = new ArrayList<>();
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login((oauth2Login) ->
@ -721,7 +721,7 @@ public class OAuth2LoginConfigurerTests {
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION))
);
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
@Override
@ -733,10 +733,10 @@ public class OAuth2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigCustomWithConfigurer extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigCustomWithConfigurer extends CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
@ -745,22 +745,22 @@ public class OAuth2LoginConfigurerTests {
.userInfoEndpoint()
.userAuthoritiesMapper(createGrantedAuthoritiesMapper());
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigCustomWithBeanRegistration extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigCustomWithBeanRegistration extends CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login();
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
@Bean
@ -777,10 +777,10 @@ public class OAuth2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigCustomUserServiceBeanRegistration extends WebSecurityConfigurerAdapter {
static class OAuth2LoginConfigCustomUserServiceBeanRegistration {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -792,6 +792,7 @@ public class OAuth2LoginConfigurerTests {
.oauth2Login()
.tokenEndpoint()
.accessTokenResponseClient(createOauth2AccessTokenResponseClient());
return http.build();
// @formatter:on
}
@ -829,10 +830,10 @@ public class OAuth2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigLoginProcessingUrl extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigLoginProcessingUrl extends CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
@ -840,22 +841,22 @@ public class OAuth2LoginConfigurerTests {
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION))
.loginProcessingUrl("/login/oauth2/*");
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigCustomAuthorizationRequestResolver extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigCustomAuthorizationRequestResolver extends CommonSecurityFilterChainConfig {
private ClientRegistrationRepository clientRegistrationRepository = new InMemoryClientRegistrationRepository(
GOOGLE_CLIENT_REGISTRATION);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
@ -863,7 +864,7 @@ public class OAuth2LoginConfigurerTests {
.authorizationEndpoint()
.authorizationRequestResolver(this.resolver);
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@ -871,15 +872,15 @@ public class OAuth2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigCustomAuthorizationRequestResolverInLambda
extends CommonLambdaWebSecurityConfigurerAdapter {
extends CommonLambdaSecurityFilterChainConfig {
private ClientRegistrationRepository clientRegistrationRepository = new InMemoryClientRegistrationRepository(
GOOGLE_CLIENT_REGISTRATION);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login((oauth2Login) ->
@ -891,22 +892,22 @@ public class OAuth2LoginConfigurerTests {
)
);
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigCustomAuthorizationRedirectStrategy extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigCustomAuthorizationRedirectStrategy extends CommonSecurityFilterChainConfig {
private final ClientRegistrationRepository clientRegistrationRepository = new InMemoryClientRegistrationRepository(
GOOGLE_CLIENT_REGISTRATION);
RedirectStrategy redirectStrategy = mock(RedirectStrategy.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login((oauth2Login) ->
@ -918,22 +919,22 @@ public class OAuth2LoginConfigurerTests {
)
);
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@EnableWebSecurity
static class OAuth2LoginConfigCustomAuthorizationRedirectStrategyInLambda
extends CommonLambdaWebSecurityConfigurerAdapter {
extends CommonLambdaSecurityFilterChainConfig {
private final ClientRegistrationRepository clientRegistrationRepository = new InMemoryClientRegistrationRepository(
GOOGLE_CLIENT_REGISTRATION);
RedirectStrategy redirectStrategy = mock(RedirectStrategy.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain configureFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login((oauth2Login) ->
@ -945,16 +946,17 @@ public class OAuth2LoginConfigurerTests {
)
);
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigMultipleClients extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigMultipleClients extends CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
@ -962,17 +964,17 @@ public class OAuth2LoginConfigurerTests {
new InMemoryClientRegistrationRepository(
GOOGLE_CLIENT_REGISTRATION, GITHUB_CLIENT_REGISTRATION));
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigAuthorizationCodeClientAndOtherClients extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigAuthorizationCodeClientAndOtherClients extends CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
@ -980,17 +982,17 @@ public class OAuth2LoginConfigurerTests {
new InMemoryClientRegistrationRepository(
GOOGLE_CLIENT_REGISTRATION, CLIENT_CREDENTIALS_REGISTRATION));
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigCustomLoginPage extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigCustomLoginPage extends CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
@ -998,17 +1000,17 @@ public class OAuth2LoginConfigurerTests {
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION))
.loginPage("/custom-login");
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigCustomLoginPageInLambda extends CommonLambdaWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigCustomLoginPageInLambda extends CommonLambdaSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login((oauth2Login) ->
@ -1018,23 +1020,23 @@ public class OAuth2LoginConfigurerTests {
.loginPage("/custom-login")
);
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginConfigWithOidcLogoutSuccessHandler extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginConfigWithOidcLogoutSuccessHandler extends CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
.logoutSuccessHandler(oidcLogoutSuccessHandler());
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
@Bean
@ -1053,10 +1055,10 @@ public class OAuth2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
static class OAuth2LoginWithHttpBasicConfig extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginWithHttpBasicConfig extends CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
@ -1065,17 +1067,17 @@ public class OAuth2LoginConfigurerTests {
.and()
.httpBasic();
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
@Configuration
@EnableWebSecurity
static class OAuth2LoginWithXHREntryPointConfig extends CommonWebSecurityConfigurerAdapter {
static class OAuth2LoginWithXHREntryPointConfig extends CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login()
@ -1087,15 +1089,14 @@ public class OAuth2LoginConfigurerTests {
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"));
// @formatter:on
super.configure(http);
return super.configureFilterChain(http);
}
}
private abstract static class CommonWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private abstract static class CommonSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
SecurityFilterChain configureFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1112,6 +1113,7 @@ public class OAuth2LoginConfigurerTests {
.userService(createOauth2UserService())
.oidcUserService(createOidcUserService());
// @formatter:on
return http.build();
}
@Bean
@ -1126,13 +1128,12 @@ public class OAuth2LoginConfigurerTests {
}
private abstract static class CommonLambdaWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private abstract static class CommonLambdaSecurityFilterChainConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
SecurityFilterChain configureFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
.authorizeHttpRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
@ -1153,6 +1154,7 @@ public class OAuth2LoginConfigurerTests {
)
);
// @formatter:on
return http.build();
}
@Bean

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -86,7 +86,6 @@ import org.springframework.security.config.annotation.method.configuration.Enabl
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
@ -1458,10 +1457,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultConfig extends WebSecurityConfigurerAdapter {
static class DefaultConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1470,6 +1469,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -1477,10 +1477,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultInLambdaConfig extends WebSecurityConfigurerAdapter {
static class DefaultInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -1492,6 +1492,7 @@ public class OAuth2ResourceServerConfigurerTests {
oauth2ResourceServer
.jwt(withDefaults())
);
return http.build();
// @formatter:on
}
@ -1499,13 +1500,13 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class JwkSetUriConfig extends WebSecurityConfigurerAdapter {
static class JwkSetUriConfig {
@Value("${mockwebserver.url:https://example.org}")
String jwkSetUri;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1515,6 +1516,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.jwt()
.jwkSetUri(this.jwkSetUri);
return http.build();
// @formatter:on
}
@ -1522,13 +1524,13 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class JwkSetUriInLambdaConfig extends WebSecurityConfigurerAdapter {
static class JwkSetUriInLambdaConfig {
@Value("${mockwebserver.url:https://example.org}")
String jwkSetUri;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -1543,6 +1545,7 @@ public class OAuth2ResourceServerConfigurerTests {
.jwkSetUri(this.jwkSetUri)
)
);
return http.build();
// @formatter:on
}
@ -1550,13 +1553,13 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class CsrfDisabledConfig extends WebSecurityConfigurerAdapter {
static class CsrfDisabledConfig {
@Value("${mockwebserver.url:https://example.org}")
String jwkSetUri;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1567,6 +1570,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.jwt()
.jwkSetUri(this.jwkSetUri);
return http.build();
// @formatter:on
}
@ -1574,10 +1578,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class AnonymousDisabledConfig extends WebSecurityConfigurerAdapter {
static class AnonymousDisabledConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1586,6 +1590,7 @@ public class OAuth2ResourceServerConfigurerTests {
.anonymous().disable()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -1594,10 +1599,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class MethodSecurityConfig extends WebSecurityConfigurerAdapter {
static class MethodSecurityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1605,6 +1610,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -1612,16 +1618,17 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class JwtlessConfig extends WebSecurityConfigurerAdapter {
static class JwtlessConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer();
return http.build();
// @formatter:on
}
@ -1629,10 +1636,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class RealmNameConfiguredOnEntryPoint extends WebSecurityConfigurerAdapter {
static class RealmNameConfiguredOnEntryPoint {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1641,6 +1648,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.authenticationEntryPoint(authenticationEntryPoint())
.jwt();
return http.build();
// @formatter:on
}
@ -1654,10 +1662,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class RealmNameConfiguredOnAccessDeniedHandler extends WebSecurityConfigurerAdapter {
static class RealmNameConfiguredOnAccessDeniedHandler {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1666,6 +1674,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.accessDeniedHandler(accessDeniedHandler())
.jwt();
return http.build();
// @formatter:on
}
@ -1679,10 +1688,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class ExceptionHandlingAndResourceServerWithAccessDeniedHandlerConfig extends WebSecurityConfigurerAdapter {
static class ExceptionHandlingAndResourceServerWithAccessDeniedHandlerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1695,12 +1704,12 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@Override
@Bean
public UserDetailsService userDetailsService() {
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
// @formatter:off
org.springframework.security.core.userdetails.User.withDefaultPasswordEncoder()
@ -1715,12 +1724,12 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class JwtAuthenticationConverterConfiguredOnDsl extends WebSecurityConfigurerAdapter {
static class JwtAuthenticationConverterConfiguredOnDsl {
private final Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter = mock(Converter.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1729,6 +1738,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(getJwtAuthenticationConverter());
return http.build();
// @formatter:on
}
@ -1740,10 +1750,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class CustomAuthorityMappingConfig extends WebSecurityConfigurerAdapter {
static class CustomAuthorityMappingConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1752,6 +1762,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(getJwtAuthenticationConverter());
return http.build();
// @formatter:on
}
@ -1766,10 +1777,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class BasicAndResourceServerConfig extends WebSecurityConfigurerAdapter {
static class BasicAndResourceServerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1779,12 +1790,12 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@Override
@Bean
public UserDetailsService userDetailsService() {
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
// @formatter:off
org.springframework.security.core.userdetails.User.withDefaultPasswordEncoder()
@ -1799,10 +1810,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class FormAndResourceServerConfig extends WebSecurityConfigurerAdapter {
static class FormAndResourceServerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1812,6 +1823,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -1819,10 +1831,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class OAuth2LoginAndResourceServerConfig extends WebSecurityConfigurerAdapter {
static class OAuth2LoginAndResourceServerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authz) -> authz
@ -1832,6 +1844,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer((oauth2) -> oauth2
.jwt()
);
return http.build();
// @formatter:on
}
@ -1845,17 +1858,18 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class JwtHalfConfiguredConfig extends WebSecurityConfigurerAdapter {
static class JwtHalfConfiguredConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt(); // missing key configuration, e.g. jwkSetUri
.jwt();
return http.build(); // missing key configuration, e.g. jwkSetUri
// @formatter:on
}
@ -1863,10 +1877,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class AlwaysSessionCreationConfig extends WebSecurityConfigurerAdapter {
static class AlwaysSessionCreationConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
@ -1874,6 +1888,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -1881,10 +1896,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class AllowBearerTokenInRequestBodyConfig extends WebSecurityConfigurerAdapter {
static class AllowBearerTokenInRequestBodyConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1893,6 +1908,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.bearerTokenResolver(allowRequestBody())
.jwt();
return http.build();
// @formatter:on
}
@ -1906,10 +1922,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class AllowBearerTokenAsQueryParameterConfig extends WebSecurityConfigurerAdapter {
static class AllowBearerTokenAsQueryParameterConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1917,6 +1933,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -1931,10 +1948,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class MultipleBearerTokenResolverBeansConfig extends WebSecurityConfigurerAdapter {
static class MultipleBearerTokenResolverBeansConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -1942,6 +1959,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -1996,12 +2014,12 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class CustomJwtDecoderOnDsl extends WebSecurityConfigurerAdapter {
static class CustomJwtDecoderOnDsl {
JwtDecoder decoder = mock(JwtDecoder.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2010,6 +2028,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.jwt()
.decoder(decoder());
return http.build();
// @formatter:on
}
@ -2021,12 +2040,12 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class CustomJwtDecoderInLambdaOnDsl extends WebSecurityConfigurerAdapter {
static class CustomJwtDecoderInLambdaOnDsl {
JwtDecoder decoder = mock(JwtDecoder.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -2040,6 +2059,7 @@ public class OAuth2ResourceServerConfigurerTests {
.decoder(decoder())
)
);
return http.build();
// @formatter:on
}
@ -2051,10 +2071,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class CustomJwtDecoderAsBean extends WebSecurityConfigurerAdapter {
static class CustomJwtDecoderAsBean {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2062,6 +2082,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -2074,10 +2095,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class JwtAuthenticationManagerConfig extends WebSecurityConfigurerAdapter {
static class JwtAuthenticationManagerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2086,6 +2107,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.jwt()
.authenticationManager(authenticationProvider()::authenticate);
return http.build();
// @formatter:on
}
@ -2098,14 +2120,14 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultAndJwtAuthenticationManagerConfig extends WebSecurityConfigurerAdapter {
static class DefaultAndJwtAuthenticationManagerConfig {
AuthenticationManager defaultAuthenticationManager = mock(AuthenticationManager.class);
AuthenticationManager jwtAuthenticationManager = mock(AuthenticationManager.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authenticationManager(this.defaultAuthenticationManager)
@ -2117,6 +2139,7 @@ public class OAuth2ResourceServerConfigurerTests {
.authenticationManager(this.jwtAuthenticationManager)
)
);
return http.build();
// @formatter:on
}
@ -2132,20 +2155,21 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class CustomJwtValidatorConfig extends WebSecurityConfigurerAdapter {
static class CustomJwtValidatorConfig {
@Autowired
NimbusJwtDecoder jwtDecoder;
private final OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
this.jwtDecoder.setJwtValidator(this.jwtValidator);
// @formatter:off
http
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -2157,13 +2181,13 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class UnexpiredJwtClockSkewConfig extends WebSecurityConfigurerAdapter {
static class UnexpiredJwtClockSkewConfig {
@Autowired
NimbusJwtDecoder jwtDecoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
Clock nearlyAnHourFromTokenExpiry = Clock.fixed(Instant.ofEpochMilli(4687181540000L),
ZoneId.systemDefault());
JwtTimestampValidator jwtValidator = new JwtTimestampValidator(Duration.ofHours(1));
@ -2173,6 +2197,7 @@ public class OAuth2ResourceServerConfigurerTests {
http
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -2180,13 +2205,13 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class ExpiredJwtClockSkewConfig extends WebSecurityConfigurerAdapter {
static class ExpiredJwtClockSkewConfig {
@Autowired
NimbusJwtDecoder jwtDecoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
Clock justOverOneHourAfterExpiry = Clock.fixed(Instant.ofEpochMilli(4687181595000L),
ZoneId.systemDefault());
JwtTimestampValidator jwtValidator = new JwtTimestampValidator(Duration.ofHours(1));
@ -2196,11 +2221,12 @@ public class OAuth2ResourceServerConfigurerTests {
http
.oauth2ResourceServer()
.jwt();
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class SingleKeyConfig extends WebSecurityConfigurerAdapter {
static class SingleKeyConfig {
byte[] spec = Base64.getDecoder().decode(
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoXJ8OyOv/eRnce4akdan" +
"R4KYRfnC2zLV4uYNQpcFn6oHL0dj7D6kxQmsXoYgJV8ZVDn71KGmuLvolxsDncc2" +
@ -2209,8 +2235,9 @@ public class OAuth2ResourceServerConfigurerTests {
"iZCtPzL/IffDUcfhLQteGebhW8A6eUHgpD5A1PQ+JCw/G7UOzZAjjDjtNM2eqm8j" +
"+Ms/gqnm4MiCZ4E+9pDN77CAAPVN7kuX6ejs9KBXpk01z48i9fORYk9u7rAkh1Hu" +
"QwIDAQAB");
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2218,6 +2245,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -2232,10 +2260,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class CustomAuthenticationEventPublisher extends WebSecurityConfigurerAdapter {
static class CustomAuthenticationEventPublisher {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2243,6 +2271,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
// @formatter:on
}
@ -2260,10 +2289,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class OpaqueTokenConfig extends WebSecurityConfigurerAdapter {
static class OpaqueTokenConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2272,6 +2301,7 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.opaqueToken();
return http.build();
// @formatter:on
}
@ -2279,10 +2309,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class OpaqueTokenInLambdaConfig extends WebSecurityConfigurerAdapter {
static class OpaqueTokenInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -2294,6 +2324,7 @@ public class OAuth2ResourceServerConfigurerTests {
oauth2ResourceServer
.opaqueToken(withDefaults())
);
return http.build();
// @formatter:on
}
@ -2301,10 +2332,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class OpaqueTokenAuthenticationManagerConfig extends WebSecurityConfigurerAdapter {
static class OpaqueTokenAuthenticationManagerConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2313,6 +2344,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.opaqueToken()
.authenticationManager(authenticationProvider()::authenticate);
return http.build();
// @formatter:on
}
@ -2325,10 +2357,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class OpaqueTokenAuthenticationManagerInLambdaConfig extends WebSecurityConfigurerAdapter {
static class OpaqueTokenAuthenticationManagerInLambdaConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authorizeRequests) ->
@ -2342,6 +2374,7 @@ public class OAuth2ResourceServerConfigurerTests {
.authenticationManager(authenticationProvider()::authenticate)
)
);
return http.build();
// @formatter:on
}
@ -2354,14 +2387,14 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class DefaultAndOpaqueTokenAuthenticationManagerConfig extends WebSecurityConfigurerAdapter {
static class DefaultAndOpaqueTokenAuthenticationManagerConfig {
AuthenticationManager defaultAuthenticationManager = mock(AuthenticationManager.class);
AuthenticationManager opaqueTokenAuthenticationManager = mock(AuthenticationManager.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authenticationManager(this.defaultAuthenticationManager)
@ -2373,6 +2406,7 @@ public class OAuth2ResourceServerConfigurerTests {
.authenticationManager(this.opaqueTokenAuthenticationManager)
)
);
return http.build();
// @formatter:on
}
@ -2388,16 +2422,17 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class OpaqueAndJwtConfig extends WebSecurityConfigurerAdapter {
static class OpaqueAndJwtConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2ResourceServer()
.jwt()
.and()
.opaqueToken();
return http.build();
// @formatter:on
}
@ -2405,10 +2440,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class OpaqueTokenHalfConfiguredConfig extends WebSecurityConfigurerAdapter {
static class OpaqueTokenHalfConfiguredConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2416,7 +2451,8 @@ public class OAuth2ResourceServerConfigurerTests {
.and()
.oauth2ResourceServer()
.opaqueToken()
.introspectionUri("https://idp.example.com"); // missing credentials
.introspectionUri("https://idp.example.com");
return http.build(); // missing credentials
// @formatter:on
}
@ -2424,13 +2460,13 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class MultipleIssuersConfig extends WebSecurityConfigurerAdapter {
static class MultipleIssuersConfig {
@Autowired
MockWebServer web;
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
String issuerOne = this.web.url("/issuerOne").toString();
String issuerTwo = this.web.url("/issuerTwo").toString();
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver(
@ -2439,6 +2475,7 @@ public class OAuth2ResourceServerConfigurerTests {
http
.oauth2ResourceServer()
.authenticationManagerResolver(authenticationManagerResolver);
return http.build();
// @formatter:on
}
@ -2446,10 +2483,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class AuthenticationManagerResolverPlusOtherConfig extends WebSecurityConfigurerAdapter {
static class AuthenticationManagerResolverPlusOtherConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2458,6 +2495,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.authenticationManagerResolver(mock(AuthenticationManagerResolver.class))
.opaqueToken();
return http.build();
// @formatter:on
}
@ -2465,10 +2503,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Configuration
@EnableWebSecurity
static class OpaqueTokenAuthenticationConverterConfig extends WebSecurityConfigurerAdapter {
static class OpaqueTokenAuthenticationConverterConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
@ -2478,6 +2516,7 @@ public class OAuth2ResourceServerConfigurerTests {
.oauth2ResourceServer()
.opaqueToken()
.authenticationConverter(authenticationConverter());
return http.build();
// @formatter:on
}

View File

@ -47,7 +47,6 @@ import org.springframework.security.authentication.AuthenticationServiceExceptio
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
@ -386,12 +385,12 @@ public class Saml2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
@Import(Saml2LoginConfigBeans.class)
static class Saml2LoginConfigWithCustomAuthenticationManager extends WebSecurityConfigurerAdapter {
static class Saml2LoginConfigWithCustomAuthenticationManager {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.saml2Login().authenticationManager(getAuthenticationManagerMock("ROLE_AUTH_MANAGER"));
super.configure(http);
return http.build();
}
}
@ -399,17 +398,17 @@ public class Saml2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
@Import(Saml2LoginConfigBeans.class)
static class Saml2LoginConfigWithDefaultAndCustomAuthenticationManager extends WebSecurityConfigurerAdapter {
static class Saml2LoginConfigWithDefaultAndCustomAuthenticationManager {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authenticationManager(getAuthenticationManagerMock("DEFAULT_AUTH_MANAGER"))
.saml2Login((saml) -> saml
.authenticationManager(getAuthenticationManagerMock("ROLE_AUTH_MANAGER"))
);
super.configure(http);
return http.build();
// @formatter:on
}
@ -418,15 +417,16 @@ public class Saml2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
@Import(Saml2LoginConfigBeans.class)
static class CustomAuthenticationFailureHandler extends WebSecurityConfigurerAdapter {
static class CustomAuthenticationFailureHandler {
static final AuthenticationFailureHandler authenticationFailureHandler = mock(
AuthenticationFailureHandler.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
.saml2Login((saml2) -> saml2.failureHandler(authenticationFailureHandler));
return http.build();
}
}
@ -498,14 +498,15 @@ public class Saml2LoginConfigurerTests {
@Configuration
@EnableWebSecurity
@Import(Saml2LoginConfigBeans.class)
static class CustomAuthenticationConverter extends WebSecurityConfigurerAdapter {
static class CustomAuthenticationConverter {
static final AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
.saml2Login((saml2) -> saml2.authenticationConverter(authenticationConverter));
return http.build();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -29,7 +29,6 @@ import org.springframework.security.config.annotation.authentication.builders.Au
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.authentication.configuration.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
@ -79,7 +78,7 @@ public class AuthenticationConfigurationGh3935Tests {
@Configuration
@EnableWebSecurity
static class WebSecurity extends WebSecurityConfigurerAdapter {
static class WebSecurity {
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -40,10 +40,10 @@ import org.springframework.security.config.annotation.authentication.builders.Au
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ -150,7 +150,7 @@ public class GrantedAuthorityDefaultsJcTests {
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
static class Config extends WebSecurityConfigurerAdapter {
static class Config {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
@ -161,12 +161,13 @@ public class GrantedAuthorityDefaultsJcTests {
// @formatter:on
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().access("hasRole('USER')");
return http.build();
// @formatter:on
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -34,8 +34,8 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
@ -112,14 +112,15 @@ public class CustomHttpSecurityConfigurerTests {
@Configuration
@EnableWebSecurity
static class Config extends WebSecurityConfigurerAdapter {
static class Config {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.apply(CustomConfigurer.customConfigurer())
.loginPage("/custom");
return http.build();
// @formatter:on
}
@ -137,10 +138,10 @@ public class CustomHttpSecurityConfigurerTests {
@Configuration
@EnableWebSecurity
static class ConfigCustomize extends WebSecurityConfigurerAdapter {
static class ConfigCustomize {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.apply(CustomConfigurer.customConfigurer())
@ -148,6 +149,7 @@ public class CustomHttpSecurityConfigurerTests {
.csrf().disable()
.formLogin()
.loginPage("/other");
return http.build();
// @formatter:on
}

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