![](/img/trans.png)
[英]How to dynamically switch application context in Spring Security?
[英]How to switch security model in runtime with spring security?
如何在運行時切換安全模型,以便
Authentication
,並且 Authentication
我認為我已經解決了(2),但不能完全弄清(1) 。
Spring Security配置
@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或其他)
(受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(..)
之間有什么區別?
它出現的Filter
負責創建Authentication
(不知道別的太)。
以AnonymousAuthenticationFilter
為例
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
if (SecurityContextHolder.getContext().getAuthentication() == null) {
SecurityContextHolder.getContext().setAuthentication(
createAuthentication((HttpServletRequest) req));
}
類似,我認為SwitchingFilter
應該類似於SwitchingAuthenticationProvider
public class SwitchingFilter extends GenericFilterBean {
private Filter[] filters = // ...
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
filters[i].doFilter(request, response, chain);
// do filterChain.doFilter(request, response); ??
}
}
..用於選擇合適索引i
某種機制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.