欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能

程序员文章站 2022-04-09 08:32:28
在 Spring Security 中基于表单的认证模式,默认就是密码帐号登录认证,那么对于短信验证码+登录的方式,Spring Security 没有现成的接口可以使用,所以需要自己的封装一个类似的认证过滤器和认证处理器实现短信认证。 短信验证码认证 验证码对象类设计 和图片验证码一样,需要自己封 ......

在 spring security 中基于表单的认证模式,默认就是密码帐号登录认证,那么对于短信验证码+登录的方式,spring security 没有现成的接口可以使用,所以需要自己的封装一个类似的认证过滤器和认证处理器实现短信认证。

短信验证码认证

验证码对象类设计

和图片验证码一样,需要自己封装一个验证码对象,用来生成手机验证码并发送给手机。因为图片验证码和手机验证码对象的区别就在于前者多了个图片对象,所以两者共同部分抽象出来可以设计成一个validatecode类,这个类里面只存放验证码和过期时间,短信验证码直接使用这个类即可:

import java.time.localdatetime;

import lombok.data;

@data
public class validatecode {

    private string code;

    private localdatetime expiretime;

    public validatecode(string code, int expirein){
        this.code = code;
        this.expiretime = localdatetime.now().plusseconds(expirein);
    }
    
    public boolean isexpried() {
        return localdatetime.now().isafter(getexpiretime());
    }

    public validatecode(string code, localdatetime expiretime) {
        super();
        this.code = code;
        this.expiretime = expiretime;
    }
}

图片验证码承继此类:

import java.awt.image.bufferedimage;
import java.time.localdatetime;

import org.woodwhales.king.validate.code.validatecode;

import lombok.data;
import lombok.equalsandhashcode;

@data
@equalsandhashcode(callsuper=false)
public class imagecode extends validatecode {

    private bufferedimage image;

    public imagecode(bufferedimage image, string code, int expireid) {
        super(code, localdatetime.now().plusseconds(expireid));
        this.image = image;
    }

    public imagecode(bufferedimage image, string code, localdatetime localdatetime) {
        super(code, localdatetime);
        this.image = image;
    }

}

验证码生成类设计

由于图片和短信类均可以生成相应的验证码,所以直接设计一个验证码生成接口,具体实现类根据业务进行实现:

import org.springframework.web.context.request.servletwebrequest;

public interface validatecodegenerator {

    validatecode generate(servletwebrequest request);

}

这里的传参设计成了servletwebrequest是能够根据前端请求中的参数进行不同的业务实现

目前实现累只有图片生成器和验证码生成器:

// 图片验证码生成器
@component("imagecodegenerator")
public class imagecodegenerator implements validatecodegenerator {

    /**
     * 生成图形验证码
     * @param request
     * @return
     */
    @override
    public validatecode generate(servletwebrequest request) {
        
        ……

        return new imagecode(image, srand, securityconstants.expire_second);

    }
}

// 短信验证码生成器
@component("smscodegenerator")
public class smscodegenerator implements validatecodegenerator {

    @override
    public validatecode generate(servletwebrequest request) {
        string code = randomstringutils.randomnumeric(securityconstants.sms_random_size);
        return new validatecode(code, securityconstants.sms_expire_second);
    }

}

短信验证码发送接口设计

短信验证码生成之后,需要设计接口依赖短信服务提供商进行验证码发送,因此至少设计一个统一的接口,供短信服务提供商生成发送短信服务:

public interface smscodesender {
    // 至少需要手机号和验证码
    void send(string mobile, string code);

}

为了演示,设计一个虚拟的默认短信发送器,只在日志文件中打印一行log:

import org.springframework.stereotype.service;

import lombok.extern.slf4j.slf4j;

/**
 * 短信发送模拟
 * @author administrator
 *
 */
@slf4j
@service
public class defaultsmscodesender implements smscodesender {

