验证码的获取与验证

该博客详细介绍了如何使用Vue.js前端与SpringBoot后端配合实现验证码功能。前端通过生成uuid请求后端接口,后端利用SimpleCaptcha生成验证码图片并存储,设置过期时间,然后返回给前端。整个流程确保了验证码的安全性和时效性。
摘要由CSDN通过智能技术生成

1、前端vue部分:

/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

根据生成的uuid从后端获取验证码

    created () {
      this.getCaptcha()
    },

    // 获取验证码
    getCaptcha () {
      this.dataForm.uuid = getUUID()
      this.captchaPath = this.$http.adornUrl(`/captcha.jpg?uuid=${this.dataForm.uuid}`)
    }

提交表单

    // 提交表单
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/login?grant_type=admin'),
            method: 'post',
            data: this.$http.adornData({
              'principal': this.dataForm.userName,
              'credentials': this.dataForm.password,
              'sessionUUID': this.dataForm.uuid,
              'imageCode': this.dataForm.captcha
            })
          }).then(({ data }) => {
            this.$cookie.set('Authorization', 'bearer' + data.access_token)
            this.$router.replace({ name: 'home' })
          }).catch(() => {
            this.getCaptcha()
          })
        }
      })
    },

验证码部分的表单

            <el-row :gutter="20">
              <el-col :span="14">
                <el-input v-model="dataForm.captcha" placeholder="验证码">
                </el-input>
              </el-col>
              <el-col :span="10" class="login-captcha">
                <img :src="captchaPath" @click="getCaptcha()" alt="" />
              </el-col>
            </el-row>

2、后端Spring Boot部分

获取验证码图片路径的接口

	@GetMapping("/captcha.jpg")
	public void login(HttpServletResponse response,String uuid) {
		//定义图形验证码的长、宽、验证码字符数、干扰元素个数  300s后过期
		SimpleCaptcha simpleCaptcha = new SimpleCaptcha(200, 50, 4, 20);
		try {
			simpleCaptcha.write(response.getOutputStream());
			RedisUtil.set(SecurityConstants.SPRING_SECURITY_RESTFUL_IMAGE_CODE+uuid, simpleCaptcha.getCode(), 300);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

这个方法生成了code,过期时间,并和uuid一起组成了一个 验证码对象,保存到了数据库当中。当做完这些操作后,将生成的图片响应给前端。

总结:前端生成uuid,携带该参数请求后台接口。后台调用方法生成验证码,设置过期时间,合并前端传递的uuid组成一个对象,保存至数据库。设置响应类型,响应给前端

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值