springboot + security 自定义登陆校验Filter
默认的登陆校验Filter是UsernamePasswordAuthenticationFilter,实现顺序是 AbstractAuthenticationProcessingFilter.doFilter->UsernamePasswordAuthenticationFilter.attemptAuthentication->ProviderManager.authenticate->AbstractUserDetailsAuthenticationProvider.authenticate->DaoAuthenticationProvider.retrieveUser->自定义的UserDetailsService.loadUserByUsername 这里在自定义的UserDetailsService里按username取出user,security会去给你判断密码是否相等。
因为业务需求,需要在登录前进入业务逻辑的判断,所以这里自定义Filter
public class OpenIdAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
@Autowired
private RefactorSysUserService sysUserService;
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
//业务逻辑
}
在securityConfig配置,感兴趣的可以去看看这个类FilterComparator,里面有个Map
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilter(openIdAuthenticationFilter());
}
/**
* 自定义登陆验证接口
*/
public OpenIdAuthenticationFilter openIdAuthenticationFilter() throws Exception {
OpenIdAuthenticationFilter openIdAuthenticationFilter = new OpenIdAuthenticationFilter();
openIdAuthenticationFilter.setAuthenticationManager(authenticationManager());
//只有post请求才拦截
openIdAuthenticationFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
openIdAuthenticationFilter.setAuthenticationSuccessHandler(securityAuthenticationSuccessHandler);
openIdAuthenticationFilter.setAuthenticationFailureHandler(securityAuthenticationFailureHandler);
return openIdAuthenticationFilter;
}