    @override
    public void send(string mobile, string code) {
        log.debug("send to mobile :{}, code : {}", mobile, code);
    }
}

短信验证码请求controller

所有验证码的请求都在统一的validatecodecontroller里,这里注入了两个验证码生成器validatecodegenerator,后期可以利用 spring 的依赖查找/搜索技巧来重构代码,另外所有的请求也是可以做成动态配置,这里临时全部 hardcode 在代码里:

import java.io.ioexception;

import javax.imageio.imageio;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.social.connect.web.sessionstrategy;
import org.springframework.web.bind.servletrequestbindingexception;
import org.springframework.web.bind.servletrequestutils;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.context.request.servletwebrequest;
import org.woodwhales.king.core.commons.securityconstants;
import org.woodwhales.king.validate.code.validatecode;
import org.woodwhales.king.validate.code.validatecodegenerator;
import org.woodwhales.king.validate.code.image.imagecode;
import org.woodwhales.king.validate.code.sms.defaultsmscodesender;

@restcontroller
public class validatecodecontroller {
    
    @autowired
    private sessionstrategy sessionstrategy;

    @autowired
    private validatecodegenerator imagecodegenerator;
    
    @autowired
    private validatecodegenerator smscodegenerator;
    
    @autowired
    private defaultsmscodesender defaultsmscodesender;
    
    @getmapping("code/image")
    public void createimagecode(httpservletrequest request, httpservletresponse response) throws ioexception {
        imagecode imagecode = (imagecode)imagecodegenerator.generate(new servletwebrequest(request));
        sessionstrategy.setattribute(new servletwebrequest(request), securityconstants.session_key, imagecode);
        imageio.write(imagecode.getimage(), "jpeg", response.getoutputstream());
    }
    
    @getmapping("code/sms")
    public void createsmscode(httpservletrequest request, httpservletresponse response) throws servletrequestbindingexception {
        validatecode smscode = smscodegenerator.generate(new servletwebrequest(request));
        sessionstrategy.setattribute(new servletwebrequest(request), securityconstants.session_key, smscode);
        string mobile = servletrequestutils.getstringparameter(request, "mobile");
        defaultsmscodesender.send(mobile, smscode.getcode());
    }
}

从上述代码中可以看出图片验证码和短信验证码的生成请求逻辑是相似的:首先调用验证码生成接口生成验证码,然后将验证码放入 session 中,最后将验证码返回给前端或者用户。因此这个套路流程可以抽象成一个模板方法,以增强代码的可维护性和可扩展性。

用一张图来表述重构后的代码结构:

SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能

随机验证码过滤器设计

由于图片和手机都会产生验证码,后期还可以通过邮件发送随机验证码的方式进行随机验证码登录验证,因此将随机验证码的认证可以独立封装在一个随机验证码过滤器中,并且这个过滤器在整个 spring security 过滤器链的最前端(它是第一道认证墙)。

随机验证码过滤器只要继承 spring 框架中的onceperrequestfilter即可保证这个过滤器在请求来的时候只被调用一次,具体代码实现参见文末源码。

这里重点解释一下如何将随机验证码过滤器配置到 spring security 过滤器认证最前端,需要重写securityconfigureradapterconfigure()方法,并将自定义的过滤器放到abstractpreauthenticatedprocessingfilter过滤器之前即可:

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.security.config.annotation.securityconfigureradapter;
import org.springframework.security.config.annotation.web.builders.httpsecurity;
import org.springframework.security.web.defaultsecurityfilterchain;
import org.springframework.security.web.authentication.preauth.abstractpreauthenticatedprocessingfilter;
import org.springframework.stereotype.component;

import javax.servlet.filter;


@component
public class validatecodesecurityconfig extends securityconfigureradapter<defaultsecurityfilterchain, httpsecurity> {

    @autowired
    private filter validatecodefilter;

