spring boot3登录开发-2(2短信验证码接口实现)

2024-03-21 22:44

本文主要是介绍spring boot3登录开发-2(2短信验证码接口实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

⛰️个人主页:     蒾酒

🔥系列专栏:《spring boot实战》

🌊山高路远,行路漫漫,终有归途


目录

写在前面

上文衔接

内容简介

短信验证码接口实现

1.依赖导入

2.接口分析

3.实现思路

3.功能实现

创建发送短信工具类

配置阿里云短信服务

接口代码实现

4.功能测试

写在最后


写在前面

本文介绍了springboot开发后端服务中,短信验证码接口功能的设计与实现,坚持看完相信对你有帮助。

同时欢迎订阅springboot系列专栏,持续分享spring boot的使用经验。

上文衔接

本文衔接上文,可以看一下:

spring boot3登录开发-2(1图形验证码接口实现)_用户登录验证码接口设计-CSDN博客文章浏览阅读5.2k次,点赞146次,收藏109次。上文我们已经整合好了jwt,本文我们开始实现图形验证码接口的实现。通过糊涂工具包的图形验证码工具完成获取验证码接口通过redis缓存key(验证码id)-value(验证码内容)_用户登录验证码接口设计https://blog.csdn.net/qq_62262918/article/details/136064820?spm=1001.2014.3001.5502

内容简介

上文我们已经整合好了jwt,本文我们开始实现短信验证码接口的实现。这里我选用阿里云的短信服务。本文侧重点在于设计思路,阿里云控制台开通短信服务,你跟着流程走一遍就可以。个人也是可以申请的。

短信验证码接口实现

1.依赖导入

导入阿里云短信服务SDK

pom.xml:

 <dependency><groupId>com.aliyun</groupId><artifactId>dysmsapi20170525</artifactId><version>2.0.24</version></dependency>

2.接口分析

关键点:

  1. 60s发送间隔
  2. 连发多次封禁24H

3.实现思路

接口接收一个手机号参数,先去redis查询该手机是否有未过期的验证码,如果有先判断发送次数,超过5次,先修改过期时间为24H,再抛发送次数过多异常,少于五次,就再判断发送频率,距离上次发送间隔少于60s,就抛出发送频繁异常,  如果没有未过期的验证码,代表这是第一次发送就直接生成验证码发送短信,接着redis存入一个哈希,key通过手机号生成,value就是,三个键值对,验证码,上次发送时间戳,发送次数(初始为1),默认过期时间5分钟

  1. 接收手机号参数。
  2. 查询 Redis 中该手机号是否有未过期的验证码。
  3. 如果有未过期的验证码:
    • 判断发送次数是否超过5次,如果超过5次,修改过期时间为24小时并抛出发送次数过多异常。
    • 如果发送次数未超过5次,再判断距离上次发送时间间隔是否少于60秒,如果少于60秒,抛出发送频繁异常。
  4. 如果没有未过期的验证码,代表第一次发送:
    • 生成验证码并发送短信。
    • 将验证码信息存入 Redis,包括验证码、上次发送时间戳和发送次数(初始为1),设置过期时间为5分钟。

注意事项:

考虑到验证码本身的敏感性,虽然存入Redis是临时的,但考虑安全建议对验证码内容进行加密存储,增强数据的安全性。

考虑对接口调用方进行身份验证,确保只有合法的客户端可以请求发送验证码。

整合redis:

Spring Boot3整合Redis_springboot 3 集成redis-CSDN博客文章浏览阅读5.4k次,点赞101次,收藏105次。spring boot整合redis简单四步即可。_springboot 3 集成redishttps://blog.csdn.net/qq_62262918/article/details/136067550?spm=1001.2014.3001.5501

3.功能实现

创建发送短信工具类

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;/*** @author mijiupro*/
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.sms")
@Slf4j
public class SmsUtil {private String accessKeyId;// 访问密钥idprivate String accessKeySecret;// 访问密钥secretprivate String endpoint;// 短信 API 的访问域名private String signName;// 短信签名private String templateCode;// 短信模板ID// 发送短信public Boolean sendSms(String phone, String code) {// 创建阿里云客户端Config config = new Config().setAccessKeyId(accessKeyId)// 配置访问密钥 ID.setAccessKeySecret(accessKeySecret);// 配置密钥config.endpoint = endpoint;// 配置访问端点Client client;try {client = new Client(config);} catch (Exception e) {log.error("阿里云短信服务初始化失败", e);return false;}// 构建发送请求SendSmsRequest sendSmsRequest = new SendSmsRequest().setSignName(signName) // 设置签名.setTemplateCode(templateCode) // 设置模板.setPhoneNumbers(phone) // 设置手机号为参数传入的值.setTemplateParam("{\"code\":\"" + code + "\"}"); // 设置模板参数为传入的验证码RuntimeOptions runtime = new RuntimeOptions();// 运行时选择,可以设置不同的属性来配置运行时环境的参数。try {// 复制代码运行请自行打印 API 的返回值SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);if (!"OK".equals(sendSmsResponse.getBody().getCode())) {log.error("短信发送失败:{}", sendSmsResponse.getBody().getMessage());return false;}log.info("短信发送成功");return true;} catch (Exception error) {log.error("短信发送失败:{}", error.getMessage());return false;}}
}

配置阿里云短信服务

application.yml:

此处修改为你的信息,这里我乱写的

aliyun:sms:access-key-id: Lih5disdjisdidaccess-key-secret: sdisajfdisf6s7d88sdendpoint: dysmsapi.aliyuncs.comsignName: mijiutemplateCode: SMS_46544097

接口代码实现

接口

public interface CaptchaService {/***  获取短信验证码* @param phone*/void getSmsCaptcha(String phone);}

实现类


import com.mijiu.commom.exception.GeneralBusinessException;
import com.mijiu.commom.util.SmsUtil;
import com.mijiu.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;/*** @author mijiupro*/
@Service
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {private final StringRedisTemplate stringRedisTemplate;private final SmsUtil smsUtil;public CaptchaServiceImpl(StringRedisTemplate stringRedisTemplate, SmsUtil smsUtil) {this.stringRedisTemplate = stringRedisTemplate;this.smsUtil = smsUtil;}@Overridepublic void getSmsCaptcha(String phone) {String hashKey = "login:sms:captcha:" + phone;BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(hashKey);// 初始检查String lastSendTimestamp = hashOps.get("lastSendTimestamp");String sendCount = hashOps.get("sendCount");String captcha = hashOps.get("captcha");hashOps.expire(5, TimeUnit.MINUTES); // 设置过期时间为5分钟// 判断发送次数是否超过限制if (StringUtils.isNotBlank(sendCount) && Integer.parseInt(sendCount) >= 5) {hashOps.expire(24, TimeUnit.HOURS); // 重新设置过期时间为24Hthrow new GeneralBusinessException("发送次数过多,请24H后再试");}// 判断发送频率是否过高if (StringUtils.isNotBlank(lastSendTimestamp)) {long lastSendTime = Long.parseLong(lastSendTimestamp);long currentTime = System.currentTimeMillis();long elapsedTime = currentTime - lastSendTime;long interval = 60 * 1000; // 60秒if (elapsedTime < interval) {throw new GeneralBusinessException("发送短信过于频繁,请稍后再试");}}// 更新发送次数int newSendCount = StringUtils.isNotBlank(sendCount) ? Integer.parseInt(sendCount) + 1 : 1;// 生成新验证码if (StringUtils.isBlank(captcha)) {captcha = RandomStringUtils.randomNumeric(6);}// 发送短信if (!smsUtil.sendSms(phone, captcha)) {throw new GeneralBusinessException("发送短信失败");}// 更新 Redis 中的信息hashOps.put("captcha", captcha);hashOps.put("lastSendTimestamp", String.valueOf(System.currentTimeMillis()));hashOps.put("sendCount", String.valueOf(newSendCount));}}

控制器


import com.mijiu.service.CaptchaService;
import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author mijiupro*/
@RestController
@RequestMapping("/captcha")
@Tag(name = "验证码接口", description = "验证码接口相关操作")
public class CaptchaController {private final CaptchaService captchaService;public CaptchaController(CaptchaService captchaService) {this.captchaService = captchaService;}@GetMapping("/sms-captcha/{phone}")@Operation(summary = "获取短信验证码")public void getSmsCaptcha(@PathVariable String phone) {captchaService.getSmsCaptcha(phone);}
}

说明:

代码里面我直接返回void是因为我做了全局响应结果拦截统一封装,实际应用为了考虑防盗刷等因素并不会返回空。

4.功能测试

我这里是整合了swagger3的,相关文章在本专栏:

Spring Boot3整合knife4j(swagger3)_springboot3 knife4j-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/qq_62262918/article/details/135761392?spm=1001.2014.3001.5502

 直接发一次

 

 60内重复发送

连发5次

写在最后

对接阿里云短信服务实现短信验证码接口到这里就结束了,接口设计我尽可能简单并有一定安全性考虑。希望看完对你有帮助。后面我会出一篇仿百度云短信验证接口的设计实现(考虑更多防盗刷策略),欢迎大家订阅本专栏。任何问题评论区或私信讨论,欢迎指正。

这篇关于spring boot3登录开发-2(2短信验证码接口实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/834025

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.