springboot验证码-kaptcha谷歌验证码工具

验证码,就是将一串随机产生的数字或符号,生成一幅图片,图片里加上一些干扰象素(防止OCR),由用户肉眼识别其中的验证码信息。
Maven依赖
在开发验证码功能的时候,kaptcha谷歌验证码工具,依赖。

<!--验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
<exclusions>
<exclusion>
<artifactId>javax.servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
</exclusions>
</dependency>
功能实现
最常见的验证码有两种形式,一种是字符串验证码,另一种是数字加减法验证码(如下图所示)

 

 

 

 

 

application.yml文件以及自定义验证码过滤器

在application.yml文件中增加了一个验证码的开关与验证码类型的相关配置,便于页面对验证码的类型进行切换。

shiro:
# 验证码开关
captchaEnabled: true
# 验证码类型 math 数组计算 char 字符
captchaType: math
验证码的配置是增加在了shiro节点下,那么在ShiroConfig中也就需要增加两个相应的参数并把自己的验证码过滤器配置到shiro中。

CaptchaValidateFilter.java

public class CaptchaValidateFilter extends AccessControlFilter
{
/**
* 是否开启验证码
*/
private boolean captchaEnabled = true;

/**
* 验证码类型
*/
private String captchaType = "math";

public void setCaptchaEnabled(boolean captchaEnabled){
this.captchaEnabled = captchaEnabled;
}

public void setCaptchaType(String captchaType){
this.captchaType = captchaType;
}

@Override
public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception{
request.setAttribute(ShiroConstants.CURRENT_ENABLED, captchaEnabled);
request.setAttribute(ShiroConstants.CURRENT_TYPE, captchaType);
return super.onPreHandle(request, response, mappedValue);
}

@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
throws Exception{
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 验证码禁用或不是表单提交时,允许访问
if (captchaEnabled == false || !"post".equals(httpServletRequest.getMethod().toLowerCase())){
return true;
}
return validateResponse(httpServletRequest, httpServletRequest.getParameter(ShiroConstants.CURRENT_VALIDATECODE));
}

public boolean validateResponse(HttpServletRequest request, String validateCode){
Object obj = ShiroUtils.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
String code = String.valueOf(obj != null ? obj : "");
if (StringUtils.isEmpty(validateCode) || !validateCode.equalsIgnoreCase(code)){
return false;
}
return true;
}

@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception{
request.setAttribute(ShiroConstants.CURRENT_CAPTCHA, ShiroConstants.CAPTCHA_ERROR);
return true;
}
}
ShiroConfig.java

// 验证码开关
@Value("${shiro.user.captchaEnabled}")
private boolean captchaEnabled;

// 验证码类型
@Value("${shiro.user.captchaType}")
private String captchaType;

/**
* 自定义验证码过滤器
*/
@Bean
public CaptchaValidateFilter captchaValidateFilter(){
CaptchaValidateFilter captchaValidateFilter = new CaptchaValidateFilter();
captchaValidateFilter.setCaptchaEnabled(captchaEnabled);
captchaValidateFilter.setCaptchaType(captchaType);
return captchaValidateFilter;
}
登录页面

页面使用的是Thymeleaf,其中captchaType就是上面提到的在application.yml中配置的验证码类型,根据设置的类型去绘制不同的验证码。

<a href="javascript:void(0);" title="点击更换验证码">
<img th:src="@{captcha/captchaImage(type=${captchaType})}" class="imgcode" width="85%"/>
</a>
点击图片更换验证码

$(function() {
$('.imgcode').click(function() {
var url = 项目地址 + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
$(".imgcode").attr("src", url);
});
});
控制器与相关配置

CaptchaController.java

@Controller
@RequestMapping("/captcha")
public class CaptchaController extends BaseController{

@Resource(name = "captchaProducer")
private Producer captchaProducer;

@Resource(name = "captchaProducerMath")
private Producer captchaProducerMath;

/**
* 验证码生成
*/
@GetMapping(value = "/captchaImage")
public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response){

ServletOutputStream out = null;
try{

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 type = request.getParameter("type");
String capStr = null;
String code = null;
BufferedImage bi = null;
if ("math".equals(type)){
String capText = captchaProducerMath.createText();
capStr = capText.substring(0, capText.lastIndexOf("@"));
code = capText.substring(capText.lastIndexOf("@") + 1);
bi = captchaProducerMath.createImage(capStr);
}else if ("char".equals(type)){
capStr = code = captchaProducer.createText();
bi = captchaProducer.createImage(capStr);
}
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
out.flush();

}
catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (out != null){
out.close();
}
}
catch (IOException e){
e.printStackTrace();
}
}
return null;
}
}

 


CaptchaConfig.java(验证码配置)

@Configuration
public class CaptchaConfig{

@Bean(name = "captchaProducer")
public DefaultKaptcha getKaptchaBean(){
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 是否有边框 默认为true
properties.setProperty(KAPTCHA_BORDER, "yes");
// 验证码文本字符颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
// 验证码图片宽度 默认为200
properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
// 验证码图片高度 默认为50
properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
// 验证码文本字符大小 默认为40
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38");
// KAPTCHA_SESSION_KEY
properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode");
// 验证码文本字符长度 默认为5
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
// 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
// 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.WaterRipple");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}

@Bean(name = "captchaProducerMath")
public DefaultKaptcha getKaptchaBeanMath(){
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 是否有边框 默认为true
properties.setProperty(KAPTCHA_BORDER, "yes");
// 边框颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
// 验证码文本字符颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
// 验证码图片宽度 默认为200
properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
// 验证码图片高度 默认为50
properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
// 验证码文本字符大小 默认为40
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35");
// KAPTCHA_SESSION_KEY
properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath");
// 调用自己的数字加减法验证码文本生成器
properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "xxx.xxx.xxx.KaptchaTextCreator");
// 验证码文本字符间距 默认为2
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3");
// 验证码文本字符长度 默认为5
properties.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.BLACK
properties.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.ShadowGimpy
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.WaterRipple");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
KaptchaTextCreator.java(数字加减法验证码文本生成器)

public class KaptchaTextCreator extends DefaultTextCreator{

private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");

@Override
public String getText(){

Integer result = 0;
Random random = new SecureRandom();
int x = random.nextInt(10);
int y = random.nextInt(10);
StringBuilder suChinese = new StringBuilder();
int randomoperands = (int) Math.round(Math.random() * 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();
}
}

posted @ 2023-08-18 22:37  全琪俊  阅读(255)  评论(0编辑  收藏  举报