    @override
    public void configure(httpsecurity http) throws exception {
        super.configure(http);
        http.addfilterbefore(validatecodefilter, abstractpreauthenticatedprocessingfilter.class);
    }
}

短信验证码认证

在自定义短信登录认证流程之前,建议可以移步到之前的文章:springboot + spring security 学习笔记(二)安全认证流程源码详解,了解清除用户密码的认证流程才能更容易理解下面这张经典的流程图:

SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能

左侧是用户+密码的认证流程,整体的流程就是经过用户名+密码认证过滤器认证,将请求封装成 token 并注入到 autheticationmananger 中,之后由默认的认证校验器进行校验,在校验的过程中会调用 userdetailsservice 接口进行 token 校验,当校验成功之后,就会将已经认证的 token 放到 securitycontextholder 中。

同理,由于短信登录方式只需要使用随机验证码进行校验而不需要密码登录功能,当校验成功之后就认为用户认证成功了,因此需要仿造左侧的流程开发自定义的短信登录认证 token,这个 token 只需要存放手机号即可,在token 校验的过程中,不能使用默认的校验器了,需要自己开发校验当前自定义 token 的校验器,最后将自定义的过滤器和校验器配置到 spring security 框架中即可。

注意:短信随机验证码的验证过程是在 smscodeauthticationfilter 之前就已经完成。

短信登录认证token

仿造usernamepasswordauthenticationtoken设计一个属于短信验证的认证 token 对象,为什么要自定义一个短信验证的 token,spring security 框架不只提供了用户名+密码的验证方式,用户认证是否成功,最终看的就是securitycontextholder对象中是否有对应的authenticationtoken,因此要设计一个认证对象,当认证成功之后,将其设置到securitycontextholder即可。

import java.util.collection;

import org.springframework.security.authentication.abstractauthenticationtoken;
import org.springframework.security.core.grantedauthority;
import org.springframework.security.core.springsecuritycoreversion;

public class smscodeauthenticationtoken extends abstractauthenticationtoken {

    private static final long serialversionuid = springsecuritycoreversion.serial_version_uid;

    private final object principal;

    public smscodeauthenticationtoken(object mobile) {
        super(null);
        this.principal = mobile;
        setauthenticated(false);
    }

    public smscodeauthenticationtoken(object mobile, collection<? extends grantedauthority> authorities) {
        super(authorities);
        this.principal = mobile;
        super.setauthenticated(true); // must use super, as we override
    }

    public object getprincipal() {
        return this.principal;
    }
    
    public object getcredentials() {
        return null;
    }

    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();
    }

}

authenticationtoken接口可以看到,现在框架中有我们自己定义短信登录的 token 了:

SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能

短信登录认证过滤器

短信验证码的过滤器设计思路同理,仿造usernamepasswordauthenticationfilter过滤器,这里再次提醒,短信随机验证码

import java.util.objects;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.springframework.security.authentication.authenticationserviceexception;
import org.springframework.security.core.authentication;
import org.springframework.security.core.authenticationexception;
import org.springframework.security.web.authentication.abstractauthenticationprocessingfilter;
import org.springframework.security.web.util.matcher.antpathrequestmatcher;
import org.springframework.util.assert;
import org.woodwhales.core.constants.securityconstants;

public class smscodeauthenticationfilter extends abstractauthenticationprocessingfilter {

    /**
     * 请求中的参数
     */
    private string mobileparameter = securityconstants.default_parameter_name_mobile;
    
    private boolean postonly = true;

    public smscodeauthenticationfilter() {
        super(new antpathrequestmatcher(securityconstants.default_login_processing_url_mobile, "post"));
    }

    public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception {
        if (postonly && !request.getmethod().equals("post")) {
            throw new authenticationserviceexception("authentication method not supported: " + request.getmethod());
        }

        // 获取请求中的参数值
        string mobile = obtainmobile(request);

        if (objects.isnull(mobile)) {
            mobile = "";
        }

        mobile = mobile.trim();
        
        smscodeauthenticationtoken authrequest = new smscodeauthenticationtoken(mobile);

        // allow subclasses to set the "details" property
        setdetails(request, authrequest);

        return this.getauthenticationmanager().authenticate(authrequest);
    }

