当前位置: 首页 > 编程笔记 >

实例详解Spring Boot实战之Redis缓存登录验证码

郎宏浚
2023-03-14
本文向大家介绍实例详解Spring Boot实战之Redis缓存登录验证码,包括了实例详解Spring Boot实战之Redis缓存登录验证码的使用技巧和注意事项,需要的朋友参考一下

本章简单介绍redis的配置及使用方法,本文示例代码在前面代码的基础上进行修改添加,实现了使用redis进行缓存验证码,以及校验验证码的过程。

1、添加依赖库(添加redis库,以及第三方的验证码库)

       <dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-redis</artifactId> 
</dependency> 
<dependency> 
  <groupId>cn.apiclub.tool</groupId> 
  <artifactId>simplecaptcha</artifactId> 
  <version>1.2.2</version> 
</dependency> 

2、在application.properties中添加redis的配置信息

spring.redis.database=4 
spring.redis.host=hostname 
spring.redis.password=password 
spring.redis.port=6379 
spring.redis.timeout=2000 
spring.redis.pool.max-idle=8 
spring.redis.pool.min-idle=0 
spring.redis.pool.max-active=8 
spring.redis.pool.max-wait=-1 

3、添加redis数据模版

新增RedisConfig.Java

package com.xiaofangtech.sun.config; 
import org.springframework.context.annotation.Bean; 
import org.springframework.data.redis.connection.RedisConnectionFactory; 
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 
import org.springframework.data.redis.core.RedisTemplate; 
import org.springframework.data.redis.serializer.StringRedisSerializer; 
public class RedisConfig { 
  @Bean 
  JedisConnectionFactory jedisConnectionFactory() { 
    return new JedisConnectionFactory(); 
  } 
  @Bean RedisTemplate<String, String>redisTemplate(RedisConnectionFactory factory) 
  { 
    RedisTemplate<String, String> template = new RedisTemplate<String, String>(); 
    template.setConnectionFactory(jedisConnectionFactory()); 
    template.setKeySerializer(new StringRedisSerializer()); 
    template.setValueSerializer(new StringRedisSerializer()); 
    return template; 
  } 
} 

4、redis的基本使用(缓存生成的验证码信息)

新建CaptchaModule.java,涉及redis插入操作关键代码

@Autowired 
  private RedisTemplate<String, String> redisTemplate; 
//将验证码以<key,value>形式缓存到redis 
    redisTemplate.opsForValue().set(uuid, captcha.getAnswer(), captchaExpires, TimeUnit.SECONDS); 

完整代码

package com.xiaofangtech.sunt.utils; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.util.UUID; 
import java.util.concurrent.TimeUnit; 
import javax.imageio.ImageIO; 
import javax.servlet.http.Cookie; 
import javax.servlet.http.HttpServletResponse; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.redis.core.RedisTemplate; 
import org.springframework.http.MediaType; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.ResponseBody; 
import org.springframework.web.bind.annotation.RestController; 
import cn.apiclub.captcha.Captcha; 
import cn.apiclub.captcha.backgrounds.GradiatedBackgroundProducer; 
import cn.apiclub.captcha.gimpy.FishEyeGimpyRenderer; 
@RestController 
@RequestMapping("captcha") 
public class CaptchaModule { 
  @Autowired 
  private RedisTemplate<String, String> redisTemplate; 
  private static int captchaExpires = 3*60; //超时时间3min 
  private static int captchaW = 200; 
  private static int captchaH = 60; 
  @RequestMapping(value = "getcaptcha", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE) 
  public @ResponseBody byte[] getCaptcha(HttpServletResponse response) 
  { 
    //生成验证码 
    String uuid = UUID.randomUUID().toString(); 
    Captcha captcha = new Captcha.Builder(captchaW, captchaH) 
        .addText().addBackground(new GradiatedBackgroundProducer()) 
        .gimp(new FishEyeGimpyRenderer()) 
        .build(); 
    //将验证码以<key,value>形式缓存到redis 
    redisTemplate.opsForValue().set(uuid, captcha.getAnswer(), captchaExpires, TimeUnit.SECONDS); 
    //将验证码key,及验证码的图片返回 
    Cookie cookie = new Cookie("CaptchaCode",uuid); 
    response.addCookie(cookie); 
    ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
    try { 
      ImageIO.write(captcha.getImage(), "png", bao); 
      return bao.toByteArray(); 
    } catch (IOException e) { 
      return null; 
    } 
  } 
} 

