Spring Security 解析(四) ——短信登陆开发

Spring Security 解析(四) —— 短信登陆开发

  在学习Spring Cloud 时,遇到了受权服务oauth 相关内容时,老是只知其一;不知其二,所以决定先把Spring Security 、Spring Security Oauth2 等权限、认证相关的内容、原理及设计学习并整理一遍。本系列文章就是在学习的过程当中增强印象和理解所撰写的,若有侵权请告知。git

项目环境:github

- JDK1.8redis

- Spring boot 2.xspring

- Spring Security 5.x缓存

1、如何在Security的基础上实现短信登陆功能?

  回顾下Security实现表单登陆的过程:app

https://user-gold-cdn.xitu.io/2019/9/2/16cf275b9ca9a2bd?w=1340&h=872&f=jpeg&s=86789

  从流程中咱们发现其在登陆过程当中存在特殊处理或者说拥有其余姊妹实现子类的:dom

- AuthenticationFilter:用于拦截登陆请求;ide

- 未认证的Authentication 对象,做为认证方法的入参;函数

- AuthenticationProvider 进行认证处理。工具

  所以咱们能够彻底经过自定义 一个 SmsAuthenticationFilter 进行拦截 ,一个 SmsAuthenticationToken 来进行传输认证数据,一个 SmsAuthenticationProvider 进行认证业务处理。因为咱们知道 UsernamePasswordAuthenticationFilter 的 doFilter 是经过 AbstractAuthenticationProcessingFilter 来实现的,而 UsernamePasswordAuthenticationFilter 自己只实现了attemptAuthentication() 方法。按照这样的设计,咱们的 SmsAuthenticationFilter 也 只实现 attemptAuthentication() 方法,那么如何进行验证码的验证呢?这时咱们须要在 SmsAuthenticationFilter 前 调用 一个 实现验证码的验证过滤 filter :ValidateCodeFilter。整理实现事后的流程以下图:

https://user-gold-cdn.xitu.io/2019/9/2/16cf275bc967fc81?w=1258&h=934&f=jpeg&s=134973

2、短信登陆认证开发

(一) SmsAuthenticationFilter 实现

  模拟UsernamePasswordAuthenticationFilter实现SmsAuthenticationFilter后其代码以下:

@EqualsAndHashCode(callSuper = true)
@Data
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    // 获取request中传递手机号的参数名
    private String mobileParameter = SecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE;

    private boolean postOnly = true;

    // 构造函数,主要配置其拦截器要拦截的请求地址url
    public SmsCodeAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE, "POST"));
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        // 判断请求是否为 POST 方式
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 调用 obtainMobile 方法从request中获取手机号
        String mobile = obtainMobile(request);

        if (mobile == null) {
            mobile = "";
        }

        mobile = mobile.trim();

        // 建立 未认证的  SmsCodeAuthenticationToken  对象
        SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);

        setDetails(request, authRequest);
        
        // 调用 认证方法
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    /**
     * 获取手机号
     */
    protected String obtainMobile(HttpServletRequest request) {
        return request.getParameter(mobileParameter);
    }
    
    /**
     * 原封不动照搬UsernamePasswordAuthenticationFilter 的实现 (注意这里是 SmsCodeAuthenticationToken  )
     */
    protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    /**
     * 开放设置 RemmemberMeServices 的set方法
     */
    @Override
    public void setRememberMeServices(RememberMeServices rememberMeServices) {
        super.setRememberMeServices(rememberMeServices);
    }
}复制代码

其内部实现主要有几个注意点:

- 设置传输手机号的参数属性

- 构造方法调用父类的有参构造方法,主要用于设置其要拦截的url

- 照搬UsernamePasswordAuthenticationFilter 的 attemptAuthentication() 的实现 ,其内部须要改造有2点:一、 obtainMobile 获取 手机号信息 二、建立 SmsCodeAuthenticationToken 对象

