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组成一个对象,保存至数据库。设置响应类型,响应给前端

Logo

前往低代码交流专区

更多推荐