WebSecurityConfigurerAdapter 过时了怎么办
时间: 2023-10-26 15:16:45 浏览: 33
如果你使用的是 Spring Boot 2.4 或者更高版本,那么 WebSecurityConfigurerAdapter 已经过时了。相应的,你可以使用实现 WebSecurityConfigurer 接口的方式来进行配置。具体步骤如下:
1. 创建一个类,实现 WebSecurityConfigurer 接口。
2. 在该类中覆盖 configure(HttpSecurity http) 方法,对安全配置进行定制。
3. 如果需要,可以覆盖 configure(AuthenticationManagerBuilder auth) 方法,用于配置身份验证管理器。
下面是一个示例代码:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig implements WebSecurityConfigurer {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER");
}
}
```
在上述示例中,我们通过实现 WebSecurityConfigurer 接口来配置安全。在 configure(HttpSecurity http) 方法中,我们首先允许所有用户访问 /public/** 下的资源,然后要求任何其他请求都需要进行身份验证。接着,我们配置了表单登录,并指定了登录页面为 /login。最后,我们允许所有用户注销。
在 configure(AuthenticationManagerBuilder auth) 方法中,我们使用内存中的用户进行身份验证。在这个示例中,我们创建了一个用户,用户名为 user,密码为 password,角色为 USER。
注意,如果你已经使用了 WebSecurityConfigurerAdapter,你可以继续使用它。不过,建议使用新的方式进行配置,以便更好地支持未来的版本。