随着网络安全威胁日益严峻,验证码已成为网站保护账户安全的重要手段之一。本文将详细介绍如何在Spring Boot项目中集成谷歌Captcha验证码,包括引入依赖、配置类的编写、放行安全配置以及验证码的生成与校验等关键步骤。
一、引入依赖
首先,在项目的pom.xml
文件中添加Kaptcha验证码的依赖:
<!-- 谷歌 Captcha验证码依赖 -->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
二、配置类
接下来,创建一个配置类CaptchaConfig
来初始化验证码生成器:
/**
* Captcha验证码配置类
*/
@Configuration
public class CaptchaConfig {
@Bean
public DefaultKaptcha defaultKaptcha() {
// 验证码生成器
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
// 配置
Properties properties = new Properties();
// 是否有边框
properties.setProperty("kaptcha.border","yes");
// 设置边框颜色
properties.setProperty("kaptcha.border.color","105,179,90");
// 验证码
properties.setProperty("kaptcha.session.code","code");
// 验证码文本字符颜色,默认为黑色
properties.setProperty("kaptcha.textproducer.font.color","blue");
// 设置字体样式
properties.setProperty("kaptcha.textproducer.font.names","宋体,楷体,微软雅黑");
// 字体大小,默认为40
properties.setProperty("kaptcha.textproducer.font.size","30");
// 字符长度,默认为5
properties.setProperty("kaptcha.textproducer.char.length","4");
// 字符间距,默认为2
properties.setProperty("kaptcha.textproducer.char.space","4");
// 验证码图片宽度,默认为200
properties.setProperty("kaptcha.iamge.width","100");
// 验证码图片高度,默认为40
properties.setProperty("kaptcha.iamge.height", "40");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
三、放行安全配置
如果项目当中集成了security安全框架,那么为了确保验证码相关请求能够正常访问,需要在WebSecurityConfigurerAdapter
中配置放行规则:
/*
configure(HttpSecurity http)方法可以设置放行资源
configure(WebSecurity web)方法也可以设置放行资源,
这里configure(HttpSecurity http)配置拦截所有资源,配置jwt拦截器 以及添加自定义未授权和未登录结果返回的处理器
所以此处使用configure(WebSecurity web)方法放行资源使代码结构分明
* */
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(
"/websocket/**",
"/login",
"/logout",
"/css/**",
"/js/**",
"/img/**",
"/fonts/**",
"/index.html",
//放行swagger2的资源
"favicon.ico",
"/doc.html",
"/webjars/**",
"/swagger-resources/**",
"/v2/api-docs/**",
//放行访问图形验证码controller
"/captcha",
"/ws/**");
}
四、验证码生成控制器
创建一个控制器类CaptchaController
,用于生成验证码图片:
/**
图形验证码的controller层
*/
@RestController
public class CaptchaController {
@Autowired
private DefaultKaptcha defaultKaptcha;
@ApiOperation(value = "验证码")
@GetMapping(value = "/captcha",produces = "image/jpeg")
public void captcha(HttpServletRequest request, HttpServletResponse response) {
// 定义response输出类型为image/jpeg类型
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 text = defaultKaptcha.createText(); // 获取验证码文本内容
System.out.println("验证码文本内容:" + text);
request.getSession().setAttribute("captcha", text);
BufferedImage image = defaultKaptcha.createImage(text); // 根据文本内容创建图形验证码
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
ImageIO.write(image, "jpg", outputStream); // 输出流输出图片,格式为jpg
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != outputStream) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 生成验证码结束
}
}
五、验证码校验
在实际业务逻辑中,需要验证用户提交的验证码是否正确。可以通过以下方式实现:
// 校验验证码是否正确
String captcha = (String) request.getSession().getAttribute("captcha");
if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
return RespBean.error("验证码错误,请重新输入");
}
当然,存储验证码方式很多,常用的是集成redis进行存储,笔者这里只是简单实现一下验证码的功能。
六、最后
通过上述步骤,我们成功地在Spring Boot项目中集成了谷歌Captcha验证码。当然上面的代码示例仅作为开发者的参考示例,由于开发环境各不相同,往往会遇到各种各样的问题。
集成验证码功能,这不仅提高了系统的安全性,也为用户体验带来了积极影响。无论是新项目还是现有系统的升级,此方案都能提供可靠的支持。未来,随着技术的进步和安全需求的变化,验证码的设计与实现也将不断完善和发展。