在仿造用表单登录认证流程时,得知道这个流程中经过了哪些类,并且哪些类是重要的?不记得的童鞋再去回顾下捋一遍登录Spring Security登录流程(源码篇)这篇文章,详细的介绍了表单登录认证的整个流程。如下图:
1、IpAuthenticationToken
该AuthenticationToken仿造UsernamePasswordAuthenticationToken,同样继承自AbstractAuthenticationToken,然后添加一个ip属性,让getPrincipal方法返回ip,然后仿造UsernamePasswordAuthenticationToken增加两个构造方法,一个是未认证的token,一个是认证成功的token,这两个构造方法在认证过程中会被用到。
public class IpAuthenticationToken extends AbstractAuthenticationToken {private final String ip;public IpAuthenticationToken(String ip) {super(null);this.ip = ip;this.setAuthenticated(false);}public IpAuthenticationToken(String ip, Collection<? extends GrantedAuthority> authorities) {super(authorities);this.ip = ip;super.setAuthenticated(true);}@Overridepublic Object getCredentials() {return null;}@Overridepublic Object getPrincipal() {return ip;}}
2、IpAuthenticationFilter
该过滤器仿造UsernamePasswordAuthenticationFilter过滤器,也继承自AbstractAuthenticationProcessingFilter,不过需要拦截的请求地址变成/api/auth/ip-login,然后也要像UsernamePasswordAuthenticationFilter过滤器一样重写父类的attemptAuthentication方法,new一个IpAuthenticationToken对象交给ProviderManager中的Providers集合去认证,我们知道,一个Provider只能认证一个AuthenticationToken对象,那么这个时候问题来了,能够认证IpAuthenticationToken对象还并不存在,所以,我们还得仿造DaoAuthenticationProvider去写一个IpAuthenticationProvider类。
@Slf4jpublic class IpAuthenticationFilter extends AbstractAuthenticationProcessingFilter {private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER =new AntPathRequestMatcher(SecurityConstant.IP_LOGIN_PROCESSING_URL, "POST");private boolean postOnly = true;public IpAuthenticationFilter() {super(DEFAULT_ANT_PATH_REQUEST_MATCHER);}@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {if (this.postOnly && !request.getMethod().equals("POST")) {throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());} else {String ip = request.getRemoteHost();log.info(String.format("当前登录用户ip地址为%s", ip));IpAuthenticationToken authRequest = new IpAuthenticationToken(ip);return this.getAuthenticationManager().authenticate(authRequest);}}}
3、IpAuthenticationProvider
该认证类方法仿造DaoAuthenticationProvider类,同样实现AuthenticationProvider接口,实现接口中的authenticate和supports方法,让该认证类只对IpAuthenticationToken生效,然后在认证过程中,DaoAuthenticationProvider会去调用UserDetailsService接口去数据库或内存中拿取用户,然后判断加密后密码是否匹配等等校验,而IpAuthenticationProvider的认证逻辑有点不同,只需要判断当前登录用户的ip地址是否在白名单中,这个白名单当前简单点,直接在内存中写死,如果以后有需要,可以类似UserDetailsService一样从数据库中读取,如果当前用户的ip地址是在白名单中,那么返回一个认证成功的IpAuthenticataionToken,否则返回null。
@Componentpublic class IpAuthenticationProvider implements AuthenticationProvider, MessageSourceAware {protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();private static final Map<String, SimpleGrantedAuthority> ipAuthorityMap =new ConcurrentHashMap<>();static {ipAuthorityMap.put("127.0.0.1", new SimpleGrantedAuthority("ADMIN"));}@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {Assert.isInstanceOf(IpAuthenticationToken.class,authentication,() ->this.messages.getMessage("IpAuthenticationProvider.onlySupports","Only IpAuthenticationToken is supported"));String ip = (String) authentication.getPrincipal();if (ipAuthorityMap.containsKey(ip)) {return new IpAuthenticationToken(ip, Collections.singletonList(ipAuthorityMap.get(ip)));}return null;}@Overridepublic boolean supports(Class<?> authentication) {return IpAuthenticationToken.class.isAssignableFrom(authentication);}@Overridepublic void setMessageSource(MessageSource messageSource) {this.messages = new MessageSourceAccessor(messageSource);}}
4、IpLoginConfigurer
看完Spring Security 初始化流程梳理(源码篇二)🎁这篇文章的童鞋应该知道,一条过滤器链是怎么产生的?遍历HttpSecurity中的configurers集合,对每一个configurer配置类进行init和configure方法,这样就将配置好的过滤器添加到HttpSecurity#filters集合中,然后HttpSecurity再执行performBuild方法使用filters集合构建出一条过滤器链。所以在这里我们得仿造FormLoginConfigurer编写一个IpLoginConfigurer,继承自SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>,重写其中的configure方法,在configure方法中需要将IpLoginFilter添加到HttpSecurity#filters集合中。
@Component@RequiredArgsConstructorpublic class IpLoginConfigurerextends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {private final MyAuthenticationSuccessHandler authenticationSuccessHandler;private final MyAuthenticationFailureHandler authenticationFailureHandler;private final IpAuthenticationProvider ipAuthenticationProvider;@Overridepublic void init(HttpSecurity http) {http.authenticationProvider(postProcess(new IpAuthenticationProvider()));}@Overridepublic void configure(HttpSecurity http) {IpAuthenticationFilter ipAuthenticationFilter = new IpAuthenticationFilter();ipAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));ipAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);ipAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);http.addFilterBefore(ipAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);}}
一定得记住将ipAuthenticationProvider通过HttpSecurity对象添加到ProviderManager中的providers属性中,否则在后面认证过程中会应找不到ipAuthenticationProvider而认证不了。
:::warning
🤔我将http.authenticationProvider(ipAuthenticationProvider)写在configure方法中居然也可以?这个地方我还没搞懂为什么???正确的添加时机应该是init方法的时候,因为在HttpSecurity中的beforeConfigure中就已经将AuthenticationManager对象构建出来了。所以我没看懂为什么在configure方法中添加ipAuthenticationProvider也可以,但是是添加到了父AuthenticationManager对象中的providers集合中,搞不懂?
:::
@Overrideprotected void beforeConfigure() throws Exception {if (this.authenticationManager != null) {setSharedObject(AuthenticationManager.class, this.authenticationManager);}else {setSharedObject(AuthenticationManager.class, getAuthenticationRegistry().build());}}
5、小结
对比Spring Security默认的表单登录认证,使用Ip认证登录需要对照增加的类:
- UsernamePasswordAuthenticationToken -> IpAuthenticationToken
- UsernamePasswordAuthenticationFilter -> IpAuthenticationFilter
- DaoAuthenticationProvider -> IpAuthenticationProvider
- UserDetailService -> ConcurrentHashMap
- FormLoginConfigurer -> IpLoginConfigurer
后续使用短信登录或者第三方登录的时候也可以按照这个思路进行扩展,加油!🥳
