众所周知,在 Spring Security 5.7.0-M2 中,弃用了 WebSecurityConfigurerAdapter,Spring 鼓励用户转向基于组件的安全配置。
以前完成token验证的方法基本上都是JWT的,但是现在我们改用了最新的技术之后,JWT就无法实现接口了,所以我就没法使用。
下图是最新的拦截器功能实现。但没法与老版本的的JWT相互配合。有没有人知道改了新版本之后,要怎么处理老版本的JWT代码
或者是说直接弃用。
public class SpringSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(authorize-> {
try {
authorize
// 放行登录接口
.requestMatchers(AUTH_WHITELIST).permitAll()
// 放行资源目录
// .requestMatchers("/static/**", "/resources/**").permitAll()
// 其余的都需要权限校验
.anyRequest().authenticated()
// 防跨站请求伪造
.and().csrf(csrf -> csrf.disable());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
).build();
}
}
@Bean
public JwtAuthenticationProvider jwtAuthenticationProvider() {
return new JwtAuthenticationProvider(jwtDecoder());
}
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(publicKey).build();
}
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtDecoder jwtDecoder;
public JwtAuthenticationFilter(JwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
String jwt = authorizationHeader.substring(7);
Jwt jwtToken = jwtDecoder.decode(jwt);
JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken(jwtToken);
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
filterChain.doFilter(request, response);
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new JwtAuthenticationFilter(jwtDecoder()), UsernamePasswordAuthenticationFilter.class);
}
替代方案
https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter
还想使用JWT,可以用Spring Security的JwtAuthenticationToken类来实现,这个类是一个Authentication的实现,可以在Spring Security中使用
如果如果你还想用WebSecurityConfigurerAdapter,用Spring Security 5.6.x版本
整合JWT一共会使用 6个配置文件+各自的用户和权限文件(这里使用了5个表)
以上是会用到的文件除单文件外均使用红色框选出来,可以同下述文章对比查看