    /**
     * 获取手机号
     */
    protected string obtainmobile(httpservletrequest request) {
        return request.getparameter(mobileparameter);
    }

    protected void setdetails(httpservletrequest request, smscodeauthenticationtoken authrequest) {
        authrequest.setdetails(authenticationdetailssource.builddetails(request));
    }

    public void setmobileparameter(string mobileparameter) {
        assert.hastext(mobileparameter, "mobile parameter must not be empty or null");
        this.mobileparameter = mobileparameter;
    }

    public void setpostonly(boolean postonly) {
        this.postonly = postonly;
    }

    public final string getmobileparameter() {
        return mobileparameter;
    }

}

短信验证码过滤器也成为了abstractauthenticationprocessingfilter其中一个子类,后期需要注册到安全配置中,让它成为安全认证过滤链中的一环:

SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能

短信登录认证校验器

短信登录认证校验器的作用就是调用userdetailsserviceloaduserbyusername()方法对 authenticationtoken 进行校验,所有校验器的根接口为:authenticationprovider,因此自定义的短信登录认证校验器实现这个接口,重写authenticate()即可:

import java.util.objects;

import org.springframework.security.authentication.authenticationprovider;
import org.springframework.security.authentication.internalauthenticationserviceexception;
import org.springframework.security.core.authentication;
import org.springframework.security.core.authenticationexception;
import org.springframework.security.core.userdetails.userdetails;
import org.springframework.security.core.userdetails.userdetailsservice;

import lombok.data;

@data
public class smscodeauthenticationprovider implements authenticationprovider {

    private userdetailsservice userdetailsservice;
    
    @override
    public authentication authenticate(authentication authentication) throws authenticationexception {

        smscodeauthenticationtoken authenticationtoken = (smscodeauthenticationtoken) authentication;

        /**
         * 调用 {@link userdetailsservice}
         */
        userdetails user = userdetailsservice.loaduserbyusername((string)authenticationtoken.getprincipal());

        if (objects.isnull(user)) {
            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);
    }

}

注意,这里使用@data注解生成 setter 和 getter 方法。

SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能

短信登录认证安全配置设计

设计一个封装好的短信登录认证配置类,以供外部调用者直接调用:

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.security.authentication.authenticationmanager;
import org.springframework.security.config.annotation.securityconfigureradapter;
import org.springframework.security.config.annotation.web.builders.httpsecurity;
import org.springframework.security.core.userdetails.userdetailsservice;
import org.springframework.security.web.defaultsecurityfilterchain;
import org.springframework.security.web.authentication.authenticationfailurehandler;
import org.springframework.security.web.authentication.authenticationsuccesshandler;
import org.springframework.security.web.authentication.usernamepasswordauthenticationfilter;
import org.springframework.stereotype.component;

@component
public class smscodeauthenticationsecurityconfig extends securityconfigureradapter<defaultsecurityfilterchain, httpsecurity> {

    @autowired
    private authenticationsuccesshandler myauthenticationsuccesshandler;

    @autowired
    private authenticationfailurehandler myauthenticationfailurehandler;

    @autowired
    private userdetailsservice userdetailsservice;

