添加登入添加Google Authenticator TOTP六位动态码 授权登。2. 保留Google登录并支持动态码登录

This commit is contained in:
lu7213 committed 2026-10-21 04:03:06 -04:00
1 parent 42a06f7e4d
commit cc5fe279e9
13 files changed
+714 -2

No files matched your search

@@ -120,6 +120,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/login", "/simple-login", "/captchaImage").anonymous()
.antMatchers(HttpMethod.POST, "/system/user/usdt/register").permitAll()
.antMatchers("/auth/google/login-url", "/auth/google/callback", "/auth/google/exchange").permitAll()
.antMatchers(HttpMethod.POST, "/auth/totp/login").permitAll()
.antMatchers(
// HttpMethod.GET,
antPatterns.toArray(new String[0])
@@ -45,6 +45,13 @@ public class SysLoginService
* @return 结果
*/
public String login(String username, String password, String code, String uuid,boolean checkcode)
{
validateCaptcha(username, code, uuid, checkcode);
return authenticate(username, password);
}
/** 密码与动态码登录共用图形验证码校验,动态码不复用 code 字段。 */
public void validateCaptcha(String username, String code, String uuid, boolean checkcode)
{
String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
String captcha = redisCache.getCacheObject(verifyKey);
@@ -54,11 +61,15 @@ public class SysLoginService
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
throw new CaptchaExpireException();
}
if (checkcode && !code.equalsIgnoreCase(captcha))
if (checkcode && (code == null || !code.equalsIgnoreCase(captcha)))
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException();
}
}
private String authenticate(String username, String password)
{
// 用户验证
Authentication authentication = null;
try
@@ -0,0 +1,198 @@
package com.ruoyi.framework.web.service;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.TotpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.mapper.SysUserTotpMapper;
import com.ruoyi.system.service.ISysUserService;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
/** 独立的 Authenticator 登录方式,不改变密码登录和 Google OAuth 的认证契约。 */
@Service
public class TotpAuthService {
private static final String INVALID = "账号或动态码无效、已使用,请稍后重试";
private static final String PENDING_PREFIX = "auth:totp:pending:";
/** 计数及设置过期时间原子完成,避免进程中断后产生永久锁。 */
private static final DefaultRedisScript<Long> LIMIT_SCRIPT = new DefaultRedisScript<>(
"local n = redis.call('INCR', KEYS[1]); "
+ "if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]); end; return n", Long.class);
private final SysUserTotpMapper mapper;
private final TotpSecretCipher cipher;
private final StringRedisTemplate redis;
private final ISysUserService userService;
private final UserDetailsServiceImpl userDetailsService;
private final TokenService tokenService;
private final SysLoginService loginService;
@Value("${auth.totp.issuer:USDT PAY}")
private String issuer;
public TotpAuthService(SysUserTotpMapper mapper, TotpSecretCipher cipher, StringRedisTemplate redis,
ISysUserService userService, UserDetailsServiceImpl userDetailsService,
TokenService tokenService, SysLoginService loginService) {
this.mapper = mapper;
this.cipher = cipher;
this.redis = redis;
this.userService = userService;
this.userDetailsService = userDetailsService;
this.tokenService = tokenService;
this.loginService = loginService;
}
/** 状态接口只返回布尔值,不返回已有密钥或密文。 */
public Map<String, Object> status(Long userId) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("enabled", cipher.isConfigured());
result.put("bound", mapper.selectSecret(userId) != null);
return result;
}
/** 已登录且再次验证本地密码后生成临时绑定,Redis 也只保留加密后的密钥。 */
public Map<String, Object> setup(Long userId, String password) {
limit("manage:" + userId, 10);
SysUser user = verifyPassword(userId, password);
if (!cipher.isConfigured()) {
throw new CustomException("服务端尚未配置 Authenticator 加密密钥");
}
if (mapper.selectSecret(userId) != null) {
throw new CustomException("已绑定 Authenticator,请先解绑");
}
String key = PENDING_PREFIX + userId;
// 同一用户同时打开多个页面时复用临时绑定,防止相互覆盖二维码。
redis.opsForValue().setIfAbsent(key, cipher.encrypt(userId, TotpUtils.newSecret()), 10, TimeUnit.MINUTES);
String pending = redis.opsForValue().get(key);
if (pending == null) {
throw new CustomException("临时绑定已过期,请重新开始");
}
String secret = cipher.decrypt(userId, pending);
Map<String, Object> result = new LinkedHashMap<>();
result.put("secret", secret);
result.put("otpauthUrl", "otpauth://totp/" + encode(issuer + ":" + user.getUserName())
+ "?secret=" + secret + "&issuer=" + encode(issuer) + "&algorithm=SHA1&digits=6&period=30");
return result;
}
/** 必须验证手机实际生成的六位码才入库;唯一键保证不能覆盖已有绑定。 */
public void bind(Long userId, String password, String code) {
limit("manage:" + userId, 10);
verifyPassword(userId, password);
String pending = redis.opsForValue().get(PENDING_PREFIX + userId);
if (pending == null) {
throw new CustomException("临时绑定已过期,请重新开始");
}
long step = TotpUtils.matchingStep(cipher.decrypt(userId, pending), code, Instant.now().getEpochSecond());
if (step < 0) {
throw new CustomException("动态码错误,请核对手机时间");
}
try {
mapper.insert(userId, pending, step);
} catch (DuplicateKeyException exception) {
throw new CustomException("已绑定 Authenticator,请刷新页面");
}
redis.delete(PENDING_PREFIX + userId);
}
/** 解绑必须同时持有密码和当前动态码,不允许仅靠已登录会话重置认证器。 */
public void unbind(Long userId, String password, String code) {
limit("manage:" + userId, 10);
verifyPassword(userId, password);
String encrypted = consumeCode(userId, code);
if (mapper.delete(userId, encrypted) != 1) {
throw new CustomException("绑定状态已变化,请刷新页面");
}
redis.delete(PENDING_PREFIX + userId);
}
/** 动态码是独立登录凭据,必须同时通过图形验证码、账号限流、IP 限流和账户状态校验。 */
public String login(String username, String code, String captcha, String uuid, String remoteAddress) {
limit("ip:" + digest(remoteAddress), 50);
loginService.validateCaptcha(username, captcha, uuid, true);
if (username == null || username.trim().isEmpty() || username.length() > 64) {
throw new CustomException(INVALID);
}
SysUser user = userService.selectUserByUserName(username.trim());
limit("login:" + (user == null ? digest(username) : user.getUserId()), 10);
if (user == null) {
throw new CustomException(INVALID);
}
LoginUser loginUser;
try {
// 复用现有用户状态、角色和菜单权限装配,禁用/删除用户不能使用动态码绕过。
loginUser = (LoginUser) userDetailsService.loadUserByUsername(user.getUserName());
consumeCode(user.getUserId(), code);
} catch (CustomException exception) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL,
"Authenticator 动态码验证失败"));
throw new CustomException(INVALID);
}
String token = tokenService.createToken(loginUser);
AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS,
"Authenticator 动态码登录成功"));
return token;
}
private String consumeCode(Long userId, String code) {
String encrypted = mapper.selectSecret(userId);
if (encrypted == null) {
throw new CustomException(INVALID);
}
long step = TotpUtils.matchingStep(cipher.decrypt(userId, encrypted), code, Instant.now().getEpochSecond());
if (step < 0 || mapper.consume(userId, encrypted, step) != 1) {
throw new CustomException(INVALID);
}
return encrypted;
}
private SysUser verifyPassword(Long userId, String password) {
SysUser user = userService.selectUserById(userId);
if (user == null || password == null || password.length() > 128
|| !SecurityUtils.matchesPassword(password, user.getPassword())) {
throw new CustomException("本地账号密码错误");
}
userDetailsService.loadUserByUsername(user.getUserName());
return user;
}
private void limit(String scope, int maximum) {
Long attempts = redis.execute(LIMIT_SCRIPT, Collections.singletonList("auth:totp:limit:" + scope), "300");
if (attempts == null || attempts > maximum) {
throw new CustomException("动态码操作过于频繁,请在五分钟后重试");
}
}
private String digest(String value) {
try {
return Base64.getUrlEncoder().withoutPadding().encodeToString(MessageDigest.getInstance("SHA-256")
.digest(String.valueOf(value).getBytes(StandardCharsets.UTF_8)));
} catch (Exception exception) {
throw new CustomException("动态码服务暂不可用");
}
}
private String encode(String value) {
try {
return URLEncoder.encode(value, "UTF-8").replace("+", "%20");
} catch (Exception exception) {
throw new CustomException("无法生成 Authenticator 绑定信息");
}
}
}
@@ -0,0 +1,71 @@
package com.ruoyi.framework.web.service;
import com.ruoyi.common.exception.CustomException;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/** 密钥由部署环境提供,与数据库分离;禁止使用默认密钥。 */
@Component
public class TotpSecretCipher {
private final SecureRandom random = new SecureRandom();
private final String configuredKey;
public TotpSecretCipher(@Value("${auth.totp.encryption-key:}") String configuredKey) {
this.configuredKey = configuredKey;
}
public boolean isConfigured() {
try {
return Base64.getDecoder().decode(configuredKey).length == 32;
} catch (IllegalArgumentException exception) {
return false;
}
}
public String encrypt(Long userId, String secret) {
try {
byte[] nonce = new byte[12];
random.nextBytes(nonce);
byte[] encrypted = cipher(Cipher.ENCRYPT_MODE, userId, nonce)
.doFinal(secret.getBytes(StandardCharsets.US_ASCII));
byte[] payload = Arrays.copyOf(nonce, nonce.length + encrypted.length);
System.arraycopy(encrypted, 0, payload, nonce.length, encrypted.length);
return Base64.getEncoder().encodeToString(payload);
} catch (Exception exception) {
throw new CustomException("动态码密钥加密失败,请检查服务端配置");
}
}
public String decrypt(Long userId, String payload) {
try {
byte[] bytes = Base64.getDecoder().decode(payload);
if (bytes.length < 29) {
throw new IllegalArgumentException();
}
return new String(cipher(Cipher.DECRYPT_MODE, userId, Arrays.copyOf(bytes, 12))
.doFinal(Arrays.copyOfRange(bytes, 12, bytes.length)), StandardCharsets.US_ASCII);
} catch (Exception exception) {
// 不透出底层异常,避免密文、密钥或配置被异常处理器记录。
throw new CustomException("动态码密钥读取失败,请联系管理员");
}
}
private Cipher cipher(int mode, Long userId, byte[] nonce) throws Exception {
if (!isConfigured()) {
throw new IllegalStateException();
}
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(mode, new SecretKeySpec(Base64.getDecoder().decode(configuredKey), "AES"),
new GCMParameterSpec(128, nonce));
// 用户 ID 作为附加认证数据,防止数据库密文被调换到另一个用户。
cipher.updateAAD(("totp:v1:" + userId).getBytes(StandardCharsets.UTF_8));
return cipher;
}
}