Spring Security 自定义身份认证过滤器

概述 我们可以通过集成AbstractAuthenticationProcessingFilter或者现有的过滤器来完成自定义的身份认证过滤器
身份验证过滤器的主要责任是何时进行身份认证以及如何进行身份认证等
实现案例 以下是实现案例,可根据需求进行拓展和剔除
1. 继承AbstractAuthenticationProcessingFilter

public class GetRequestAuthenticationFilter extends AbstractAuthenticationProcessingFilter { }

2. 重写attemptAuthentication()方法
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (request.getMethod().toUpperCase().equals("GET")) { // 创建身份认证对象 UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("test", "test"); // 设置细节信息 token.setDetails(new WebAuthenticationDetails(request)); // 将身份认证对象交给身份认证管理器进行身份认证 return this.getAuthenticationManager().authenticate(token); } return null; }

3. 为Filter设置AuthenticationManager 【Spring Security 自定义身份认证过滤器】可通过自定义AuthenticationManager和默认AuthenticationManager设置
自定义AuthenticationManager
public GetRequestAuthenticationFilter testFilter(){ GetRequestAuthenticationFilter filter = new GetRequestAuthenticationFilter(); filter.setAuthenticationManager(new ProviderManager(Arrays.asList(new AuthenticationProvider() { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if ("admin".equals(authentication.getPrincipal()) && "123456".equals(authentication.getCredentials())) { List grantedAuthorities = Arrays.asList(new SimpleGrantedAuthority("admin")); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getAuthorities(), grantedAuthorities); token.setDetails(authentication.getDetails()); return token; }else{ throw new BadCredentialsException("账号密码错误"); } }@Override public boolean supports(Class aClass) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass); } }))); return filter; }

默认ProviderManager
GetRequestAuthenticationFilter filter = new GetRequestAuthenticationFilter(); filter.setAuthenticationManager(super.authenticationManager());

    推荐阅读