This commit is contained in:
雷欧(林平凡)
2025-06-17 18:50:02 +08:00
parent faab92e9b5
commit e0f9952773
7 changed files with 59 additions and 10 deletions

View File

@@ -15,6 +15,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;
@@ -41,7 +42,7 @@ public class AuthController {
private static final String USER_TOKEN_PREFIX = "user:token:";
@PostMapping("/login")
public ApiResponse<LoginResponse> login(@RequestBody LoginRequest request) {
public ApiResponse login(@RequestBody LoginRequest request) {
logger.info("用户登录");
logger.info("用户名:{}", request.getUsername());
logger.info("密码:{}", request.getPassword());
@@ -49,28 +50,39 @@ public class AuthController {
logger.info("生成的验证码:{}", request.getGeneratedCaptcha());
// 1. 基础校验
if (StringUtils.isBlank(request.getUsername()) || StringUtils.isBlank(request.getPassword())) {
throw new RuntimeException("用户名或密码不能为空");
logger.error("用户名或密码不能为空");
return ApiResponse.badRequest();
}
// 2. 验证码校验
if (!captchaService.validateCaptcha(request.getCaptcha(), request.getGeneratedCaptcha())) {
throw new RuntimeException("验证码错误");
logger.error("验证码错误");
return ApiResponse.badRequest();
}
// 在验证码校验后、认证前添加防爆破逻辑
// 在验证码校验后、认证前添加防爆破逻辑
String loginFailKey = "login:fail:" + request.getUsername();
Long failCount = redisTemplate.opsForValue().increment(loginFailKey);
if (failCount != null && failCount > 5) {
throw new RuntimeException("尝试次数过多,请稍后再试");
logger.error("尝试次数过多,请稍后再试");
return ApiResponse.badRequest();
}else {
redisTemplate.expire(loginFailKey, 5, TimeUnit.MINUTES);
}
// 3. 用户认证Spring Security 标准流程)
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
logger.info("3. 用户认证Spring Security 标准流程)");
try {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
} catch (Exception e) {
logger.error("用户认证失败:{}", e.getMessage());
}
// 4. 生成 JWT Token
logger.info("用户认证成功");
String token = jwtUtils.generateToken(request.getUsername());
String refreshToken = generateRefreshToken(request.getUsername());
logger.info("生成 JWT Token{}", token);
// 5. 存入 Redis
saveUserToken(request.getUsername(), token, jwtUtils.getExpiration(token));