Spring Security-3:登录添加验证码

本文介绍在Spring Security中添加验证码的详细步骤,包括引入kaptcha依赖,生成验证码逻辑,自定义验证码异常类,登录控制器,验证码校验过滤器,登录失败处理器的改造,以及测试流程。
摘要由CSDN通过智能技术生成

更多内容欢迎访问我的个人 Java 站点:开坑组-Java站

前言

上篇简单介绍了如何开启自定义账户登录,这篇我们介绍下如何在登录流程中添加验证码,这里我们使用的生成验证码的包是 kaptcha

1. 引入验证码相关依赖包

<!-- 用于生成验证码 -->
<dependency>
    <groupId>com.github.axet</groupId>
    <artifactId>kaptcha</artifactId>
    <version>0.0.9</version>
</dependency>
<!-- 用于在session中保存验证码 -->
<dependency>
    <groupId>org.springframework.social</groupId>
    <artifactId>spring-social-config</artifactId>
</dependency>

2. 添加验证码生成逻辑

验证码相关配置

# 验证码配置
kaptcha:
  expired: 60
  border:
    enable: true
    color: "105,179,90"
  textproducer:
    font:
      color: "black"
      size: 30
      names: "宋体,楷体,黑体"
    char:
      length: 5
  image:
    width: 160
    height: 50

添加验证码生成配置类

package com.example.security.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfig {

    @Value("${kaptcha.border.enable}")
    private Boolean border;

    @Value("${kaptcha.border.color}")
    private String borderColor;

    @Value("${kaptcha.textproducer.font.color}")
    private String fontColor;

    @Value("${kaptcha.textproducer.font.size}")
    private String fontSize;

    @Value("${kaptcha.textproducer.font.names}")
    private String fontNames;

    @Value("${kaptcha.textproducer.char.length}")
    private String charLength;

    @Value("${kaptcha.image.width}")
    private String imageWidth;

    @Value("${kaptcha.image.height}")
    private String imageHeight;

    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        // 设置边框
        if (border) {
            properties.put("kaptcha.border", "yes");
            // 设置边框颜色
            properties.put("kaptcha.border.color", borderColor);
        }
        // 设置字体颜色
        properties.put("kaptcha.textproducer.font.color", fontColor);
        //设置字体尺寸
        properties.put("kaptcha.textproducer.font.size", fontSi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值