5、redis内容的获取(根据key获取验证码)

完善前面获取token的流程,在获取token的接口中添加校验验证码的流程(根据登录参数中的验证码id获取验证码内容,并与登录参数中的验证码内容进行比对)

修改JsonWebToken.java

@Autowired 
  private RedisTemplate<String, String> redisTemplate; 
//验证码校验在后面章节添加 
String captchaCode = loginPara.getCaptchaCode(); 
try { 
  if (captchaCode == null) 
  { 
    throw new Exception(); 
  } 
  String captchaValue = redisTemplate.opsForValue().get(captchaCode); 
  if (captchaValue == null) 
  { 
    throw new Exception(); 
  } 
  redisTemplate.delete(captchaCode); 
  if (captchaValue.compareTo(loginPara.getCaptchaValue()) != 0) 
  { 
    throw new Exception(); 
  } 
} catch (Exception e) { 
  resultMsg = new ResultMsg(ResultStatusCode.INVALID_CAPTCHA.getErrcode(),  
      ResultStatusCode.INVALID_CAPTCHA.getErrmsg(), null); 
  return resultMsg; 
} 

6、测试

1)请求获取验证码,可以获取到验证码图片,以及在cookie中返回缓存入redis的key值

2)查看redis,可以查看到之前缓存的key value

3)登录获取token时,添加验证码参数

如果验证码错误,返回验证码错误

验证码正确,且用户名密码正确,返回token


总结

以上所述是小编给大家介绍的实例详解Spring Boot实战之Redis缓存登录验证码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对小牛知识库网站的支持!

 类似资料:
  • 本文向大家介绍Springboot实现验证码登录,包括了Springboot实现验证码登录的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了Springboot实现验证码登录的具体代码,供大家参考,具体内容如下 因为在项目中需要使用到验证码,我总结一下在项目中如何快速解决项目需求~验证码,下面推荐给大家速上手验证码的例子。 一、编写验证码工具类 二、controller层使用 验证用户

  • 本文向大家介绍Vue实战之vue登录验证的实现代码,包括了Vue实战之vue登录验证的实现代码的使用技巧和注意事项,需要的朋友参考一下 最近一直在撸一个给大学生新生用的产品,在撸的时候有时候会发现自己力不从心,是不是我的能力下降,是不是我该放弃我的最热爱的事业了?这对我的心灵造成了巨大的伤害,所以我决定向苍老师起誓一定练好我这双手——好好写代码(想多的同学赶紧去面壁5秒钟再过来往下看)~~~ 我做

  • 本文向大家介绍Python完全识别验证码自动登录实例详解,包括了Python完全识别验证码自动登录实例详解的使用技巧和注意事项,需要的朋友参考一下 1、直接贴代码 2、控制台日志 以上这篇Python完全识别验证码自动登录实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

  • 本文向大家介绍Android开发之登录验证实例教程,包括了Android开发之登录验证实例教程的使用技巧和注意事项,需要的朋友参考一下 本文所述实例源自一个项目开发中的登录验证功能,具体的要求就是,在Android端输入用户名和密码,在服务器端验证MySQL数据库中是否有此用户,实现之前当然首要的是,如何使Android端的数据发送到服务器端,具体的实现方法如下: 服务器端:ManageServl

  • 本文向大家介绍yii2项目实战之restful api授权验证详解,包括了yii2项目实战之restful api授权验证详解的使用技巧和注意事项,需要的朋友参考一下 前言 什么是restful风格的api呢?我们之前有写过大篇的文章来介绍其概念以及基本操作。 既然写过了,那今天是要说点什么吗? 这篇文章主要针对实际场景中api的部署来写。 我们今天就来大大的侃侃那些年api遇到的授权验证问题!独

  • 本文向大家介绍Java实现LRU缓存的实例详解,包括了Java实现LRU缓存的实例详解的使用技巧和注意事项,需要的朋友参考一下 Java实现LRU缓存的实例详解 1.Cache Cache对于代码系统的加速与优化具有极大的作用,对于码农来说是一个很熟悉的概念。可以说,你在内存中new 了一个一段空间(比方说数组,list)存放一些冗余的结果数据,并利用这些数据完成了以空间换时间的优化目的,你就已经