Java Spring Boot/Spring Security基于路径在多个身份验证提供程序之间进行选择

Java Spring Boot/Spring Security基于路径在多个身份验证提供程序之间进行选择,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,我已将我的应用程序配置为: 我有两个身份验证提供程序(provider1和provider2),我希望将它们用于不同的端点: @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/api/v1").authenticated(); http.authorizeRequests().antMatchers("/ap

我已将我的应用程序配置为:

我有两个身份验证提供程序(provider1和provider2),我希望将它们用于不同的端点:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/api/v1").authenticated();
    http.authorizeRequests().antMatchers("/api/v2").authenticated();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(provider1);
    auth.authenticationProvider(provider2);
}
现在发生的情况是,如果调用
/api/v2
provider1
,如果不引发异常或返回false,则只调用
provider2

// In org.springframework.security.authentication.ProviderManager

for (AuthenticationProvider provider : getProviders()) {
        try {
            result = provider.authenticate(authentication);

            if (result != null) {
                copyDetails(authentication, result);
                break;
            }
        }
        ...
        ...
}
当我点击
/api/v2
时,如何使只有
provider2
被调用

大概是这样的:

http.authorizeRequests().antMatchers("/api/v2")
    .authenticated().authenticationProvider(provider2);

(我知道在
HttpSecurity
上有一个
authenticationProvider
,但是,这与调用
AuthenticationManagerBuilder#authenticationProvider
完全相同)

您可以向Spring安全筛选器链添加一个自定义筛选器,该筛选器链尝试使用自定义实现对请求进行授权。调用时,可以传入自定义身份验证的实例。然后确保更新自定义提供程序的supports(Class<?>authentication)方法,使其仅接受自定义身份验证类

然后,可以使用antmatchers将自定义筛选器应用于特定端点的安全筛选器链

下面是一个例子。