feat: 1:手机号发送验证码

2:手机号验证码登录
This commit is contained in:
2026-01-22 16:10:32 +08:00
parent 98304d27b7
commit 8d8ec86a8a
34 changed files with 2466 additions and 641 deletions
@@ -1,8 +1,10 @@
package com.central.oauth.controller;
import com.central.common.constant.SecurityConstants;
import com.central.common.feign.MsgCenterService;
import com.central.common.model.CodeEnum;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.common.utils.RSAUtil;
import com.central.common.utils.StringUtils;
import com.central.oauth.model.Client;
@@ -21,11 +23,14 @@ import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.token.OpenIdAuthenticationToken;
import com.central.oauth2.common.token.TencentAuthenticationToken;
import com.central.oauth2.common.util.AuthUtils;
import com.central.common.feign.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
@@ -48,6 +53,8 @@ import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Tag(name = "登录接口")
@RestController
@@ -86,6 +93,31 @@ public class LoginController {
@Resource
private UnifiedLogoutService unifiedLogoutService;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private MsgCenterService msgCenterService;
@Resource
private UserService userService;
/**
* 短信验证码Redis Key前缀
*/
private static final String SMS_CODE_PREFIX = "sms:code:";
/**
* 短信验证码有效期(分钟)
*/
private static final long SMS_CODE_EXPIRE_MINUTES = 5;
/**
* 短信服务商类型:tencent-腾讯云, aliyun-阿里云
*/
@org.springframework.beans.factory.annotation.Value("${sms.provider:tencent}")
private String smsProvider;
@PostMapping(value = "/login")
public Result<Map<String, Object>> login(@RequestBody LoginReq req) {
try {
@@ -133,6 +165,148 @@ public class LoginController {
}
}
/**
* 发送手机验证码
*
* @param mobile 手机号
* @return 发送结果
*/
@Operation(summary = "发送手机验证码")
@PostMapping(value = "/sendSmsCode")
public Result<String> sendSmsCode(@RequestParam("mobile") String mobile) {
try {
// 1) 校验手机号格式
if (StringUtils.isBlank(mobile) || !mobile.matches("^1[3-9]\\d{9}$")) {
return Result.failed("手机号格式不正确");
}
// 2) 检查是否频繁发送(防刷)
String redisKey = SMS_CODE_PREFIX + mobile;
String existCode = stringRedisTemplate.opsForValue().get(redisKey);
if (StringUtils.isNotBlank(existCode)) {
Long ttl = stringRedisTemplate.getExpire(redisKey, TimeUnit.SECONDS);
if (ttl != null && ttl > (SMS_CODE_EXPIRE_MINUTES - 1) * 60) {
return Result.failed("验证码发送过于频繁,请稍后再试");
}
}
// 3) 生成4位随机验证码
String code = String.format("%04d", new Random().nextInt(10000));
// 4) 根据配置选择短信服务商发送短信
Result<?> sendResult;
if ("aliyun".equalsIgnoreCase(smsProvider)) {
log.info("使用阿里云发送验证码,mobile:{}", mobile);
sendResult = msgCenterService.sendAliyunVerifyCode(mobile, code);
} else {
// 默认使用腾讯云
log.info("使用腾讯云发送验证码,mobile:{}", mobile);
sendResult = msgCenterService.sendTencentVerifyCode(mobile, code);
}
if (sendResult == null || sendResult.getResp_code() != 0) {
log.error("发送短信验证码失败,mobile:{}, result:{}", mobile, sendResult);
return Result.failed("短信发送失败,请稍后重试");
}
// 5) 发送成功后存入Redis,设置有效期
stringRedisTemplate.opsForValue().set(redisKey, code, SMS_CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);
log.info("短信验证码发送成功,mobile:{}", mobile);
return Result.succeed("验证码发送成功");
} catch (Exception e) {
log.error("发送短信验证码异常,mobile:{}", mobile, e);
return Result.failed("短信发送失败:" + e.getMessage());
}
}
/**
* 手机号验证码登录
*
* @param mobile 手机号
* @param smsCode 短信验证码
* @param clientId 客户端ID
* @return 登录结果(token)
*/
@Operation(summary = "手机号验证码登录")
@PostMapping(value = "/loginBySmsCode")
public Result<Map<String, Object>> loginBySmsCode(
@RequestParam("mobile") String mobile,
@RequestParam("smsCode") String smsCode,
@RequestParam("clientId") String clientId) {
try {
// 1) 校验参数
if (StringUtils.isBlank(mobile) || !mobile.matches("^1[3-9]\\d{9}$")) {
return Result.failed("手机号格式不正确");
}
if (StringUtils.isBlank(smsCode)) {
return Result.failed("验证码不能为空");
}
if (StringUtils.isBlank(clientId)) {
return Result.failed("客户端ID不能为空");
}
// 2) 从Redis获取验证码并校验
String redisKey = SMS_CODE_PREFIX + mobile;
String cachedCode = stringRedisTemplate.opsForValue().get(redisKey);
if (StringUtils.isBlank(cachedCode)) {
return Result.failed("验证码已过期,请重新获取");
}
if (!cachedCode.equals(smsCode)) {
return Result.failed("验证码错误");
}
// 3) 验证码校验成功后删除
stringRedisTemplate.delete(redisKey);
// 4) 查询用户是否已注册
SysUser sysUser = userService.findByMobile(mobile);
String openId;
if (sysUser == null || sysUser.getId() == null) {
// 用户不存在,先注册
log.info("用户不存在,进行注册,mobile:{}", mobile);
SysUser newUser = userService.registerByMobile(mobile);
if (newUser == null || StringUtils.isBlank(newUser.getOpenId())) {
return Result.failed("用户注册失败,请重试");
}
openId = newUser.getOpenId();
log.info("用户注册成功,mobile:{}, openId:{}", mobile, openId);
} else {
// 用户已存在
openId = sysUser.getOpenId();
if (StringUtils.isBlank(openId)) {
return Result.failed("用户信息异常,缺少openId");
}
log.info("用户已存在,直接登录,mobile:{}, openId:{}", mobile, openId);
}
// 5) 使用openId进行登录
LoginReq loginReq = new LoginReq();
loginReq.setGrantType("openId");
loginReq.setOpenId(openId);
loginReq.setClientId(clientId);
// 6) 客户端校验
Client client = clientService.loadClientByClientId(clientId);
if (client == null) {
return Result.failed("所属客户端不存在");
}
RegisteredClient registeredClient = registeredClientRepository.findByClientId(client.getClientId());
if (registeredClient == null) {
return Result.failed("未注册的客户端");
}
AuthorizationGrantType grantTypeToUse = new AuthorizationGrantType("openId");
if (!registeredClient.getAuthorizationGrantTypes().contains(grantTypeToUse)) {
return Result.failed("客户端未开通openId授权类型");
}
// 7) 颁发令牌
return issueTokenInternally(loginReq, registeredClient, null);
} catch (Exception e) {
log.error("手机号验证码登录异常,mobile:{}", mobile, e);
return Result.failed("登录失败:" + e.getMessage());
}
}
@PostMapping(value = "/logout")
public Result<String> logOut(HttpServletRequest request) {
String token = AuthUtils.extractHeaderToken(request);
@@ -63,3 +63,5 @@ zlt:
# 鍏煎榛樿琛ㄥ崟鐧诲綍涓庡唴缃櫥鍑?
- /user/login
- /oauth/remove/token
- /oauth/sendSmsCode
- /oauth/loginBySmsCode