前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springbooot使用google验证码

springbooot使用google验证码

作者头像
魚迹
发布2023-05-06 21:39:02
3030
发布2023-05-06 21:39:02
举报

springbooot使用google验证码

1、使用场景

由于需要做一个前后端分离的项目,想着使用google验证码,由于年龄大了,这些知识啊,用完就忘,在这里记录一下。

登录时验证码设计

  • 使用google验证码工具,当前端在登录请求时,在后端生成验证码,同时也生成一个随机数(UUID)与该验证码对应。
  • 使用redis作为缓存,将该随机数和验证码存储在redis中。
  • 随机数的目的是将验证码与发起登录请求的用户联系起来。
  • 当用户提交登录表单时,后端根据该随机数从redis中读取验证码与用户输入的验证码进行验证。

大概就是这样的一个设计思路,具体如下:

在这里插入图片描述
在这里插入图片描述

2、springboot使用google验证码

1、引入依赖

首先在pom文件中引入该验证码插件kaptcha

代码语言:javascript
复制
 <!-- google 验证码 -->
        <!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

2、编写配置类

引入依赖之后还需要编写配置类,在配置类里设置自己想要的验证码样式,包括颜色、大小、宽高等等。

我的配置类如下:

代码语言:javascript
复制
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfig {

       @Bean
    DefaultKaptcha producer() { //验证码的配置类
        Properties properties = new Properties();                       
        properties.put("kaptcha.border", "no");                       //边框
        properties.put("kaptcha.textproducer.font.color", "black");   //字体颜色
        properties.put("kaptcha.textproducer.char.space", "5");       //字体间隔
        properties.put("kaptcha.image.height", "40");                 //图片高度
        properties.put("kaptcha.image.width", "100");                 //图片宽度
        properties.put("kaptcha.textproducer.font.size", "30");       //字体大小
        Config config = new Config(properties);                       
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();         
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

3、编写控制层

将下面的代码放到需要使用验证码的controller中

代码语言:javascript
复制
//获取登录验证码
    @GetMapping("/captcha")
    public Result Captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());

        redisUtils.hset(Constants.CAPTCHA_KEY, key, code, 120);

        return Result.succ(
                MapUtil.builder()
                        .put("userKey", key)
                        .put("captchaImg", base64Img)
                        .build()
        );
    }

上面用到了封装的redis工具类redisUtils中的hset方法,并设置了验证码过期时间120秒。 hset方法如下:

代码语言:javascript
复制
/**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

Result是编写的统一结果返回类,代码如下所示:

代码语言:javascript
复制
@Data
public class Result_ implements Serializable {

    private int code;
    private String msg;
    private Object data;

    public static Result_ succ(Object data) {
        return succ(200, "操作成功", data);
    }

    public static Result_ fail(String msg) {
        return fail(400, msg, null);
    }

    public static Result_ succ (int code, String msg, Object data) {
        Result_ result = new Result_();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }

    public static Result_ fail (int code, String msg, Object data) {
        Result_ result = new Result_();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }
}

这里没有编写对于验证码的验证。

4、前端实现

验证码输入框代码如下:

代码语言:javascript
复制
<el-form-item label="验证码" prop="code" style="width: 380px">
                          <el-input placeholder="请输入验证码"v-model="loginForm.code"style="width: 172px; float: left" ></el-input>
                          <el-image class="captchaImg" :src="captchaImg" @click="getCaptcha()"></el-image>
                      </el-form-item>

验证码函数如下:

代码语言:javascript
复制
// 获取验证码
        getCaptcha() {
            this.$axios.get('/user/captcha1').then(res => {
                this.loginForm.token = res.data.data.token
                this.captchaImg = res.data.data.captchaImg
                this.loginForm.code = ''
            })
        }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-05-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • springbooot使用google验证码
  • 1、使用场景
  • 2、springboot使用google验证码
    • 1、引入依赖
      • 2、编写配置类
        • 3、编写控制层
          • 4、前端实现
          相关产品与服务
          验证码
          腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档