在Spring Security 5中,WebSecurityConfigurerAdapter已被弃用,可以使用更简单的方式配置安全性。可以使用@EnableWebSecurity注释以及实现WebSecurityConfigurer接口来配置安全性。示例代码如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig implements WebSecurityConfigurer {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/secure/**").authenticated().and().formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER");
}
}
其中,configure(HttpSecurity http)方法用于配置请求授权,configure(AuthenticationManagerBuilder auth)方法用于配置用户身份验证。使用@EnableWebSecurity注释启用Web安全性。