添加登入添加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

+5 -1
View File
@@ -80,6 +80,10 @@ susdt是一套全部开源的快速开发平台,毫无保留给个人及企业
</table>
## Authenticator 动态码登录
保留密码和 Google 账号登录,新增六位动态码登录及个人中心绑定/解绑。部署前执行 `sql/totp_auth.sql` 并配置 `TOTP_ENCRYPTION_KEY`,详见 [部署与使用说明](docs/totp-login.md)。
## susdt前后端分离交流群
QQ群: [![加入QQ群](https://img.shields.io/badge/已满-937441-blue.svg)](https://jq.qq.com/?_wv=1027&k=5bVB1og) [![加入QQ群](https://img.shields.io/badge/已满-887144332-blue.svg)](https://jq.qq.com/?_wv=1027&k=5eiA4DH) [![加入QQ群](https://img.shields.io/badge/已满-180251782-blue.svg)](https://jq.qq.com/?_wv=1027&k=5AxMKlC) [![加入QQ群](https://img.shields.io/badge/已满-104180207-blue.svg)](https://jq.qq.com/?_wv=1027&k=51G72yr) [![加入QQ群](https://img.shields.io/badge/186866453-blue.svg)](https://jq.qq.com/?_wv=1027&k=VvjN2nvu) 点击按钮入群。
QQ群: [![加入QQ群](https://img.shields.io/badge/已满-937441-blue.svg)](https://jq.qq.com/?_wv=1027&k=5bVB1og) [![加入QQ群](https://img.shields.io/badge/已满-887144332-blue.svg)](https://jq.qq.com/?_wv=1027&k=5eiA4DH) [![加入QQ群](https://img.shields.io/badge/已满-180251782-blue.svg)](https://jq.qq.com/?_wv=1027&k=5AxMKlC) [![加入QQ群](https://img.shields.io/badge/已满-104180207-blue.svg)](https://jq.qq.com/?_wv=1027&k=51G72yr) [![加入QQ群](https://img.shields.io/badge/186866453-blue.svg)](https://jq.qq.com/?_wv=1027&k=VvjN2nvu) 点击按钮入群。
+42
View File
@@ -0,0 +1,42 @@
# Google Authenticator 动态码登录
保留原密码登录和 Google OAuth 登录,新增独立的“账号 + 六位动态码 + 图形验证码”登录方式。动态码登录不是强制双因素验证,不改变其他登录方式的认证规则。
## 部署
1. 在现有业务数据库执行增量脚本 `sql/totp_auth.sql`,不需要修改 `sys_user` 或 Google 绑定表。
2. 使用密码学安全随机源生成 32 字节并转为 Base64,通过环境变量 `TOTP_ENCRYPTION_KEY` 配置;不要提交到代码仓库。所有后端实例使用相同密钥,备份必须与数据库分开保管。留空时无法新增绑定。更换密钥前必须迁移已有密文。
3. 可选设置 `TOTP_ISSUER`,默认 `USDT PAY`。使用 HTTPS,服务器和手机开启自动时间同步。
4. 编译部署前后端。Redis 用于短期绑定和限流,必须可用。数据库凭据表采用 InnoDB。
PowerShell 生成密钥(在部署服务器交互环境执行,输出仅写入受控配置):
```powershell
$totpKeyBytes = New-Object byte[] 32
$totpRng = [Security.Cryptography.RandomNumberGenerator]::Create()
$totpRng.GetBytes($totpKeyBytes)
$env:TOTP_ENCRYPTION_KEY = [Convert]::ToBase64String($totpKeyBytes)
$totpRng.Dispose()
```
## 使用
- 先用密码或已绑定 Google 账号登录,打开“个人中心 → 账号安全 → Google Authenticator 动态码”。
- 输入本地密码生成二维码;用 Google Authenticator 扫码,或手动输入页面展示的设置密钥,再输入手机六位动态码确认绑定。二维码在浏览器本地生成。
- 临时绑定十分钟过期,未经验证不会启用。确认绑定所用码已消费,等手机刷新下一组码后再用于登录。
- 登录页切换“动态码登录”,输入本地用户名、六位动态码和图形验证码。前导零必须保留。
- 解绑需要本地密码及未使用过的动态码。遗失认证器时可用原密码或已绑定 Google 登录;需要重置绑定时由管理员核实身份后通过受控流程处理,系统不公开免验证重置接口。
## API
| 方法 / 路径 | 认证 / 请求 |
| --- | --- |
| `POST /auth/totp/login` | 匿名;`username, totpCode, code, uuid`,其中 code 是图形验证码;返回原有 `token` 字段 |
| `GET /auth/totp/binding` | 当前 JWT;返回 `data.enabled`、`data.bound`,不返回密钥 |
| `POST /auth/totp/setup` | 当前 JWT + `password`;返回 `data.secret`、`data.otpauthUrl`,禁止缓存或记录响应 |
| `POST /auth/totp/bind` | 当前 JWT + `password, totpCode` |
| `POST /auth/totp/unbind` | 当前 JWT + `password, totpCode` |
时间步为 30 秒,SHA-1,6 位,容忍前后各一个时间步。数据库 CAS 原子消费时间步,包含绑定确认在内的同一时间步不可重复成功,也不能倒退使用旧码。账号每五分钟最多十次动态码登录尝试,管理操作另计十次;连接来源每五分钟最多五十次登录尝试。反向代理部署下连接来源按代理地址计数,可另在代理层对真实来源限流,不信任任意客户端传入的转发头。
凭据使用 AES-256-GCM 加密,绑定用户 ID 为附加认证数据。密钥不加入用户实体、常规响应或 JWT。数据库、Redis 异常时拒绝认证。不要在网关、APM 或应用中开启登录请求体和绑定响应体采集。
@@ -0,0 +1,67 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TotpAuthService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** Authenticator 六位动态码;只有 login 匿名开放,管理接口使用当前 JWT 用户 ID。 */
@RestController
@RequestMapping("/auth/totp")
public class TotpAuthController {
private final TotpAuthService service;
public TotpAuthController(TotpAuthService service) {
this.service = service;
}
@GetMapping("/binding")
public AjaxResult status(HttpServletResponse response) {
response.setHeader("Cache-Control", "no-store");
return AjaxResult.success(service.status(SecurityUtils.getUserId()));
}
@PostMapping("/setup")
public AjaxResult setup(@RequestBody TotpRequest request, HttpServletResponse response) {
response.setHeader("Cache-Control", "no-store");
return AjaxResult.success(service.setup(SecurityUtils.getUserId(), request.getPassword()));
}
@PostMapping("/bind")
public AjaxResult bind(@RequestBody TotpRequest request) {
service.bind(SecurityUtils.getUserId(), request.getPassword(), request.getTotpCode());
return AjaxResult.success("Authenticator 已绑定,下一个动态码刷新后可用于登录");
}
@PostMapping("/unbind")
public AjaxResult unbind(@RequestBody TotpRequest request) {
service.unbind(SecurityUtils.getUserId(), request.getPassword(), request.getTotpCode());
return AjaxResult.success("Authenticator 已解绑");
}
@PostMapping("/login")
public AjaxResult login(@RequestBody TotpRequest request, HttpServletRequest servletRequest,
HttpServletResponse response) {
response.setHeader("Cache-Control", "no-store");
AjaxResult result = AjaxResult.success();
result.put(Constants.TOKEN, service.login(request.getUsername(), request.getTotpCode(),
request.getCode(), request.getUuid(), servletRequest.getRemoteAddr()));
return result;
}
/** 禁止生成包含密码、动态码的 toString;动态码与图形验证码分开传输。 */
public static class TotpRequest extends LoginBody {
private String totpCode;
public String getTotpCode() { return totpCode; }
public void setTotpCode(String totpCode) { this.totpCode = totpCode; }
}
}
@@ -225,6 +225,13 @@ luqj:
dir:
prefix: lu7213/images/ # 上传文件夹路径前缀
# Authenticator 凭据使用独立的 32 字节随机 AES 密钥(Base64),所有实例必须一致。
# 留空时禁止新建绑定;不要随意更换,已有凭据需要原密钥才能解密。
auth:
totp:
encryption-key: ${TOTP_ENCRYPTION_KEY:}
issuer: ${TOTP_ISSUER:USDT PAY}
# Google OpenID Connect登录。Client Secret只能通过环境变量或外部配置提供。
google:
oauth:
@@ -0,0 +1,129 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.TotpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.TotpAuthService;
import com.ruoyi.framework.web.service.TotpSecretCipher;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.system.mapper.SysUserTotpMapper;
import com.ruoyi.system.service.ISysUserService;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/** 可控 MySQL/Redis 替身:覆盖密码校验、临时绑定、并发冲突、防重放和限流失败关闭。 */
public class TotpBindingServiceTest {
private SysUserTotpMapper mapper;
private StringRedisTemplate redis;
private ValueOperations<String, String> values;
private TotpSecretCipher cipher;
private TotpAuthService service;
private String secret;
private String encrypted;
@Before
@SuppressWarnings("unchecked")
public void setup() {
mapper = mock(SysUserTotpMapper.class);
redis = mock(StringRedisTemplate.class);
values = mock(ValueOperations.class);
when(redis.opsForValue()).thenReturn(values);
when(redis.execute(any(DefaultRedisScript.class), anyList(), eq("300"))).thenReturn(1L);
ISysUserService users = mock(ISysUserService.class);
SysUser user = new SysUser();
user.setUserId(7L);
user.setUserName("tester");
user.setPassword(SecurityUtils.encryptPassword("test-only-password"));
when(users.selectUserById(7L)).thenReturn(user);
cipher = new TotpSecretCipher(Base64.getEncoder().encodeToString(new byte[32]));
service = new TotpAuthService(mapper, cipher, redis, users, mock(UserDetailsServiceImpl.class),
mock(TokenService.class), mock(SysLoginService.class));
ReflectionTestUtils.setField(service, "issuer", "USDT PAY");
secret = TotpUtils.newSecret();
encrypted = cipher.encrypt(7L, secret);
when(values.get("auth:totp:pending:7")).thenReturn(encrypted);
}
@Test
public void setupOnlyExposesTemporarySecretAndDoesNotEnableLogin() {
Map<String, Object> result = service.setup(7L, "test-only-password");
assertEquals(secret, result.get("secret"));
assertTrue(result.get("otpauthUrl").toString().startsWith("otpauth://totp/USDT%20PAY%3Atester?"));
verify(mapper, never()).insert(anyLong(), anyString(), anyLong());
assertFalse(service.status(7L).containsKey("secret"));
}
@Test
public void bindingConsumesConfirmationStepAndDeletesTemporarySecret() {
String code = currentCode();
service.bind(7L, "test-only-password", code);
verify(mapper).insert(eq(7L), eq(encrypted), longThat(step -> step > 0));
verify(redis).delete("auth:totp:pending:7");
}
@Test
public void refusesWrongPasswordAndExpiredTemporaryBinding() {
expectFailure(() -> service.bind(7L, "wrong", currentCode()));
when(values.get("auth:totp:pending:7")).thenReturn(null);
expectFailure(() -> service.bind(7L, "test-only-password", currentCode()));
verify(mapper, never()).insert(anyLong(), anyString(), anyLong());
}
@Test
public void refusesConcurrentBindingWithoutOverwritingExistingCredential() {
doThrow(new DuplicateKeyException("mock unique key")).when(mapper)
.insert(eq(7L), eq(encrypted), anyLong());
expectFailure(() -> service.bind(7L, "test-only-password", currentCode()));
verify(mapper, never()).delete(anyLong(), anyString());
}
@Test
public void unbindRequiresSuccessfulAtomicConsumption() {
when(mapper.selectSecret(7L)).thenReturn(encrypted);
// CAS 返回零模拟该时间步已使用,禁止继续解绑。
when(mapper.consume(eq(7L), eq(encrypted), anyLong())).thenReturn(0);
expectFailure(() -> service.unbind(7L, "test-only-password", currentCode()));
verify(mapper, never()).delete(anyLong(), anyString());
when(mapper.consume(eq(7L), eq(encrypted), anyLong())).thenReturn(1);
when(mapper.delete(7L, encrypted)).thenReturn(1);
service.unbind(7L, "test-only-password", currentCode());
verify(mapper).delete(7L, encrypted);
}
@Test
@SuppressWarnings("unchecked")
public void rateLimitRejectsBeforeReadingCredentials() {
when(redis.execute(any(DefaultRedisScript.class), anyList(), eq("300"))).thenReturn(11L);
expectFailure(() -> service.setup(7L, "test-only-password"));
verify(mapper, never()).selectSecret(anyLong());
when(redis.execute(any(DefaultRedisScript.class), anyList(), eq("300"))).thenReturn(null);
expectFailure(() -> service.setup(7L, "test-only-password"));
}
private String currentCode() {
return TotpUtils.generate(secret, Instant.now().getEpochSecond() / 30);
}
private void expectFailure(Runnable operation) {
try {
operation.run();
fail("应拒绝认证操作");
} catch (CustomException expected) {
assertFalse(expected.getMessage().contains(secret));
}
}
}
@@ -0,0 +1,61 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.TotpUtils;
import com.ruoyi.framework.web.service.TotpSecretCipher;
import java.util.Base64;
import org.junit.Test;
import static org.junit.Assert.*;
/** RFC 标准向量和密钥认证加密边界,不连接数据库或 RPC。 */
public class TotpSecurityTest {
private static final String SECRET = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
@Test
public void matchesRfc6238Sha1VectorsTruncatedToSixDigits() {
long[] times = {59, 1111111109L, 1111111111L, 1234567890L, 2000000000L, 20000000000L};
String[] codes = {"287082", "081804", "050471", "005924", "279037", "353130"};
for (int index = 0; index < times.length; index++) {
assertEquals(codes[index], TotpUtils.generate(SECRET, times[index] / 30));
}
}
@Test
public void acceptsOnlySixAsciiDigitsWithinOneTimeStep() {
assertEquals(1, TotpUtils.matchingStep(SECRET, "287082", 59));
assertEquals(1, TotpUtils.matchingStep(SECRET, "287082", 89));
assertEquals(-1, TotpUtils.matchingStep(SECRET, "287082", 90));
assertEquals(-1, TotpUtils.matchingStep(SECRET, " 287082", 59));
assertEquals(-1, TotpUtils.matchingStep(SECRET, null, 59));
assertEquals(-1, TotpUtils.matchingStep(SECRET, "123456", 59));
assertEquals(32, TotpUtils.newSecret().length());
}
@Test
public void encryptsWithFreshNonceAndBindsCiphertextToUser() {
TotpSecretCipher cipher = cipher();
String first = cipher.encrypt(1L, SECRET);
assertEquals(SECRET, cipher.decrypt(1L, first));
assertNotEquals(first, cipher.encrypt(1L, SECRET));
try {
cipher.decrypt(2L, first);
fail("密文不能在用户之间调换");
} catch (CustomException expected) {
assertFalse(expected.getMessage().contains(SECRET));
}
byte[] tampered = Base64.getDecoder().decode(first);
tampered[tampered.length - 1] ^= 1;
try {
cipher.decrypt(1L, Base64.getEncoder().encodeToString(tampered));
fail("篡改的认证标签应被拒绝");
} catch (CustomException expected) {
assertFalse(expected.getMessage().contains(SECRET));
}
assertFalse(new TotpSecretCipher("").isConfigured());
}
private TotpSecretCipher cipher() {
// 仅用于隔离测试的固定密钥,不用于部署。
return new TotpSecretCipher(Base64.getEncoder().encodeToString(new byte[32]));
}
}
@@ -0,0 +1,87 @@
package com.ruoyi.common.utils;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/** Google Authenticator 兼容的 RFC 6238:SHA-1、30 秒、6 位数字。 */
public final class TotpUtils {
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
private static final SecureRandom RANDOM = new SecureRandom();
private TotpUtils() { }
/** 160 位随机密钥,Base32 无填充编码,不能写日志。 */
public static String newSecret() {
byte[] bytes = new byte[20];
RANDOM.nextBytes(bytes);
StringBuilder value = new StringBuilder(32);
int buffer = 0;
int bits = 0;
for (byte item : bytes) {
buffer = (buffer << 8) | (item & 255);
bits += 8;
while (bits >= 5) {
bits -= 5;
value.append(BASE32.charAt((buffer >> bits) & 31));
}
}
return value.toString();
}
/** 返回命中的时间步;允许前后各 30 秒时钟误差,失败返回 -1。 */
public static long matchingStep(String secret, String code, long epochSeconds) {
if (code == null || !code.matches("[0-9]{6}")) {
return -1;
}
long current = epochSeconds / 30;
// 优先当前步,保留六位码的前导零;时间步消费由数据库原子完成。
for (int offset : new int[] {0, -1, 1}) {
long step = current + offset;
if (step >= 0 && MessageDigest.isEqual(generate(secret, step).getBytes(StandardCharsets.US_ASCII),
code.getBytes(StandardCharsets.US_ASCII))) {
return step;
}
}
return -1;
}
public static String generate(String secret, long step) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(decode(secret), "HmacSHA1"));
byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(step).array());
int offset = hash[hash.length - 1] & 15;
int number = ((hash[offset] & 127) << 24) | ((hash[offset + 1] & 255) << 16)
| ((hash[offset + 2] & 255) << 8) | (hash[offset + 3] & 255);
return String.format(Locale.ROOT, "%06d", number % 1000000);
} catch (GeneralSecurityException exception) {
throw new IllegalStateException("动态码算法不可用");
}
}
private static byte[] decode(String value) {
byte[] result = new byte[value.length() * 5 / 8];
int buffer = 0;
int bits = 0;
int index = 0;
for (char character : value.toCharArray()) {
int digit = BASE32.indexOf(character);
if (digit < 0) {
throw new IllegalArgumentException("动态码密钥格式无效");
}
buffer = (buffer << 5) | digit;
bits += 5;
if (bits >= 8) {
bits -= 8;
result[index++] = (byte) (buffer >> bits);
}
}
return result;
}
}
@@ -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;
}
}
@@ -0,0 +1,25 @@
package com.ruoyi.system.mapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
/** TOTP 凭据专用映射,密钥不进入用户实体、JWT 或常规用户响应。 */
public interface SysUserTotpMapper {
@Select("SELECT secret_cipher FROM sys_user_totp WHERE user_id = #{userId}")
String selectSecret(@Param("userId") Long userId);
@Insert("INSERT INTO sys_user_totp(user_id, secret_cipher, last_used_step) "
+ "VALUES(#{userId}, #{cipher}, #{step})")
int insert(@Param("userId") Long userId, @Param("cipher") String cipher, @Param("step") long step);
/** CAS 同时校验密钥版本与时间步,多个实例并发验证也只允许一次成功。 */
@Update("UPDATE sys_user_totp SET last_used_step = #{step}, updated_at = CURRENT_TIMESTAMP "
+ "WHERE user_id = #{userId} AND secret_cipher = #{cipher} AND last_used_step < #{step}")
int consume(@Param("userId") Long userId, @Param("cipher") String cipher, @Param("step") long step);
@Delete("DELETE FROM sys_user_totp WHERE user_id = #{userId} AND secret_cipher = #{cipher}")
int delete(@Param("userId") Long userId, @Param("cipher") String cipher);
}
+9
View File
@@ -0,0 +1,9 @@
-- 增量执行,不修改已有用户及 Google OAuth 绑定。
CREATE TABLE IF NOT EXISTS sys_user_totp (
user_id BIGINT NOT NULL COMMENT '本地用户 ID,一人一个 Authenticator',
secret_cipher VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT 'AES-256-GCM 密文',
last_used_step BIGINT NOT NULL DEFAULT -1 COMMENT '防重放:最近消费的 30 秒时间步',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户 Authenticator 动态码凭据';