引言

验证码的作用:

  • 防止自动化代码(爬虫,恶意脚本)来直接发送请求
  • 确认用户信息的真实性

1. pom依赖

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency><!-- kaptcha验证码-->
<dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
</dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.19</version>
</dependency>

2. 准备

公共返回值:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {private String code;private String msg;private T data;}

公共返回值相关方法:(只用到一两个,但在这里也写上自己项目中使用到的)

public class ResultUtil {public static<T> Result<T> success(T data) {Result<T> result = new Result<>();result.setCode("200");result.setMsg("success");result.setData(data);return result;}public static<T> Result<T> success() {return success(null);}public static<T> Result<T> success(String msg, T data) {Result<T> result = new Result<>();result.setCode("200");result.setMsg(msg);result.setData(data);return result;}public static<T> Result<T> success(String msg) {Result<T> result = new Result<>();result.setCode("200");result.setMsg(msg);return result;}public static<T> Result<T> fail(String code, String msg) {Result<T> result = new Result<>();result.setCode(code);result.setMsg(msg);result.setData(null);return result;}public static<T> Result<T> fail() {Result<T> result = new Result<>();result.setCode("500");result.setMsg("系统异常");result.setData(null);return result;}public static<T> Result<T> fail(T data) {Result<T> result = new Result<>();result.setData(null);return result;}public static<T> Result<T> fail(ResultEnum resultEnum) {Result<T> result = new Result<>();result.setCode(resultEnum.getCode());result.setMsg(resultEnum.getMsg());result.setData(null);return result;}}

Redis配置:(不是必要的,如果不配置的话在Redis里看到的是一堆类似乱码的序列)

