仿若依框架的图形验证码实现

        由于这个验证码是由hutool工具生成,在使用redis把他存到数据里,首先我们准备好所需要的依赖:

redis

<!-- redis  -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

hutool

 

<!--hutoll-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.16</version> <!-- 版本号可以根据需要进行调整 -->
</dependency>

在然后在yaml文件配置所需要的redis 

redis:
  # 地址
  host: localhost
  # 端口,默认为6379
  port: 6379
  # 数据库索引
  database: 0
  # 密码
  #password:
  # 连接超时时间
  timeout: 10s
  lettuce:
    pool:
      # 连接池中的最小空闲连接
      min-idle: 0
      # 连接池中的最大空闲连接
      max-idle: 8
      # 连接池的最大数据库连接数
      max-active: 8
      # #连接池最大阻塞等待时间(使用负值表示没有限制)
      max-wait: -1ms

 

然后就是编写代码,先创建一个类  用来返回response结果

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseResult<T> implements Serializable {
    private Integer code;
    private String msg;

    private T data;
}

 

 

然后在编写验证码生成的controller,并将他存入redis里可以设置验证码的key,存在时间

@RestController
@RequestMapping("/cap")
@CrossOrigin
public class CaptchaController
{
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public ResponseResult getCaptcha(){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(80, 25, 4, 10);
        //得到验证码
        String code = lineCaptcha.getCode();
        //存储到redis
        redisTemplate.opsForValue().set("code",code);
        //设置过期时间
        redisTemplate.expire("code",60, TimeUnit.SECONDS);
        //返回base64的图片
        String imageBase64Data = lineCaptcha.getImageBase64Data();
        return new ResponseResult<>(200,"success",imageBase64Data);
    }

}

这里偷懒,不使用若依的math图形验证码了,直接使用 CaptchaUtil生成一个简易的验证码,

CaptchaUtil.createLineCaptcha 方法创建了一个图形验证码对象 LineCaptcha。具体参数如下:

  • 80: 验证码图片的宽度(像素)。
  • 25: 验证码图片的高度(像素)。
  • 4: 验证码字符的数量。
  • 10: 干扰线的数量,用于增加验证码的复杂度和安全性。

LineCaptcha 对象通常用于生成带有干扰线的验证码图片,以增加识别难度。

然后就可以根据具体的业务实现这个功能了,接下来就是示例代码:

可以先封装一个UserLoginDTO,把验证码存进去

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserLoginDTO implements Serializable {

    @Length(min = 2,max = 15,message = "用户名长度需要在[2和15]之间")
    @ApiModelProperty("用户名")
    private String username;
    @Length(min = 2,max = 15,message = "密码需要在[2和15]之间")
    @ApiModelProperty("密码")
    private String password;

    @ApiModelProperty("验证码")
    private String captcha;


}
在写自己的登录逻辑,一定要根据自己的需求去修改代码,
String captcha = userLoginDTO.getCaptcha();
//校验登陆请求参数
Object code = redisTemplate.opsForValue().get("code");
if(Objects.isNull(code)){
    throw new CustomException("验证码失效,请重新刷新");
}
if (!captcha.equalsIgnoreCase(code.toString())){
    throw new CustomException(("验证码输入错误"));
}
// 登录成功后,删除 Redis 中的验证码
redisTemplate.delete("code");

在接着就是前端了,这里使用vue和Element实现:

<el-form-item prop="captcha">

                    <el-row>

                        <el-col :span="16">

                            <el-input v-model="ruleForm.captcha" autocomplete="off" placeholder="请输入验证码" clearable>

                                <i slot="prefix" class="el-input__icon el-icon-key"></i>

                            </el-input>

                        </el-col>

                        <el-col :span="8">

                            <img :src="captchaUrl" class="captcha-image" alt="验证码" @click="refreshCaptcha" />

                        </el-col>

                    </el-row>

                </el-form-item>

在编写方法,使用axios和后端可以交互数据,里面需要的值要我们自己定义,

 

 getCapchUrl() {

            let url = "http://localhost:8080/cap";

            axios.get(url).then(res => {

                if (res.data && res.data.data) {

                    this.captchaUrl = res.data.data;

                } else {

                    console.error("Invalid captcha data", res);

                }

            }).catch(err => {

                console.error("Failed to load captcha image", err);

            });

        },

然后就完成这个功能了,特色功能可以根据自己的业务进行修改,欢迎各位大佬指正,一起加油吧!!! 

接下来就是一些效果,

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值