我们可以在 Spring Boot 的单个模块中定义 Bearer token 身份验证和 Basic 身份验证吗?

Yas*_*ant 6 spring spring-mvc spring-security spring-boot

我有一个要求,我有一个控制器只需要基本身份验证,而其他控制器需要通过承载令牌进行身份验证。是否可以在 Spring Boot 应用程序的单个模块中实现这两种安全?WebSecurityConfigurerAdapter如果是,我应该如何在、filters、 等中定义它?

Mor*_*itz 5

是的,这是可能的。

您基本上会实现两个不同的WebSecurityConfigurerAdapters,每个配置自己的HttpSecurity对象,并且每个都应用于应用程序的不同请求集。看一下下面的安全配置示例:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    private static final RequestMatcher BASIC_REQUESTS = new AntPathRequestMatcher("/api/basic/**");

    private static final RequestMatcher BEARER_REQUESTS = new NegatedRequestMatcher(BASIC_REQUESTS);

    @Configuration
    @Order(1)
    public static class BasicAuthSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatcher(BASIC_REQUESTS).authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .httpBasic()
                    ...
        }
    }

    @Configuration
    @Order(2)
    public static class BearerAuthSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatcher(BEARER_REQUESTS).authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .addFilter(...)
                    ...
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

这告诉 Spring 使用基本身份验证方案处理/api/basic/**与路径匹配的所有请求,以及使用例如执行某些承载身份验证的自定义过滤器链的所有其他请求。使 Spring仅对与给定请求匹配器匹配的请求HttpSecurity.requestMatcher(...)应用配置。

请注意,您必须手动设置 s 的顺序WebSecurityConfigurerAdapter,否则 Spring 会尝试使用默认优先级初始化两个 bean,这将导致冲突。