@Configuration
public class RedisConfig {/*** RedisTemplate配置*/@Beanpublic RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {// 设置序列化Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);// 配置redisTemplateRedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(lettuceConnectionFactory);RedisSerializer<?> stringSerializer = new StringRedisSerializer();// key序列化redisTemplate.setKeySerializer(stringSerializer);// value序列化redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// Hash key序列化redisTemplate.setHashKeySerializer(stringSerializer);// Hash value序列化redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}}

3. 整合

最后的效果是以加减乘除的方式,让用户输入等式

验证码文本生成器

public class KaptchaTextCreator extends DefaultTextCreator {private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");   //  因为验证码最后的效果图是以加减乘除的方式,让用户输入结果,所以这里只能是数字private SecureRandom random = new SecureRandom(); // /dev/urandom 作为熵池,非阻塞的随机数生成器,重复使用熵池中的数据以产生伪随机数据,不会产生阻塞,适用生成较低强度的伪随机数。public KaptchaTextCreator() throws NoSuchAlgorithmException {}@Overridepublic String getText() {Integer result = 0;int x = this.random.nextInt(10);int y = this.random.nextInt(10);StringBuilder suChinese = new StringBuilder();int randomoperands = (int) Math.round(random.nextDouble() * 2);if (randomoperands == 0) {result = x * y;suChinese.append(CNUMBERS[x]);suChinese.append("*");suChinese.append(CNUMBERS[y]);} else if (randomoperands == 1) {if (!(x == 0) && y % x == 0) {result = y / x;suChinese.append(CNUMBERS[y]);suChinese.append("/");suChinese.append(CNUMBERS[x]);} else {result = x + y;suChinese.append(CNUMBERS[x]);suChinese.append("+");suChinese.append(CNUMBERS[y]);}} else if (randomoperands == 2) {if (x >= y) {result = x - y;suChinese.append(CNUMBERS[x]);suChinese.append("-");suChinese.append(CNUMBERS[y]);} else {result = y - x;suChinese.append(CNUMBERS[y]);suChinese.append("-");suChinese.append(CNUMBERS[x]);}} else {result = x + y;suChinese.append(CNUMBERS[x]);suChinese.append("+");suChinese.append(CNUMBERS[y]);}suChinese.append("=?@" + result);return suChinese.toString();}}

以流的方式生成验证码,并将生成的验证码的值存储到Redis

@Component
@RequiredArgsConstructor
public class CaptchaHandler implements HandlerFunction<ServerResponse> {private final Producer producer;private final StringRedisTemplate redisTemplate;@Overridepublic Mono<ServerResponse> handle(ServerRequest serverRequest) {// 生成验证码String capText = producer.createText();String capStr = capText.substring(0, capText.lastIndexOf("@"));String code = capText.substring(capText.lastIndexOf("@") + 1);BufferedImage image = producer.createImage(capStr);// 缓存验证码至RedisString uuid = IdUtil.simpleUUID();redisTemplate.opsForValue().set(RedisConstant.VALIDATE_CODE_PREFIX + uuid, code, 60, TimeUnit.SECONDS);// 转换流信息写出FastByteArrayOutputStream os = new FastByteArrayOutputStream();try {ImageIO.write(image, "jpg", os);} catch (IOException e) {return Mono.error(e);}Map<String, String> resultMap = new HashMap();resultMap.put("uuid", uuid);resultMap.put("img", Base64.encode(os.toByteArray()));return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(ResultUtil.success(resultMap)));}}

Kaptcha 验证码配置

@Configuration
public class CaptchaConfig {@Bean(name = "captchaProducerMath")public DefaultKaptcha captchaProducerMath() {DefaultKaptcha defaultKaptcha = new DefaultKaptcha();Properties properties = new Properties();// 是否有边框 默认为true 我们可以自己设置yes,noproperties.setProperty("kaptcha.border", "yes");// 边框颜色 默认为Color.BLACKproperties.setProperty("kaptcha.border.color", "214,216,223");// 验证码文本字符颜色 默认为Color.BLACKproperties.setProperty("kaptcha.textproducer.font.color", "blue");// 验证码图片宽度 默认为200properties.setProperty("kaptcha.image.width", "100");// 验证码图片高度 默认为50properties.setProperty("kaptcha.image.height", "38");// 验证码文本字符大小 默认为40properties.setProperty("kaptcha.textproducer.font.size", "25");// KAPTCHA_SESSION_KEYproperties.setProperty("kaptcha.session.key", "kaptchaCodeMath");// 验证码文本生成器properties.setProperty("kaptcha.textproducer.impl", "com.csxy.Kaptcha.creator.KaptchaTextCreator");// 验证码文本字符间距 默认为2properties.setProperty("kaptcha.textproducer.char.space", "5");// 验证码文本字符长度 默认为5properties.setProperty("kaptcha.textproducer.char.length", "6");// 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1,// fontSize)properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier");// 验证码噪点颜色 默认为Color.BLACKproperties.setProperty("kaptcha.noise.color", "white");// 干扰实现类properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");// 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple// 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy// 阴影com.google.code.kaptcha.impl.ShadowGimpyproperties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");Config config = new Config(properties);defaultKaptcha.setConfig(config);return defaultKaptcha;}}

图片验证码路由

@Configuration
public class CaptchaRouter {@Beanpublic RouterFunction<ServerResponse> routerFunction(CaptchaHandler captchaHandler) {return RouterFunctions.route(RequestPredicates.GET("/captcha").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),captchaHandler::handle);}}

4. 前端(Vue)

HTML代码

<img :src="base64Captcha" @click="handleCaptchaGenerate" height="38px"/>

JS代码

export default {data() {return {verificationcode: undefined,  //  验证码uuid: undefined,  //  验证码的唯一标识base64Captcha: undefined,  //  验证码地址}},methods: {async handleCaptchaGenerate(){  //  生成图片验证码var that = this;getCaptcha().then(response => {const {img, uuid} = response.datathat.base64Captcha = "data:image/gif;base64," + imgthat.uuid = uuid;})}},created() {var that = this;that.handleCaptchaGenerate();}}

效果图

Gateway + Redis整合Kaptcha验证码相关推荐

  1. Springboot整合kaptcha验证码

    Springboot整合kaptcha验证码 01.通过配置类来配置kaptcha 01-01.添加kaptcha的依赖: <!-- kaptcha验证码 --> <dependen ...

  2. 全网最新Redis结合Kaptcha实现验证码功能篇一(前后端分离)

    文章目录 前言 一.导入Kaptcha依赖包 二.使用步骤 1.验证码配置类 2.获取验证码接口 3.Vue页面 4.去除背景 5.自定义背景以及验证码随机规则 总结 前言 Google 的 kapt ...

  3. 谷歌了java集成开发_Spring整合Kaptcha谷歌验证码工具的开发步骤

    开发步骤: 1.加入依赖 com.google.code.kaptcha kaptcha 2.3 国内镜像无法下载该依赖,需要手动通过jar包在本地仓库安装一个依赖. 安装命令: mvn instal ...

  4. Springboot整合kaptcha实现验证码

    验证码的作用 防止恶意破解密码.刷票.论坛灌水.刷页. 有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登录尝试,实际上使用验证码是现在很多网站通行的方式(比如招商银行的网上个人银 ...

  5. kaptcha验证码实现,配合spring boot使用

    一.kaptcha介绍 Kaptcha是谷歌放在github上的一个验证码jar包,我们可以简单配置属性实现验证码的验证功能. kaptcha参数设置如下所示: Constant 描述 默认值 kap ...

  6. kaptcha验证码组件使用简介

    kaptcha验证码组件使用简介 Kaptcha是一个基于SimpleCaptcha的验证码开源项目. 官网地址:http://code.google.com/p/kaptcha/ kaptcha的使 ...

  7. SpringMVC+redis整合

    2019独角兽企业重金招聘Python工程师标准>>> SpringMVC+redis整合 在网络上有一个很多人转载的springmvc+redis整合的案例,不过一直不完整,也是被 ...

  8. kaptcha 验证码在spring mvc 中的使用

    转自:http://ttaale.iteye.com/blog/808719 kaptcha 是一个非常实用的验证码生成工具.有了它,你可以生成各种样式的验证码,因为它是可配置的.kaptcha工作的 ...

  9. SringBoot+Redis整合

    缓存使用设计 连接缓存 查询缓存 如果缓存中没有再到MySQL中查询 mysql查询结果放入redis Redis整合步骤 将redis整合到项目中(redis+spring) 引入pom依赖信息(所 ...

最新文章

  1. 华北电力大学保定校区计算机专业,华北电力大学保定校区本科计算机科学与技术_华北电力大学保定校区本科计算机科学与技术简介-查字典学校网...
  2. C++语言基础(20)-模板的非类型参数
  3. 算法提高课-图论-负环-AcWing 361. 观光奶牛:spfa判正环、负环、01分数规划、二分
  4. 新闻视频 36:整合首页 用到 Repeater 主要用gridview /gridview去掉边框用到 BorderWidth=”0” inner join和 left...
  5. 怎么使用Docker搭建PHP开发环境呢?
  6. python序列元素的编号称为_Python序列
  7. AngularJS-demo - 常用命令、内置服务、自定义服务、继承
  8. 推荐8个最佳的jQuery移动开发插件
  9. 清华大学计算机科学与技术专业设置,清华大学计算机科学与技术专业介绍
  10. unix bsd linux shell bash GNU之间的联系,歪讲Linux(一)
  11. html中如何把两行合并单元格,css合并两列单元格内容
  12. XXL分布式任务调度平台
  13. 设备驱动中的并发控制-自旋锁
  14. Python使用pip安装报错ModuleNotFoundError: No module named ‘pkg_resources‘的解决方法
  15. 服务器多个cpu的作用,服务器多核CPU是什么?多核CPU有什么用?
  16. java 上传文件-生成文件首页缩略图 生成pdf 抓取图片
  17. bp神经网络和cnn神经网络,bp神经网络与cnn区别
  18. rocketmq DLedger主从自动切换
  19. matlab编码流程图,高手来帮我看看该怎么画这些代码的流程图
  20. C#中操作IIS 7.0

热门文章

  1. 什么是jedis及jedis的测试
  2. WPF制作带圆角的文本框的两种方法
  3. HashMap转JSON字符串,JSON字符串转HashMap
  4. ChatGPT的一些有趣用法
  5. 苹果iPhone X内置定制化神经引擎处理器
  6. 统计推断——假设检验——卡方检验
  7. 3D Xpoint技术与NAND Flash、3D NAND Flash及DRAM的比较
  8. Java中toString方法作用
  9. 【19调剂】成都理工大学招收计算机、数学和物理化学等相关专业的工科研究生,欢迎莘莘学子报考...
  10. AttributeError: module ‘seaborn‘ has no attribute ‘histplot‘