首页 > 解决方案 > 如何与请求过滤器共享 WebSecurityConfigurerAdapter 中的 HttpSecurity?

问题描述

我有一个 Spring Boot 应用程序,我在其中配置了 REST 安全性,其中 JWT 身份验证覆盖了

protected void configure(HttpSecurity httpSecurity) throws Exception {

我的配置类中的方法:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // ...

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
        .csrf().disable()
        // ...
        .authorizeRequests()
        // ...
        .antMatchers("/api/authentication/login").permitAll()
        .antMatchers("/api/assets/*/processed-data/csv").permitAll()
        // ...
        .antMatchers("/api/**").authenticated()
        // ...

由于某些路径需要身份验证,而其他路径不需要,我想在相应的 JWT 令牌验证过滤器中配对该配置,我实际上列出了每个子路径:

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    // ...
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if(request.getRequestURI().startsWith("/api/authentication/")) {
            // ...

HttpSecurity不是 bean,所以我不能自动装配它。我能做些什么?我应该让我的WebSecurityConfig类成为一个 bean 并添加一个getHttpSecurity()方法吗?有没有更清洁的方法?还是根本不推荐这种方法?

标签: javaspringspring-bootspring-security

解决方案


推荐阅读