标题最新的 Spring Security 5.7 版本,还是更新了不少内容,之前的 WebSecurityConfigurerAdapter 已经被废弃了,大家在使用的时候,可以参考下面的配置文件。
不需要再去重写 configure() 方法,直接通过 filterChain() 方法就能使用 HttpSecurity 来配置相关信息。
官方参考文档中,就也写得非常明白了,供参考:Spring Security without the WebSecurityConfigurerAdapter
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.config.annotation.authentication.configuration.AuthenticationConfiguration;
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.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity // 添加 security 过滤器
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级别的权限认证
public class SpringSecurityConfig {
@Autowired
private XxxUserService xxxUserService;
// 权限不足错误信息处理,包含认证错误与鉴权错误处理
@Autowired
private JwtAuthError jwtAuthError;
// jwt 校验过滤器,从 http 头部 Authorization 字段读取 token 并校验
@Bean
public JwtAuthFilter authFilter() throws Exception {
return new JwtAuthFilter();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
// 基于 token,不需要 csrf
.csrf().disable()
// 基于 token,不需要 session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 设置 jwtAuthError 处理认证失败、鉴权失败
.exceptionHandling().authenticationEntryPoint(jwtAuthError).accessDeniedHandler(jwtAuthError).and()
// 下面开始设置权限
.authorizeRequests(authorize -> authorize
// 请求放开
.antMatchers("
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}