1. 程式人生 > 其它 >SpringBoot 前後端分離 實現驗證碼操作

SpringBoot 前後端分離 實現驗證碼操作

驗證碼的功能是防止非法使用者惡意去訪問登入介面而設定的一個功能,今天我們就來看看在前後端分離的專案中,SpringBoot 是如何提供服務的。

1|0SpringBoot 版本

本文基於的 Spring Boot 的版本是 2.6.7 。

2|0 引入依賴

captcha 一款超簡單的驗證碼生成,還挺好玩的。還有中文驗證碼,動態驗證碼. 。在專案中 pom.xml 配置檔案中新增依賴,如下:

<!--驗證碼-->
<dependency>
    <groupId>com.github.whvcse</groupId>
    <artifactId>easy-captcha</artifactId>
    <version>1.6.2</version>
</dependency>
  • 把生成的驗證碼結果儲存到 redis 快取中,並設定過期時間。
  • 前端通過提交驗證碼和 key,其中 key 就是儲存到 redis 中的鍵,通過這個鍵獲取到對應的值,再與前端提交的值對比,相同就通過驗證。

3|1 實現過程

新建驗證碼列舉類

由於 captcha 這款驗證碼提供了好幾種驗證碼方法,有中文驗證碼,動態驗證碼,算術驗證碼等等,新建一個驗證碼每週類存放這幾種驗證碼型別。程式碼如下:

// fhadmin.cn
public enum LoginCodeEnum {
    /**
     * 算數
     */
    ARITHMETIC,
    /**
     * 中文
     */
    CHINESE,
    /**
     * 中文閃圖
     */
    CHINESE_GIF,
    /**
     * 閃圖
     */
    GIF,
    SPEC
}

該類是定義驗證碼的基本資訊,例如高度、寬度、字型型別、驗證碼型別等等、並且我們把它轉成通過 SpringBoot 配置檔案型別來定義更加方便。

// fhadmin.cn
@Data
public class LoginCode {

    /**
     * 驗證碼配置
     */
    private LoginCodeEnum codeType;
    /**
     * 驗證碼有效期 分鐘
     */
    private Long expiration = 2L;
    /**
     * 驗證碼內容長度
     */
    private int length = 2;
    /**
     * 驗證碼寬度
     */
    private int width = 111;
    /**
     * 驗證碼高度
     */
    private int height = 36;
    /**
     * 驗證碼字型
     */
    private String fontName;
    /**
     * 字型大小
     */
    private int fontSize = 25;

    /**
     * 驗證碼字首
     * @return
     */
    private  String   codeKey;


    public LoginCodeEnum getCodeType() {
        return codeType;
    }
}

把配置檔案轉換 Pojo 類的統一配置類

// fhadmin.cn
@Configuration
public class ConfigBeanConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "login")
    public LoginProperties loginProperties() {
        return new LoginProperties();
    }
}

定義邏輯驗證生成類

// fhadmin.cn
@Data
public class LoginProperties {

    private LoginCode loginCode;


    /**
     * 獲取驗證碼生產類
     * @return
     */
    public Captcha getCaptcha(){
        if(Objects.isNull(loginCode)){
            loginCode = new LoginCode();
            if(Objects.isNull(loginCode.getCodeType())){
                loginCode.setCodeType(LoginCodeEnum.ARITHMETIC);
            }

        }
        return switchCaptcha(loginCode);
    }

    /**
     * 依據配置資訊生產驗證碼
     * @param loginCode
     * @return
     */
    private Captcha switchCaptcha(LoginCode loginCode){
        Captcha captcha = null;
        synchronized (this){
            switch (loginCode.getCodeType()){
                case ARITHMETIC:
                    captcha = new FixedArithmeticCaptcha(loginCode.getWidth(),loginCode.getHeight());
                    captcha.setLen(loginCode.getLength());
                    break;
                case CHINESE:
                    captcha = new ChineseCaptcha(loginCode.getWidth(),loginCode.getHeight());
                    captcha.setLen(loginCode.getLength());
                    break;
                case CHINESE_GIF:
                    captcha = new ChineseGifCaptcha(loginCode.getWidth(),loginCode.getHeight());
                    captcha.setLen(loginCode.getLength());
                    break;
                case GIF:
                    captcha = new GifCaptcha(loginCode.getWidth(),loginCode.getHeight());
                    captcha.setLen(loginCode.getLength());
                    break;
                case SPEC:
                    captcha = new SpecCaptcha(loginCode.getWidth(),loginCode.getHeight());
                    captcha.setLen(loginCode.getLength());
                default:
                    System.out.println("驗證碼配置資訊錯誤!正確配置檢視 LoginCodeEnum ");

            }
        }
        if(StringUtils.isNotBlank(loginCode.getFontName())){
            captcha.setFont(new Font(loginCode.getFontName(),Font.PLAIN,loginCode.getFontSize()));
        }
        return captcha;
    }

    static  class FixedArithmeticCaptcha extends ArithmeticCaptcha{
        public FixedArithmeticCaptcha(int width,int height){
            super(width,height);
        }

        @Override
        protected char[] alphas() {
            // 生成隨機數字和運算子
            int n1 = num(1, 10), n2 = num(1, 10);
            int opt = num(3);

            // 計算結果
            int res = new int[]{n1 + n2, n1 - n2, n1 * n2}[opt];
            // 轉換為字元運算子
            char optChar = "+-x".charAt(opt);

            this.setArithmeticString(String.format("%s%c%s=?", n1, optChar, n2));
            this.chars = String.valueOf(res);

            return chars.toCharArray();
        }
    }
}

控制層定義驗證生成介面

// fhadmin.cn   
@ApiOperation(value = "獲取驗證碼", notes = "獲取驗證碼")
    @GetMapping("/code")
    public Object getCode(){

        Captcha captcha = loginProperties.getCaptcha();
        String uuid = "code-key-"+IdUtil.simpleUUID();
        //當驗證碼型別為 arithmetic時且長度 >= 2 時,captcha.text()的結果有機率為浮點型
        String captchaValue = captcha.text();
        if(captcha.getCharType()-1 == LoginCodeEnum.ARITHMETIC.ordinal() && captchaValue.contains(".")){
            captchaValue = captchaValue.split("\\.")[0];
        }
        // 儲存
        redisUtils.set(uuid,captchaValue,loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
        // 驗證碼資訊
        Map<String,Object> imgResult = new HashMap<String,Object>(2){{
            put("img",captcha.toBase64());
            put("uuid",uuid);
        }};
        return imgResult;

    }

前端呼叫介面

<template>
<div class="login-code">
  <img :src="codeUrl" @click="getCode">
</div>
</template>
<script>
    methods: {
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = res.data.img
        this.loginForm.uuid = res.data.uuid
      })
    },
    }
    created() {
    // 獲取驗證碼
    this.getCode()
  },
 </script>