使用图片验证码进行登录验证

需求:后端系统登录时使用图片验证码验证登录

效果:

使用 4 位数字加字母组合验证码登录,相关代码为:

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

@RequestMapping("/getCode")
public ResultVO getCode(HttpServletRequest request, HttpServletResponse response) {
    String imageBase64 = "";
    Map<String, String> result = new HashMap<>();
    try {
        // 定义图片大小
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 300);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        imageBase64 = "data:image/png;base64," + captcha.getImageBase64();
        String code = captcha.getCode();
        logger.info("生成的图片验正码:{}", code);
        String codeKey = UUID.randomUUID().toString();
        redisSupport.set(codeKey, captcha.getCode());
        result.put("code",imageBase64);
        result.put("codeKey", codeKey);
    } catch (Exception e) {
        logger.error("生成图片验正码异常", e);
        return new ResultVO<>(ResultVO.FAIL, "获取图片失败");
    }
    return new ResultVO<>(result, ResultVO.SUCCESS, "获取图片成功");
}

这部分代码实现的是生成图片验证码的功能,使用的是 hutool 的工具包,需要以 key-value 的形式将生成的图片和用户关联起来,所以我们将结果以 Map 的形式返回给前端。其中使用的 redisSupport 可根据实际情况进行替换,其实就是 Redis 的一个工具包,后续会单独贴出来。  Redis 工具包请参考文章:Redis 工具实用篇_jiaomubai的博客-CSDN博客

正式登录接口的代码如下:

@PostMapping("/login")
public void login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("code") String code, @RequestParam("codeKey") String codeKey, HttpServletResponse resp, HttpServletRequest request) {
    JSONObject result = new JSONObject();
    try {
        String redisCode = (String) redisSupport.get(codeKey);
        log.info("redisCode:{}",redisCode);
        if(StringUtils.isEmpty(code)  || StringUtils.isEmpty(redisCode) || !code.equals(redisCode)){
            result.put("error_description", "验证码错误");
            result.put("error", "invalid_grant");
            resp.setStatus(400);
            redisSupport.del(codeKey);
            return;
        }
    } catch (Exception e) {
        log.error("登录接口错误,错误信息:{}", e);
    } finally {
        try {
            resp.setContentType(ContentType.JSON.getValue());
            ServletOutputStream out = resp.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(out, "UTF-8");
            ow.write(result.toJSONString());
            ow.flush();
            ow.close();
        } catch (Exception e) {
            log.error("登录接口错误,错误信息:{}", e);
        }
    }
}

其中入参中 username 为登录的用户名,password 为登录密码,code 为用户输入的图片验证码的答案,codekey 为与 code 关联的 key,因为在获取验证码的接口中(/getCode)我们已经将 code 和 codekey 存储在了 Redis 中,所以此处可直接根据 codekey 去获取 Redis 中的与 codekey 对应的验证码,之后与用户输入的 code 进行比较即可。其中使用的 redisSupport 可根据实际情况进行替换,其实就是 Redis 的一个工具包,后续会单独贴出来。 Redis 工具包请参考文章:Redis 工具实用篇_jiaomubai的博客-CSDN博客

还有一种使用简单运算的登录验证方式在下一篇文章中说明~

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用Spring Boot和Vue.js实现图片验证码登录验证的前后端代码: ## 后端代码(Spring Boot) ### 1. 引入依赖 在`pom.xml`中添加以下依赖: ```xml <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency> ``` ### 2. 创建验证码生成器 在`config`包下创建一个`KaptchaConfig`类,用于配置验证码生成器: ```java @Configuration public class KaptchaConfig { @Bean public Producer captchaProducer() { Properties properties = new Properties(); // 配置验证码生成器 // ... return new DefaultKaptcha(); } } ``` ### 3. 创建验证码接口 在`controller`包下创建一个`CaptchaController`类,用于生成验证码图片: ```java @RestController @RequestMapping("/captcha") public class CaptchaController { @Autowired private Producer captchaProducer; @GetMapping("/image") public void captchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception { // 设置响应头信息,告诉浏览器返回的是图片 response.setContentType("image/jpeg"); // 配置验证码生成器 // ... // 生成验证码文本和图片 String captchaText = captchaProducer.createText(); BufferedImage captchaImage = captchaProducer.createImage(captchaText); // 将验证码文本存入session HttpSession session = request.getSession(); session.setAttribute("captchaText", captchaText); // 将验证码图片输出到响应流中 ServletOutputStream out = response.getOutputStream(); ImageIO.write(captchaImage, "jpeg", out); out.flush(); out.close(); } } ``` ### 4. 创建登录接口 在`controller`包下创建一个`LoginController`类,用于处理登录请求: ```java @RestController @RequestMapping("/login") public class LoginController { @PostMapping("/check") public boolean check(@RequestParam String captcha, HttpSession session) { // 获取session中存储的验证码文本 String captchaText = (String) session.getAttribute("captchaText"); // 比较用户输入的验证码和session中存储的验证码是否一致 return captchaText != null && captchaText.equalsIgnoreCase(captcha); } } ``` ## 前端代码(Vue.js) ### 1. 安装依赖 在项目目录下执行以下命令安装依赖: ```bash npm install axios vue-axios vue-qriously ``` ### 2. 创建组件 在`components`目录下创建一个`CaptchaLogin`组件,包含一个输入框、一个验证码图片和一个登录按钮: ```html <template> <div> <input type="text" v-model="captcha" placeholder="请输入验证码" /> <qriously :value="captchaImageUrl"></qriously> <button @click="login">登录</button> </div> </template> <script> import axios from "axios"; import VueAxios from "vue-axios"; import Qriously from "vue-qriously"; export default { name: "CaptchaLogin", components: { Qriously, }, data() { return { captcha: "", captchaImageUrl: "", }; }, created() { this.refreshCaptcha(); }, methods: { refreshCaptcha() { const captchaUrl = `/captcha/image?timestamp=${new Date().getTime()}`; this.captchaImageUrl = captchaUrl; }, login() { axios .post("/login/check", { captcha: this.captcha }) .then((response) => { if (response.data) { alert("登录成功"); } else { alert("验证码错误"); } this.refreshCaptcha(); }); }, }, mounted() { Vue.use(VueAxios, axios); }, }; </script> ``` ### 3. 在页面中使用组件 在需要登录验证的页面中使用`CaptchaLogin`组件: ```html <template> <div> <CaptchaLogin /> </div> </template> <script> import CaptchaLogin from "@/components/CaptchaLogin.vue"; export default { name: "LoginPage", components: { CaptchaLogin, }, }; </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值