如何在运行时切换安全模型以便
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或其他)
(灵感来自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(..)
之间有什么区别?
答案 0 :(得分:1)
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
的某种机制。