本文主要是介绍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
可通过自定义AuthenticationManager
和默认AuthenticationManager
设置
自定义AuthenticationManager
public GetRequestAuthenticationFilter testFilter(){GetRequestAuthenticationFilter filter = new GetRequestAuthenticationFilter();filter.setAuthenticationManager(new ProviderManager(Arrays.asList(new AuthenticationProvider() {@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {if ("admin".equals(authentication.getPrincipal()) && "123456".equals(authentication.getCredentials())) {List<GrantedAuthority> 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("账号密码错误");}}@Overridepublic boolean supports(Class<?> aClass) {return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);}})));return filter;
}
默认ProviderManager
GetRequestAuthenticationFilter filter = new GetRequestAuthenticationFilter();
filter.setAuthenticationManager(super.authenticationManager());
这篇关于Spring Security 自定义身份认证过滤器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!