springboot整合谷歌验证码使用redis进行存储判断

1、添加pom依赖


 		<!--        kaptcha验证码  第三方谷歌验证码 -->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>
        <!--        kaptcha验证码  第三方谷歌验证码 -->

		<!--        redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--        redis-->

2、配置redis的yaml文件

redis:
    host: ip地址
    port: 6379(一般使用该端口)
    password: 密码(最好拿引号括起来)
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 500
        min-idle: 0
    lettuce:
      shutdown-timeout: 30000

3、编写config文件

package com.twogroup.shoppingwall.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

//验证码
@Configuration
public class KaptchaConfig {
    @Bean(value = "DefaultKaptcha")
    public DefaultKaptcha getDefaultKaptcha(){
        DefaultKaptcha captchaProducer = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        properties.setProperty("kaptcha.image.width", "110");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        captchaProducer.setConfig(config);
        return captchaProducer;
    }
}

4、编写验证码的util类

package com.twogroup.shoppingwall.util;

import javax.servlet.http.HttpServletRequest;

public class CodeUtil {
    /**
     * 将获取到的前端参数转为string类型
     */
    public static String getString(HttpServletRequest request, String key) {
        try {
            String result = request.getParameter(key);
            if(result != null) {
                result = result.trim();
            }
            if("".equals(result)) {
                result = null;
            }
            return result;
        }catch(Exception e) {
            return null;
        }
    }
    /**
     * 验证码校验
     */
    public static boolean checkVerifyCode(HttpServletRequest request,String code,Object email) {
        //获取生成的验证码
        String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

        RedisUtil redisUtil = new RedisUtil();
        Object redis = redisUtil.getRedis(email );
        //获取用户输入的验证码
//        String verifyCodeActual = CodeUtil.getString(request, "verifyCodeActual");
        if(code == null ||!code.equals(redis)) {
            Result.fail("验证码错误");
            return false;
        }
        return true;
    }
}

5、编写redis的util类

package com.twogroup.shoppingwall.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class RedisUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 写入缓存
     * @param key 键
     * @param value 值
     * @return  boolean
     */
    public boolean setRedis(String key, Object value) {
        try {
             redisTemplate.opsForValue().set(key, value);
             return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /*
    获取缓存内的值
     */
    public Object getRedis(Object key){

        System.out.println("key:---->"+redisTemplate.opsForValue().get(key));
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time > 0 若 time <= 0 将设置无限期
     * @return true 成功 false 失败
     */
    public boolean setRedis(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                setRedis(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return redis
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }

        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return redis
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().decrement(key, delta);
    }
}

6、编写验证码的controller类

package com.twogroup.shoppingwall.controller;

import com.google.code.kaptcha.Constants;

import com.google.code.kaptcha.Producer;
import com.twogroup.shoppingwall.util.RedisUtil;
import com.twogroup.shoppingwall.util.Result;
import com.twogroup.shoppingwall.util.UserUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@Controller
@Api(tags = "A:生成图片验证码的controller")
public class CodeController {
    @Autowired
    private Producer captchaProducer = null;
    private RedisUtil redisUtil = new RedisUtil();

    @GetMapping("/kaptch")
    public void getKaptchaImage(String email,HttpServletRequest request, HttpServletResponse response) throws Exception {
        if(!UserUtil.emailUtil(email)){
            Result.fail("邮箱格式错误");
            return;
        }

        HttpSession session = request.getSession();
        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
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        session.setAttribute(email,email);
        session.getAttribute(email);
        //验证码存入redis
        redisUtil.setRedis(email,capText,60);
        Object redis = redisUtil.getRedis(email);
        System.out.println("验证码:"+redis);

        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}

7、验证图片验证码与用户输入的是否正确

	@GetMapping("/loginByPassword")
    public Result loginByPassword(String email, String password,HttpServletResponse response,HttpServletRequest request,String code){
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(email);

        if(!CodeUtil.checkVerifyCode(request,code,attribute)){
            return Result.fail("验证码有误!");
        }
        return Result..sucess("成功");
     }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值