springboot项目使用redis进行验证码验证

该教程介绍了如何在SpringBoot应用中使用Kaptcha生成验证码,并结合Redis进行存储和验证。首先,添加Kaptcha依赖,然后配置Redis数据库。在控制器中,创建验证码并存储到Redis,同时发送给客户端。在验证阶段,从Redis读取验证码并与用户输入对比,完成验证过程。
摘要由CSDN通过智能技术生成

第一步引入依赖

        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

第二步下载并配置redis数据库,了解redis一些基本知识

(46条消息) Redis入门及Spring整合redis_大磊程序员(轻大)的博客-CSDN博客_redis基础springicon-default.png?t=M85Bhttps://blog.csdn.net/m0_59860403/article/details/122800672?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166640692816782428655418%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=166640692816782428655418&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-122800672-null-null.nonecase&utm_term=redis&spm=1018.2226.3001.4450

第三步控制层处理

读取验证码

  @Autowired
    private Producer captchaProducer;
    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
                session.setAttribute("kaptcha", capText);
        System.out.println(session.getAttribute("kaptcha"));
        //将验证码存储到redis数据库中
        redisTemplate.opsForValue().set("kaptchaKsy",capText,60, TimeUnit.SECONDS );
        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }

    }

调用Producer 得到验证码,并且存储到redis数据库中,可以设置存储时间等一些参数。

验证验证码

//登录
    @ApiOperation("用户登录")
    @PostMapping("/login/{code}")
    public R login(@PathVariable("code")String code, User user1,HttpSession session){
        User user = userService.login(user1);
        if(user==null){
            R.error("用户不存在");
        }
        //比较验证码
       String code2= (String) redisTemplate.opsForValue().get("kaptchaKsy");
        System.out.println(code2);
        boolean codeFlag=code.equalsIgnoreCase(code2);
        if(!codeFlag){
            return R.error("验证码错误");
        }
        if(user1!=null){

            return R.ok().put("user",user);
        }else {
            return R.error("登陆失败!请检查用户名或密码");
        }
    }

调用redisTemplate进行读取验证码,进而验证

到此springboot验证码验证的教程已经完毕,感兴趣的朋友们可以点个赞加个关注,我们一块学习java

Redis可以用来实现短信验证码功能,具体步骤如下: 1. 生成验证码使用随机数生成生成一个6位数字的验证码,并将其存储到Redis中,以手机号作为key,验证码作为value,同时设置过期时间为5分钟。 2. 发送验证码:将验证码发送到用户手机上,可以使用短信平台或者第三方SDK来实现。 3. 验证验证码:用户输入验证码后,从Redis中读取对应手机号的验证码,与用户输入的验证码进行比对,如果一致则验证通过,否则验证失败。 以下是使用Redis实现短信验证码的代码示例(使用Python语言): ``` import redis import random import time # 连接Redis r = redis.Redis(host='localhost', port=6379, db=0) # 生成验证码 def generate_verification_code(phone): verification_code = random.randint(100000, 999999) r.set(phone, verification_code, ex=300) # 设置过期时间为5分钟 return verification_code # 验证验证码 def verify_verification_code(phone, verification_code): stored_code = r.get(phone) if stored_code is None: return False if int(stored_code) != verification_code: return False r.delete(phone) # 验证通过后删除验证码 return True # 示例代码 phone = '13812345678' code = generate_verification_code(phone) print(code) time.sleep(2) # 模拟发送验证码到用户手机上的过程 result = verify_verification_code(phone, code) print(result) ``` 需要注意的是,由于Redis是内存数据库,如果服务器重启或者Redis进程被杀死,存储在Redis中的数据会丢失,因此需要根据实际情况进行合理的持久化和备份。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大磊程序员(“hello world”)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值