springboot 项目整合easy-captcha验证码功能

news/2024/4/30 2:41:40
效果

1、验证码使用easy-captcha,在pom文件增加依赖
	<!-- google 验证码 --><dependency><groupId>com.github.whvcse</groupId><artifactId>easy-captcha</artifactId></dependency>
2、增加获取kaptcha的ctrl
package com.*.*.system.controller;import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;/*** @Description* @auther zxf* @date 29/3/2024 上午 8:49*/
@RestController
@RequestMapping("kaptcha")
public class KaptchaController {@GetMapping("/getKaptcha")public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{httpServletResponse.setHeader("Cache-Control","no-store");httpServletResponse.setHeader("Pragma","no-cache");httpServletResponse.setDateHeader("Expires",0);httpServletResponse.setContentType("image/gif");//生成验证码对象,三个参数分别是宽、高、位数SpecCaptcha captcha = new SpecCaptcha(100, 38, 4);//设置验证码的字符类型为数字和字母混合captcha.setCharType(Captcha.TYPE_ONLY_NUMBER);// 设置内置字体captcha.setCharType(Captcha.FONT_1);//验证码存入sessionhttpServletRequest.getSession().setAttribute("kaptcha",captcha.text().toLowerCase());//输出图片流captcha.out(httpServletResponse.getOutputStream());}public String verify(@RequestParam("code") String code, HttpSession session){if (!StringUtils.hasLength(code)){return "验证码不能为空";}String kaptchaCode = session.getAttribute("kaptcha")+"";if (!StringUtils.hasLength(kaptchaCode)||!code.toLowerCase().equals(kaptchaCode)){return "验证码错误";}return "验证成功";}
}
3、前台
<a-form-item><a-inputsize="large"style="width: 80%"placeholder="请输入验证码"v-decorator="['kaptcha',{rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]" type="text"><a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/></a-input><img alt="验证码" style="float: right" width="65px" height="40px" :src="kaptcha" @click="changekaptcha"/>
</a-form-item>data里配置:
kaptcha: window.location.origin+"/kaptcha/getKaptcha",更改验证码方法
changekaptcha(){this.kaptcha =this.kaptcha+'?d='+new Date().getTime();}
3.增加filter
package com.*.*.*.*.config;import com.alibaba.fastjson.JSONObject;
import com.gc.common.base.message.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;/*** @Description* @auther zxf* @date 1/4/2024 下午 3:05*/
@Slf4j
@Configuration
public class CaptchaFilter implements Filter {private static final String CODE_ANT_URL = "auth/login";private static final String CAPTCHA_SESSION_KEY = "kaptcha";private static final String CAPTCHA_PARAM_NAME = "kaptcha";//请求路径匹配@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("init()......");}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request =  (HttpServletRequest)servletRequest;HttpServletResponse response = (HttpServletResponse)servletResponse;String url = request.getRequestURL().toString();//判断请求路径是否是登录路径if(!url.contains(CODE_ANT_URL)){filterChain.doFilter(request, response);return;}HttpSession session = request.getSession(false);if (session != null) {//拿到session中存放的 captcha 属性String captcha = (String) session.getAttribute(CAPTCHA_SESSION_KEY);if (captcha == null) {returnResult(response, "验证码已过期,请重新获取。");return;}//获取输入的验证码信息String inputCaptcha = request.getParameter(CAPTCHA_PARAM_NAME);if (inputCaptcha == null || !captcha.equals(inputCaptcha.trim())) {returnResult(response, "验证码错误,请重新输入。");return;}} else {returnResult(response, "无法验证验证码,因为HTTP会话不存在");return;}//判断令牌是否存在,如果不存在则返回错误结果filterChain.doFilter(request,response);}private void returnResult(HttpServletResponse response, String s) throws IOException {Result responseResult = Result.failure(s);//把Result对象转换为JSON格式字符串String json = JSONObject.toJSONString(responseResult);response.setContentType("application/json;charset=utf-8");//将json字符串返回给页面response.getWriter().write(json);}@Overridepublic void destroy() {System.out.println("destroy()......");}
}

spring security config中设置优先访问filter

  @Overrideprotected void configure(HttpSecurity http) throws Exception {//增加filterhttp.addFilterBefore(new CaptchaFilter(), UsernamePasswordAuthenticationFilter.class);super.configure(http);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.cpky.cn/p/11630.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

Dapr(一) 基于云原生了解Dapr

(这期先了解Dapr&#xff0c;之后在推出如何搭建Dapr&#xff0c;以及如何使用。Dapr(二) 分布式应用运行时搭建及服务调用--Dapr(二) 分布式应用运行时搭建及服务调用-CSDN博客) 目录 引言&#xff1a; Service Mesh定义 Service Mesh解决的痛点 Istio介绍 Service Mes…

vscode安装通义灵码

作为vscode的插件&#xff0c;直接使用 通义灵码-灵动指间&#xff0c;快码加编&#xff0c;你的智能编码助手 通义灵码&#xff0c;是一款基于通义大模型的智能编码辅助工具&#xff0c;提供行级/函数级实时续写、自然语言生成代码、单元测试生成、代码注释生成、代码解释、研…

用html实现在页面底部养鱼的效果

<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>在网页底部养鱼</title><link rel"stylesheet" href"./style.css"> </head> <body> <div id"fi…

Redis -- 缓存雪崩问题

缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机&#xff0c;导致大量请求到达数据库&#xff0c;带来巨大压力。 可能原因 : 同一时间大量的key到期 ; 解决方案&#xff1a; 给不同的Key的TTL添加随机值 利用Redis集群提高服务的可用性 给缓存业务添加降…

电脑上音频太多,播放速度又不一致,如何批量调节音频播放速度?

批量调节音频速度是现代音频处理中的一个重要环节&#xff0c;尤其在音乐制作、电影剪辑、有声书制作等领域&#xff0c;它能够帮助制作者快速高效地调整音频的播放速度&#xff0c;从而满足特定的制作需求。本文将详细介绍批量调节音频速度的方法、技巧和注意事项&#xff0c;…

Windows 2008虚拟机安装、安装VM Tools、快照和链接克隆、添加硬盘修改格式为GPT

一、安装vmware workstation软件 VMware workstation的安装介质&#xff0c;获取路径&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1AUAw_--yjZAUPbsR7StOJQ 提取码&#xff1a;umz1 所在目录&#xff1a;\vmware\VMware workstation 15.1.0 1.找到百度网盘中vmwa…