Spring Security without the WebSecurityConfigurerAdapter
In Spring Security 5.7.0-M2 we deprecated the WebSecurityConfigurerAdapter
, as we encourage users to move towards a component-based security configuration.
To assist with the transition to this new style of configuration, we have compiled a list of common use-cases and the suggested alternatives going forward.
In the examples below we follow best practice by using the Spring Security lambda DSL and the method HttpSecurity#authorizeHttpRequests
to define our authorization rules. If you are new to the lambda DSL you can read about it in this blog post. If you would like to learn more about why we choose to use HttpSecurity#authorizeHttpRequests
you can check out the reference documentation.
Configuring HttpSecurity
In Spring Security 5.4 we introduced the ability to configure HttpSecurity
by creating a SecurityFilterChain
bean.
Below is an example configuration using the WebSecurityConfigurerAdapter
that secures all endpoints with HTTP Basic:
COPY@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
}
}
Going forward, the recommended way of doing this is registering a SecurityFilterChain
bean:
COPY@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
return http.build();
}
}
Configuring WebSecurity
In Spring Security 5.4 we also introduced the WebSecurityCustomizer
.
The WebSecurityCustomizer
is a callback interface that can be used to customize WebSecurity
.
Below is an example configuration using the WebSecurityConfigurerAdapter
that ignores requests that match /ignore1
or /ignore2
:
COPY@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/ignore1", "/ignore2");
}
}
Going forward, the recommended way of doing this is registering a WebSecurityCustomizer
bean:
COPY@Configuration
public class SecurityConfiguration {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
}
}
WARNING: If you are configuring WebSecurity
to ignore requests, consider using permitAll
via HttpSecurity#authorizeHttpRequests instead. See the configure
Javadoc for additional details.
LDAP Authentication
In Spring Security 5.7 we introduced the EmbeddedLdapServerContextSourceFactoryBean
, LdapBindAuthenticationManagerFactory
and LdapPasswordComparisonAuthenticationManagerFactory
which can be used to create an embedded LDAP Server and an AuthenticationManager
that performs LDAP authentication.
Below is an example configuration using WebSecurityConfigurerAdapter
the that creates an embedded LDAP server and an AuthenticationManager
that performs LDAP authentication using bind authentication:
COPY@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDetailsContextMapper(new PersonContextMapper())
.userDnPatterns("uid={0},ou=people")
.contextSource()
.port(0);
}
}
Going forward, the recommended way of doing this is using the new LDAP classes:
COPY@Configuration
public class SecurityConfiguration {
@Bean
public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean =
EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();
contextSourceFactoryBean.setPort(0);
return contextSourceFactoryBean;
}
@Bean
AuthenticationManager ldapAuthenticationManager(
BaseLdapPathContextSource contextSource) {
LdapBindAuthenticationManagerFactory factory =
new LdapBindAuthenticationManagerFactory(contextSource);
factory.setUserDnPatterns("uid={0},ou=people");
factory.setUserDetailsContextMapper(new PersonContextMapper());
return factory.createAuthenticationManager();
}
}
JDBC Authentication
Below is an example configuration using the WebSecurityConfigurerAdapter
with an embedded DataSource
that is initialized with the default schema and has a single user:
COPY@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.build();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
auth.jdbcAuthentication()
.withDefaultSchema()
.dataSource(dataSource())
.withUser(user);
}
}
The recommended way of doing this is registering a JdbcUserDetailsManager
bean:
COPY@Configuration
public class SecurityConfiguration {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript(JdbcDaoImpl.DEFAULT_USER_SCHEMA_DDL_LOCATION)
.build();
}
@Bean
public UserDetailsManager users(DataSource dataSource) {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource);
users.createUser(user);
return users;
}
}
Note: In these examples, we use the method User.withDefaultPasswordEncoder()
for readability. It is not intended for production and instead we recommend hashing your passwords externally. One way to do that is to use the Spring Boot CLI as described in the reference documentation.
In-Memory Authentication
Below is an example configuration using the WebSecurityConfigurerAdapter
that configures an in-memory user store with a single user:
COPY@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
auth.inMemoryAuthentication()
.withUser(user);
}
}
The recommended way of doing this is registering an InMemoryUserDetailsManager
bean:
COPY@Configuration
public class SecurityConfiguration {
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
Note: In these examples, we use the method User.withDefaultPasswordEncoder()
for readability. It is not intended for production and instead we recommend hashing your passwords externally. One way to do that is to use the Spring Boot CLI as described in the reference documentation.
Global AuthenticationManager
To create an AuthenticationManager
that is available to the entire application you can simply register the AuthenticationManager
as a @Bean
.
This type of configuration is shown above in the LDAP Authentication example.
Local AuthenticationManager
In Spring Security 5.6 we introduced the method HttpSecurity#authenticationManager that overrides the default AuthenticationManager
for a specific SecurityFilterChain
. Below is an example configuration that sets a custom AuthenticationManager
as the default:
COPY@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated()
)
.httpBasic(withDefaults())
.authenticationManager(new CustomAuthenticationManager());
return http.build();
}
}
Accessing the local AuthenticationManager
The local AuthenticationManager
can be accessed in a custom DSL. This is actually how Spring Security internally implements methods like HttpSecurity.authorizeRequests()
.
COPYpublic class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {
@Override
public void configure(HttpSecurity http) throws Exception {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
http.addFilter(new CustomFilter(authenticationManager));
}
public static MyCustomDsl customDsl() {
return new MyCustomDsl();
}
}
The custom DSL can then be applied when building the SecurityFilterChain
:
COPY@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// ...
http.apply(customDsl());
return http.build();
}
Getting Involved
We are excited to share these updates with you and we look forward to further enhancing Spring Security with your feedback! If you are interested in contributing, you can find us on GitHub.
https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2019-12-22 java.sql.SQLException: connection holder is null
2016-12-22 Basic认证
2016-12-22 mysql及redis环境部署时遇到的问题解决
2016-12-22 Formatting Domain Names--域名可以由哪些字符串组成
2016-12-22 Using RestTemplate, how to send the request to a proxy first so I can use my junits with JMeter?
2014-12-22 用PowerMockito来mock私有方法(转)
2014-12-22 Mockito简介(转)