- 为了实现短信登陆也拥有记住个人功能,这里开放 setRememberMeServices() 方法用于设置 rememberMeServices 。

(二) SmsAuthenticationToken 实现

  同样的咱们模拟UsernamePasswordAuthenticationToken实现SmsAuthenticationToken:

public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;


    private final Object principal;

    /**
     * 未认证时,内容为手机号
     * @param mobile
     */
    public SmsCodeAuthenticationToken(String mobile) {
        super(null);
        this.principal = mobile;
        setAuthenticated(false);
    }

    /**
     *
     * 认证成功后,其中为用户信息
     *
     * @param principal
     * @param authorities
     */
    public SmsCodeAuthenticationToken(Object principal,
                                      Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }

        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }
}复制代码

  对比UsernamePasswordAuthenticationToken,咱们减小了 credentials(能够理解为密码),其余的基本上是原封不动。

(三) SmsAuthenticationProvider 实现

  因为SmsCodeAuthenticationProvider 是一个全新的不一样的认证委托实现,所以这个咱们按照本身的设想写,没必要参照 DaoAuthenticationProvider。看下咱们本身实现的代码:

@Data
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;

        UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());

        if (user == null) {
            throw new InternalAuthenticationServiceException("没法获取用户信息");
        }

        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, user.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}复制代码

  经过直接继承 AuthenticationProvider实现其接口方法 authenticate() 和 supports() 。 supports() 咱们直接参照其余Provider写的,这个主要是判断当前处理的Authentication是否为SmsCodeAuthenticationToken或其子类。 authenticate() 咱们就直接调用 userDetailsService的loadUserByUsername()方法简单实现,由于验证码已经在 ValidateCodeFilter 验证经过了,因此这里咱们只要能经过手机号查询到用户信息那就直接判顶当前用户认证成功,而且生成 已认证 的 SmsCodeAuthenticationToken返回。

(四) ValidateCodeFilter 实现

   正如咱们以前描述的同样ValidateCodeFilter只作验证码的验证,这里咱们设置经过redis获取生成验证码来对比用户输入的验证码:

@Component
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    /**
     * 验证码校验失败处理器
     */
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    /**
     * 系统配置信息
     */
    @Autowired
    private SecurityProperties securityProperties;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 存放全部须要校验验证码的url
     */
    private Map<String, String> urlMap = new HashMap<>();
    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 初始化要拦截的url配置信息
     */
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();

        urlMap.put(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE, SecurityConstants.DEFAULT_PARAMETER_NAME_CODE_SMS);
        addUrlToMap(securityProperties.getSms().getSendSmsUrl(), SecurityConstants.DEFAULT_PARAMETER_NAME_CODE_SMS);
    }

    /**
     * 讲系统中配置的须要校验验证码的URL根据校验的类型放入map
     *
     * @param urlString
     * @param smsParam
     */
    protected void addUrlToMap(String urlString, String smsParam) {
        if (StringUtils.isNotBlank(urlString)) {
            String[] urls = StringUtils.splitByWholeSeparatorPreserveAllTokens(urlString, ",");
            for (String url : urls) {
                urlMap.put(url, smsParam);
            }
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        String code = request.getParameter(getValidateCode(request));
        if (code != null) {
            try {
                String oldCode = stringRedisTemplate.opsForValue().get(request.getParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE));
                if (StringUtils.equalsIgnoreCase(oldCode,code)) {
                    logger.info("验证码校验经过");
                } else {
                    throw new ValidateCodeException("验证码失效或错误!");
                }
            } catch (AuthenticationException e) {
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * 获取校验码
     *
     * @param request
     * @return
     */
    private String getValidateCode(HttpServletRequest request) {
        String result = null;
        if (!StringUtils.equalsIgnoreCase(request.getMethod(), "get")) {
            Set<String> urls = urlMap.keySet();
            for (String url : urls) {
                if (pathMatcher.match(url, request.getRequestURI())) {
                    result = urlMap.get(url);
                }
            }
        }
        return result;
    }
}复制代码

这里主要看下 doFilterInternal 实现验证码验证逻辑便可。

3、如何将设置SMS的Filter加入到FilterChain生效呢?

这里咱们须要引进新的配置类 SmsCodeAuthenticationSecurityConfig,其实现代码以下:

@Component
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler ;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Resource
    private UserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        // 设置 AuthenticationManager
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        // 分别设置成功和失败处理器
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
        // 设置 RememberMeServices
        smsCodeAuthenticationFilter.setRememberMeServices(http
                .getSharedObject(RememberMeServices.class));

        // 建立 SmsCodeAuthenticationProvider 并设置 userDetailsService
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);

        // 将Provider添加到其中
        http.authenticationProvider(smsCodeAuthenticationProvider)
                // 将过滤器添加到UsernamePasswordAuthenticationFilter后面
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }复制代码

