如何切换的安全模型在运行时,以便如何使用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(..)
之间的区别?