如何切換的安全模型在運行時,以便如何使用spring安全性在運行時切換安全模型?
- 現有春季安全組件可以產生
Authentication
,並 - 現有春季安全組件可以驗證
Authentication
我想我解決(2),但不能完全弄清楚(1)。
春季安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").authenticated().and()
.addFilterBefore(switchingFilter);
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(switchingAuthenticationProvider);
}
@Bean
public SwitchingAuthenticationProvider switchingAuthenticationProvider() {
return new SwitchingAuthenticationProvider();
}
@Bean
public SwitchingFilter switchingFilter() {
return new SwitchingFilter();
}
}
SwitchingAuthenticationProvider
的是直截了當:簡單地委派給某一其它AuthenticationProvder
(即,LDAP/OAuth2用戶或以其它方式)
(由Switching authentication approaches at runtime with Spring Security啓發)。
public class SwitchingAuthenticationProvider implements AuthenticationProvider {
private AuthenticationProvider[] authProviders = // ...
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return authProvider[i].authenticate(authentication);
}
}
但是什麼創造了Authentication
?據我所知,一個選項是讓GenericFilterBean
創建Authentication
,如下圖所示。
public class SwitchingFilter extends GenericFilterBean {
private AuthProviderService authProviders = // ...
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Authentication authentication = authProviders.getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
SecurityContextHolder.getContext().setAuthentication(null);
}
}
...其中一個AuthProviderService
會委託的東西,創建authentication
。但是,我怎樣才能使用例如相當於HttpSecurity#httpBasic()
或HttpSecurity#openIdLogin()
的插件呢?
獎金的問題:什麼是HttpSecurity#authenticationProvider(..)
和AuthenticationManagerBuilder.authenticationProvider(..)
之間的區別?