最后咱们须要 在 SpringSecurityConfig 配置类中引用 SmsCodeAuthenticationSecurityConfig :

http.addFilterBefore(validateCodeFilter, AbstractPreAuthenticatedProcessingFilter.class)
                .apply(smsCodeAuthenticationSecurityConfig)
                . ...复制代码

4、新增发送验证码接口和验证码登陆表单

   新增发送验证码接口(主要设置成无权限访问):

@GetMapping("/send/sms/{mobile}")
    public void sendSms(@PathVariable String mobile) {
        // 随机生成 6 位的数字串
        String code = RandomStringUtils.randomNumeric(6);
        // 经过 stringRedisTemplate 缓存到redis中 
        stringRedisTemplate.opsForValue().set(mobile, code, 60 * 5, TimeUnit.SECONDS);
        // 模拟发送短信验证码
        log.info("向手机: " + mobile + " 发送短信验证码是: " + code);
    }复制代码

   新增验证码登陆表单:

// 注意这里的请求接口要与 SmsAuthenticationFilter的构造函数 设置的一致
<form action="/loginByMobile" method="post">
    <table>
        <tr>
            <td>手机号:</td>
            <td><input type="text" name="mobile" value="15680659123"></td>
        </tr>
        <tr>
            <td>短信验证码:</td>
            <td>
                <input type="text" name="smsCode">
                <a href="/send/sms/15680659123">发送验证码</a>
            </td>
        </tr>
        <tr>
            <td colspan='2'><input name="remember-me" type="checkbox" value="true"/>记住我</td>
        </tr>
        <tr>
            <td colspan="2">
                <button type="submit">登陆</button>
            </td>
        </tr>
    </table>
</form>复制代码

5、我的总结

  其实实现另外一种登陆方式,关键点就在与 filter 、 AuthenticationToken、AuthenticationProvider 这3个点上。整理出来就是: 经过自定义 一个 SmsAuthenticationFilter 进行拦截 ,一个 AuthenticationToken 来进行传输认证数据,一个 AuthenticationProvider 进行认证业务处理。因为咱们知道 UsernamePasswordAuthenticationFilter 的 doFilter 是经过 AbstractAuthenticationProcessingFilter 来实现的,而 UsernamePasswordAuthenticationFilter 自己只实现了attemptAuthentication() 方法。按照这样的设计,咱们的 AuthenticationFilter 也 只实现 attemptAuthentication() 方法,但同时须要在 AuthenticationFilter 前 调用 一个 实现验证过滤 filter :ValidatFilter。 正以下面的流程图同样,能够按照这种方式添加任意一种登陆方式:

https://user-gold-cdn.xitu.io/2019/9/2/16cf275bc967fc81?w=1258&h=934&f=jpeg&s=134973

   本文介绍短信登陆开发的代码能够访问代码仓库中的 security 模块 ,项目的github 地址 : https://github.com/BUG9/spring-security

         若是您对这些感兴趣,欢迎star、follow、收藏、转发给予支持!

相关文章
相关标签/搜索