Vue实现图片验证码生成
图片验证码主要用于注册,登录等提交场景中,目的是防止脚本进行批量注册、登录、灌水,相比不带图片验证的安全度有所提高,不过目前也有自动识别图片验证码的程序出现,基本都是付费识别,随之又出现了滑动验证,选取正确选项验证等更加安全的验证方式。但图片验证码码仍用于大部分网站中。
一、前端图片验证码生成
前端逻辑大体就是进行图形绘制,取几个随机数放入图片中,加入干扰,进行验证
1.创建验证码组件identify.vue
<template> <div class="s-canvas" style="display: inline"> <canvas id="s-canvas" :width="contentWidth" :height="contentHeight"></canvas> </div> </template> <script> export default{ name: 'SIdentify', props: { identifyCode: { // 默认注册码 type: String, default: '1234' }, fontSizeMin: { // 字体最小值 type: Number, default: 25 }, fontSizeMax: { // 字体最大值 type: Number, default: 35 }, backgroundColorMin: { // 验证码图片背景色最小值 type: Number, default: 200 }, backgroundColorMax: { // 验证码图片背景色最大值 type: Number, default: 220 }, dotColorMin: { // 背景干扰点最小值 type: Number, default: 60 }, dotColorMax: { // 背景干扰点最大值 type: Number, default: 120 }, contentWidth: { // 容器宽度 type: Number, default: 117 }, contentHeight: { // 容器高度 type: Number, default: 32 } }, methods: { // 生成一个随机数 randomNum (min, max) { return Math.floor(Math.random() * (max - min) + min) }, // 生成一个随机的颜色 randomColor (min, max) { let r = this.randomNum(min, max) let g = this.randomNum(min, max) let b = this.randomNum(min, max) return 'rgb(' + r + ',' + g + ',' + b + ')' }, drawPic () { let canvas = document.getElementById('s-canvas') let ctx = canvas.getContext('2d') ctx.textBaseline = 'bottom' // 绘制背景 ctx.fillStyle = '#e6ecfd' ctx.fillRect(0, 0, this.contentWidth, this.contentHeight) // 绘制文字 for (let i = 0; i < this.identifyCode.length; i++) { this.drawText(ctx, this.identifyCode[i], i) } this.drawLine(ctx) this.drawDot(ctx) }, drawText (ctx, txt, i) { ctx.fillStyle = this.randomColor(50, 160) // 随机生成字体颜色 ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei' // 随机生成字体大小 let x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1)) let y = this.randomNum(this.fontSizeMax, this.contentHeight - 5) var deg = this.randomNum(-30, 30) // 修改坐标原点和旋转角度 ctx.translate(x, y) ctx.rotate(deg * Math.PI / 180) ctx.fillText(txt, 0, 0) // 恢复坐标原点和旋转角度 ctx.rotate(-deg * Math.PI / 180) ctx.translate(-x, -y) }, drawLine (ctx) { // 绘制干扰线 for (let i = 0; i < 4; i++) { ctx.strokeStyle = this.randomColor(100, 200) ctx.beginPath() ctx.moveTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight)) ctx.lineTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight)) ctx.stroke() } }, drawDot (ctx) { // 绘制干扰点 for (let i = 0; i < 30; i++) { ctx.fillStyle = this.randomColor(0, 255) ctx.beginPath() ctx.arc(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight), 1, 0, 2 * Math.PI) ctx.fill() } } }, watch: { identifyCode () { this.drawPic() } }, mounted () { this.drawPic() } } </script>
2.父组件
前端生成验证码的校验是自己生成验证码,用户输入的值和生成的验证码字符串进行比对校验的,校验没有走后端,在真正发送请求到后端的时候也是不将验证码传给后台的。
<template> <div slot="content" class="reg-body"> <div class="main-content"> <el-form ref="form" :model="form" :rules="rules" label-width="125px" label-position="left"> <el-form-item label="验证码" class="my-item" prop="code"> <el-input v-model.trim="form.code" placeholder="请输入正确的验证码" size="small" style="width: 200px " /> <span class="login-code" style="position: absolute; right: 0; top: 4px; left: 257px"> <Identify :identifyCode="identifyCode"></Identify> </span> <span class="el-icon-refresh-right" style="position: absolute; left: 394px; top: 13px; cursor: pointer" @click="refreshCode" /> </el-form-item> </el-form> <div style="text-align: center"> <el-button v-if="form.agreement" style="background:#6BC6A1; color: white; border-radius:2px; width: 200px; height: 30px; line-height: 5px; border: none;margin-bottom: 10px" @click="submitForm()" :loading="loading" >提交</el-button> </div> </div> </div> </template> <script> import Identify from "./identify"; export default { name: "Reg", mixins: [region], components: {Identify }, data() { return { formSetting: { contentWidth: 340, }, form: { logoUrl: "", licenseUrl: "", description: [], account: "", name: "", }, code:this.$route.query.code, identifyCodes: "1234567890abcdefjhijklinopqrsduvwxyz", identifyCode: "", picList: [], props: { label: "name", value: "id", children: "children" }, rules: { code: [{ required: true, message: "请输入验证码", trigger: "change" }], }, formList: [], }; }, created() { // this.getAllDict() }, mounted() { this.getRegion(); // 初始化验证码 this.identifyCode = ""; this.makeCode(this.identifyCodes, 4); localStorage.setItem("code", this.code); }, methods: { openHtml() { this.visible = true; }, //刷新验证码 refreshCode() { this.identifyCode = ""; this.makeCode(this.identifyCodes, 4); }, //生成验证上的随机数,验证码中的数从identifyCodes中取, makeCode(o, l) { for (let i = 0; i < l; i++) { this.identifyCode += this.identifyCodes[ this.randomNum(0, this.identifyCodes.length) ]; } }, //生成随机数,这里是生成 //Math.random()方法返回大于等于0小于1的一个随机数 //随机数 = Math.floor(Math.random() * 可能的总数 + 第一个可能的值) randomNum(min, max) { return Math.floor(Math.random() * (max - min) + min); }, // 提交表单 submitForm() { this.$refs["form"].validate((valid) => { if (valid) { if (this.loading) { return; } this.loading = true; this.submit(); } else { return false; } }); }, submit: async function () { if (this.form.code.toLowerCase() !== this.identifyCode.toLowerCase()) { this.$msg({ type: "error", message: "请填写正确验证码" }); this.refreshCode(); this.loading = false; return; } else { //验证码校验成功就可以调接口提交表单了 }, }, }; </script>
二、后端生成图片验证码
后台思路很,利用BufferedImage类创建一张图片,再用Graphics对图片进行绘制(生成随机字符,添加噪点,干扰线)即可。
package com.hengtiansoft.gxrc.base.util; import com.hengtiansoft.gxrc.common.constant.MagicNumConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.imageio.ImageIO; import java.awt.Font; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.Random; @Slf4j @Component public class ImgCaptchaUtil { private Random random = new Random(); /** * 验证码的宽 */ private final int width = 160; /** * 验证码的高 */ private final int height = 40; /** * 验证码的干扰线数量 */ private final int lineSize = 30; /** * 验证码词典 */ private final String randomString = "0123456789abcdefghijklmnopqrstuvwxyz"; /** * 获取字体 * @return */ private Font getFont() { return new Font("Times New Roman", Font.ROMAN_BASELINE, MagicNumConstant.FORTY); } /** * 获取颜色 * @param fc * @param bc * @return */ private Color getRandomColor(int fc, int bc) { int fcc = Math.min(fc, MagicNumConstant.TWO_HUNDRED_FIFTY_FIVE); int bcc = Math.min(bc, MagicNumConstant.TWO_HUNDRED_FIFTY_FIVE); int r = fcc + random.nextInt(bcc - fcc - MagicNumConstant.SIXTEEN); int g = fcc + random.nextInt(bcc - fcc - MagicNumConstant.FOURTEEN); int b = fcc + random.nextInt(bcc - fcc - MagicNumConstant.TWELVE); return new Color(r, g, b); } /** * 绘制干扰线 * @param g */ private void drawLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(MagicNumConstant.TWENTY); int yl = random.nextInt(MagicNumConstant.TEN); g.drawLine(x, y, x + xl, y + yl); } /** * 获取随机字符 * @param num * @return */ private String getRandomString(int num) { int number = num > 0 ? num : randomString.length(); return String.valueOf(randomString.charAt(random.nextInt(number))); } /** * 绘制字符串 * @param g * @param randomStr * @param i * @return */ private String drawString(Graphics g, String randomStr, int i) { g.setFont(getFont()); g.setColor(getRandomColor(MagicNumConstant.ONE_HUNDRED_EIGHT, MagicNumConstant.ONE_HUNDRED_NINETY)); String rand = getRandomString(random.nextInt(randomString.length())); String randomString = randomStr + rand; g.translate(random.nextInt(MagicNumConstant.THREE), random.nextInt(MagicNumConstant.SIX)); g.drawString(rand, MagicNumConstant.FORTY * i + MagicNumConstant.TEN, MagicNumConstant.TWENTY_FIVE); return randomString; } /** * 生成随机图片,返回 base64 字符串 * @param * @return */ public Map<String, String> getImgCodeBaseCode(int length) { Map<String, String> result = new HashMap<>(); // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics(); g.fillRect(0, 0, width, height); // 获取颜色 g.setColor(getRandomColor(MagicNumConstant.ONE_HUNDRED_FIVE, MagicNumConstant.ONE_HUNDRED_EIGHTY_NINE)); // 获取字体 g.setFont(getFont()); // 绘制干扰线 for (int i = 0; i < lineSize; i++) { drawLine(g); } // 绘制随机字符 String randomCode = ""; for (int i = 0; i < length; i++) { randomCode = drawString(g, randomCode, i); } g.dispose(); result.put("imgCode", randomCode); String base64Code = ""; try { //返回 base64 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", bos); byte[] bytes = bos.toByteArray(); Base64.Encoder encoder = Base64.getEncoder(); base64Code = encoder.encodeToString(bytes); } catch (Exception e) { log.debug(e.getMessage()); } result.put("data", "data:image/png;base64," + base64Code); return result; } }
后台生成图片base64,和一个唯一的key(通过这个key判断是哪张图片),后台可以通过接口传给前端图片base64和key,前端输入验证码,传给后台key和验证码去校验验证。
package com.hengtiansoft.gxrc.base.service.impl; import com.hengtiansoft.gxrc.base.service.ImgCaptchaService; import com.hengtiansoft.gxrc.base.util.ImgCaptchaUtil; import com.hengtiansoft.gxrc.common.constant.MagicNumConstant; import com.hengtiansoft.gxrc.common.entity.exception.BusinessException; import com.hengtiansoft.gxrc.common.redis.RedisOperation; import com.hengtiansoft.gxrc.common.util.UUIDUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.Map; /** * @Description: * @Author: wu * @CreateDate: 2020/11/11 17:17 */ @Service public class ImgCaptchaServiceImpl implements ImgCaptchaService { private static final String IMG_CAPTCHA = "imgCaptcha:"; @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private ImgCaptchaUtil imgCaptchaUtil; @Override public Map<String, String> getImgCaptcha() { RedisOperation redisOperation = new RedisOperation(redisTemplate); Map<String, String> map = imgCaptchaUtil.getImgCodeBaseCode(MagicNumConstant.FOUR); String uuid = UUIDUtils.createUUID(); redisOperation.set(IMG_CAPTCHA + uuid, map.get("imgCode")); redisOperation.expire(IMG_CAPTCHA + uuid, MagicNumConstant.THIRTY_THOUSAND); map.remove("imgCode"); map.put("key", uuid); return map; } @Override public void checkImgCaptcha(String code, String key) { RedisOperation redisOperation = new RedisOperation(redisTemplate); String captcha = redisOperation.get(IMG_CAPTCHA + key); if (ObjectUtils.isEmpty(captcha) || !StringUtils.equals(captcha, code)) { throw new BusinessException("验证码错误"); } redisOperation.del(IMG_CAPTCHA + key); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
解决Can''t find variable: SockJS vue项目的问题
这篇文章主要介绍了解决Can't find variable: SockJS vue项目的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-09-09vue element-ui的table列表中展示多张图片(可放大)效果实例
这篇文章主要给大家介绍了关于vue element-ui的table列表中展示多张图片(可放大)效果的相关资料,文中通过代码示例介绍的非常详细,需要的朋友可以参考下2023-08-08Vue 2.0+Vue-router构建一个简单的单页应用(附源码)
这篇文章主要给大家介绍了基于Vue 2.0+Vue-router构建了一个简单的单页应用,文中通过实例介绍的非常详细,并在文末给出了源码下载,需要的朋友可以下载学习参考,下面来一起看看吧。2017-03-03
最新评论