    @override
    public void configure(httpsecurity http) throws exception {

        smscodeauthenticationfilter smscodeauthenticationfilter = new smscodeauthenticationfilter();
        smscodeauthenticationfilter.setauthenticationmanager(http.getsharedobject(authenticationmanager.class));
        smscodeauthenticationfilter.setauthenticationsuccesshandler(myauthenticationsuccesshandler);
        smscodeauthenticationfilter.setauthenticationfailurehandler(myauthenticationfailurehandler);

        // 获取验证码提供者
        smscodeauthenticationprovider smscodeauthenticationprovider = new smscodeauthenticationprovider();
        smscodeauthenticationprovider.setuserdetailsservice(userdetailsservice);

        // 将短信验证码校验器注册到 httpsecurity, 并将短信验证码过滤器添加在 usernamepasswordauthenticationfilter 之前
        http.authenticationprovider(smscodeauthenticationprovider).addfilterafter(smscodeauthenticationfilter, usernamepasswordauthenticationfilter.class);

    }
}

当外部想要引用这个封装好的配置,只需要在自定义的abstractchannelsecurityconfig安全认证配置中添加进去即可,注意这个配置对象使用了@component注解,注册到了spring 中,所以可以直接通过@autowired引用,如:

import javax.sql.datasource;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.bean;
import org.springframework.security.config.annotation.web.builders.httpsecurity;
import org.springframework.security.core.userdetails.userdetailsservice;
import org.springframework.security.web.authentication.authenticationfailurehandler;
import org.springframework.security.web.authentication.authenticationsuccesshandler;
import org.springframework.security.web.authentication.rememberme.jdbctokenrepositoryimpl;
import org.springframework.security.web.authentication.rememberme.persistenttokenrepository;
import org.springframework.stereotype.component;
import org.woodwhales.core.authentication.sms.abstractchannelsecurityconfig;
import org.woodwhales.core.authentication.sms.smscodeauthenticationsecurityconfig;
import org.woodwhales.core.validate.code.config.validatecodesecurityconfig;

@component
public class browsersecurityconfig extends abstractchannelsecurityconfig {

    @autowired
    private smscodeauthenticationsecurityconfig smscodeauthenticationsecurityconfig;

    @autowired
    private validatecodesecurityconfig validatecodesecurityconfig;
    
    @autowired
    protected authenticationsuccesshandler authenticationsuccesshandler;

    @autowired
    protected authenticationfailurehandler authenticationfailurehandler;
    
    @autowired
    private userdetailsservice userdetailsservice;
    
    @autowired
    private datasource datasource;

    @override
    protected void configure(httpsecurity http) throws exception {

        http.formlogin()
            .loginpage("/authentication/require") // 登录页面回调
            .successhandler(authenticationsuccesshandler)// 认证成功回调
            .failurehandler(authenticationfailurehandler)
        
            // 以下验证码的校验配置
            .and()
            .apply(validatecodesecurityconfig) 
    
            // 以下短信登录认证的配置
            .and()
            .apply(smscodeauthenticationsecurityconfig)
                
            // 记住我的配置
            .and()
            .rememberme()
            .tokenrepository(persistenttokenrepository())
            .tokenvalidityseconds(3600) // 设置记住我的过期时间
            .userdetailsservice(userdetailsservice)
            
            .and()
            // 请求做授权配置
            .authorizerequests() 
            // 以下请求路径不需要认证
            .antmatchers("/authentication/require",
                    "/authentication/mobile",
                    "/login",
                    "/code/*",
                    "/")
            .permitall() 
            .anyrequest() // 任何请求
            .authenticated() // 都需要身份认证
            
            // 暂时将防护跨站请求伪造的功能置为不可用
            .and()
            .csrf().disable();
    }
    
    /**
     * 配置tokenrepository
     * @return
     */
    @bean
    public persistenttokenrepository persistenttokenrepository() {
        jdbctokenrepositoryimpl jdbctokenrepository = new jdbctokenrepositoryimpl();
        jdbctokenrepository.setdatasource(datasource);
        // 初始化记住我的数据库表,建议通过看源码直接创建出来
        // jdbctokenrepository.setcreatetableonstartup(true);
        return jdbctokenrepository;
    }

}

这里的配置中有些代码出现了冗余配置,可以全部封装成抽象模板,完成一些基础的配置。

项目源码:

参考源码: