栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

1、添加pom依赖
 		
        
            com.github.penggle
            kaptcha
            2.3.2
        
        

		
        
            org.springframework.boot
            spring-boot-starter-data-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 {
    
    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 redisTemplate;

    
    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);
    }

    
    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;
        }
    }
    
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }

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

    
    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("成功");
     }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/583872.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号