首页 > 解决方案 > 每个 url 模式的身份验证提供程序 - Spring Boot

问题描述


在使用 Spring Boot 安全性为每个 url 模式配置不同的身份验证提供程序时,我遇到了问题。我正在尝试在 Spring Boot 应用程序中配置安全性,并希望在基本身份验证之后大摇大摆,并且所有 API 仅由令牌保护。我几乎可以使用它,但注意到 API 除了它由 IDAuthProvider 类验证的令牌保护之外,它还由基本身份验证保护。我不希望这样,并且还注意到如果我删除了 line: sessionCreationPolicy(SessionCreationPolicy.STATELESS). 它似乎工作正常,但仍然在请求中添加了标头 Basic {token} 这是我不想要的......
你知道我该如何配置它使所有由基本身份验证保护的东西和由令牌保护的API东西保护的所有东西?

我的配置如下所示:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Configuration
    @Order(1)
    public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {
        private final AuthenticationProvider userPassAuthProvider;

        @Autowired
        SwaggerSecurityConfig(UserPassAuthProvider userPassAuthProvider) {
            this.userPassAuthProvider = userPassAuthProvider;
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/swagger**").
                    authorizeRequests().
                    antMatchers("/swagger**").authenticated().
                    and().httpBasic().and().csrf().disable();
        }

        @Override
        public void configure(AuthenticationManagerBuilder auth)
                throws Exception {
            auth.authenticationProvider(userPassAuthProvider);
        }
    }

    @Configuration
    @Order(2)
    public class APISecurityConfig extends WebSecurityConfigurerAdapter {
        private final AuthenticationProvider idAuthProvider;

        @Autowired
        APISecurityConfig(IDAuthProvider idAuthProvider) {
            this.idAuthProvider = idAuthProvider;
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/v1/**").
                    authorizeRequests().anyRequest().authenticated().
                    and().
                    addFilterBefore(idpAuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class).sessionManagement().
                    and().
                    csrf().disable();
        }

        @Override
        public void configure(AuthenticationManagerBuilder auth)
                throws Exception {
            auth.authenticationProvider(idAuthProvider);
        }

        IDPAuthenticationFilter idpAuthenticationFilter(AuthenticationManager auth) {
            return new IDPAuthenticationFilter(auth, new OrRequestMatcher(new AntPathRequestMatcher(ApiRouter.API_PATH + "/**", HttpMethod.GET.toString()), new AntPathRequestMatcher(ApiRouter.API_PATH + "/**", HttpMethod.POST.toString()), new AntPathRequestMatcher(ApiRouter.API_PATH + "/**", HttpMethod.DELETE.toString()),  new AntPathRequestMatcher("/swagger**", HttpMethod.GET.toString())));
        }
    }
}

标签: spring-bootspring-security

解决方案


推荐阅读