我已将我的应用程序配置为:
我有两个身份验证提供程序(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;
}
}
...
...
}
我怎样才能做到只有
provider2
当我点击 /api/v2
时被调用?像这样的东西:
http.authorizeRequests().antMatchers("/api/v2")
.authenticated().authenticationProvider(provider2);
(我知道
authenticationProvider
上有 HttpSecurity
,但是,这与调用 AuthenticationManagerBuilder#authenticationProvider
完全相同)
最佳答案
您可以向 Spring Security 过滤器链添加一个自定义过滤器,该过滤器尝试使用自定义 Authentication 授权请求。执行。当您调用 AuthenticationManager.authenticate() ,您可以传入自定义身份验证的实例。然后确保您更新了您的自定义提供程序的 supports(Class> authentication) 方法以仅接受您的自定义身份验证类。
然后,您可以使用 antmatchers 将自定义过滤器应用于特定端点的安全过滤器链。
关于java - Spring Boot/Spring Security 根据路径在多个认证提供者之间进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078836/