繁体   English   中英

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

[英]Spring Boot/Spring Security Choose Between Multiple Authentication Providers Based On Path

我已经这样配置了我的应用程序:

我有两个身份验证提供程序(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 Security过滤器链中添加一个定制过滤器,以尝试使用定制Authentication实现授权请求。 调用AuthenticationManager.authenticate()时 ,可以传入自定义Authentication的实例。 然后,确保您更新自定义提供程序的supports(Class <?> authentication)方法以仅接受您的自定义身份验证类。

然后,您可以使用antmatchers将自定义过滤器应用于特定端点的安全过滤器链。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM