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

@@ -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]));
}
}