我们可以在Spring Boot的单个模块中定义承载令牌身份验证和基本身份验证吗?

我们可以在Spring Boot的单个模块中定义承载令牌身份验证和基本身份验证吗?,spring,spring-boot,spring-mvc,spring-security,Spring,Spring Boot,Spring Mvc,Spring Security,我有一个要求,我有一个只需要基本身份验证的控制器,而其他控制器需要通过承载令牌进行身份验证。在Spring Boot应用程序的单个模块中是否可以实现这两种安全性?如果是,我应该如何在websecurityConfigureAdapter、过滤器等中定义它?是,这是可能的 基本上,您将实现两个不同的websecurityConfigureAdapters,每个都配置自己的HttpSecurity对象,并分别应用于应用程序的不同请求集。请查看以下安全配置示例: @Configuration @Ena

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

是,这是可能的

基本上,您将实现两个不同的
websecurityConfigureAdapter
s,每个都配置自己的
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(...)
                    ...
        }
    }

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

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