![](/img/trans.png)
[英]Spring security with multiple authentication providers - UsernameNotFoundException
[英]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.