springboot + security 自定义登陆校验Filter

2022-08-07 09:39:30

默认的登陆校验Filter是UsernamePasswordAuthenticationFilter,实现顺序是
AbstractAuthenticationProcessingFilter.doFilter->UsernamePasswordAuthenticationFilter.attemptAuthentication->ProviderManager.authenticate->AbstractUserDetailsAuthenticationProvider.authenticate->DaoAuthenticationProvider.retrieveUser->自定义的UserDetailsService.loadUserByUsername
这里在自定义的UserDetailsService里按username取出user,security会去给你判断密码是否相等。

因为业务需求,需要在登录前进入业务逻辑的判断,所以这里自定义Filter

publicclassOpenIdAuthenticationFilterextendsUsernamePasswordAuthenticationFilter{@Autowiredprivate RefactorSysUserService sysUserService;@Overridepublic AuthenticationattemptAuthentication(HttpServletRequest request,
                                              HttpServletResponse response)throws AuthenticationException {//业务逻辑
}

在securityConfig配置,感兴趣的可以去看看这个类FilterComparator,里面有个Map

@Overrideprotectedvoidconfigure(HttpSecurity http)throws Exception {
    http.addFilter(openIdAuthenticationFilter());
  }/**
   * 自定义登陆验证接口
   */public OpenIdAuthenticationFilteropenIdAuthenticationFilter()throws Exception {
    OpenIdAuthenticationFilter openIdAuthenticationFilter =new OpenIdAuthenticationFilter();
    openIdAuthenticationFilter.setAuthenticationManager(authenticationManager());//只有post请求才拦截
    openIdAuthenticationFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login","POST"));
    openIdAuthenticationFilter.setAuthenticationSuccessHandler(securityAuthenticationSuccessHandler);
    openIdAuthenticationFilter.setAuthenticationFailureHandler(securityAuthenticationFailureHandler);return openIdAuthenticationFilter;
  }
  • 作者:米兰的老油条
  • 原文链接:https://blog.csdn.net/mushuntaosama/article/details/78904863
    更新时间:2022-08-07 09:39:30