提交登录修改
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package com.nanri.aiimage.modules.auth.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "aiimage.auth")
|
||||
public class AuthProperties {
|
||||
|
||||
private String jwtSecret = "please-change-this-secret-please-rotate-at-least-32-bytes";
|
||||
private long jwtTtlHours = 168L;
|
||||
private String cookieName = "aiimage_token";
|
||||
private boolean cookieSecure = false;
|
||||
private String cookieSameSite = "Lax";
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.nanri.aiimage.modules.auth.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
|
||||
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
|
||||
import com.nanri.aiimage.modules.auth.service.AuthService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
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.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "登录认证", description = "桌面端登录与会话校验")
|
||||
public class LoginController {
|
||||
|
||||
private static final String DEVICE_ID_HEADER = "X-Device-Id";
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
@PostMapping("/login")
|
||||
@Operation(summary = "用户名密码登录")
|
||||
public ResponseEntity<ApiResponse<LoginResultVo>> login(@RequestBody LoginRequest request) {
|
||||
LoginResultVo result = authService.login(request);
|
||||
ResponseCookie cookie = authService.buildAuthCookie(result.getToken());
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.SET_COOKIE, cookie.toString())
|
||||
.body(ApiResponse.success("登录成功", result));
|
||||
}
|
||||
|
||||
@GetMapping("/check_login")
|
||||
@Operation(summary = "校验登录态")
|
||||
public ResponseEntity<ApiResponse<LoginResultVo>> checkLogin(
|
||||
HttpServletRequest httpRequest,
|
||||
@RequestHeader(value = DEVICE_ID_HEADER, required = false) String deviceIdHeader) {
|
||||
String token = resolveToken(httpRequest);
|
||||
LoginResultVo result = authService.checkLogin(token, deviceIdHeader);
|
||||
ResponseCookie cookie = authService.buildAuthCookie(result.getToken());
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.SET_COOKIE, cookie.toString())
|
||||
.body(ApiResponse.success(result));
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
@Operation(summary = "登出")
|
||||
public ResponseEntity<ApiResponse<Void>> logout() {
|
||||
ResponseCookie cookie = authService.buildClearCookie();
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.SET_COOKIE, cookie.toString())
|
||||
.body(ApiResponse.success("已登出", null));
|
||||
}
|
||||
|
||||
private String resolveToken(HttpServletRequest request) {
|
||||
String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
return authHeader.substring(7).trim();
|
||||
}
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) {
|
||||
return null;
|
||||
}
|
||||
String cookieName = authService.cookieName();
|
||||
for (Cookie cookie : cookies) {
|
||||
if (cookieName.equals(cookie.getName())) {
|
||||
return cookie.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.nanri.aiimage.modules.auth.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface LoginUserMapper extends BaseMapper<LoginUserEntity> {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.nanri.aiimage.modules.auth.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LoginRequest {
|
||||
|
||||
private String username;
|
||||
private String password;
|
||||
private String deviceId;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.nanri.aiimage.modules.auth.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@TableName("users")
|
||||
public class LoginUserEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private String username;
|
||||
@TableField("password_hash")
|
||||
private String passwordHash;
|
||||
private String machine;
|
||||
@TableField("is_admin")
|
||||
private Integer isAdmin;
|
||||
private String role;
|
||||
@TableField("created_by_id")
|
||||
private Long createdById;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.nanri.aiimage.modules.auth.model.vo;
|
||||
|
||||
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class LoginResultVo {
|
||||
|
||||
private Long userId;
|
||||
private String username;
|
||||
private String role;
|
||||
private Boolean isAdmin;
|
||||
private String deviceId;
|
||||
private String token;
|
||||
private Long expiresIn;
|
||||
private List<PermissionMenuItemVo> appColumns;
|
||||
private List<PermissionMenuItemVo> adminColumns;
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.nanri.aiimage.modules.auth.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.auth.config.AuthProperties;
|
||||
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
|
||||
import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
|
||||
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
|
||||
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
|
||||
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AuthService {
|
||||
|
||||
private final LoginUserMapper loginUserMapper;
|
||||
private final WerkzeugPasswordEncoder passwordEncoder;
|
||||
private final JwtService jwtService;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final AuthProperties authProperties;
|
||||
|
||||
public LoginResultVo login(LoginRequest request) {
|
||||
String username = trim(request.getUsername());
|
||||
String password = request.getPassword() == null ? "" : request.getPassword();
|
||||
String deviceId = trim(request.getDeviceId());
|
||||
if (username.isEmpty() || password.isEmpty()) {
|
||||
throw new BusinessException("请输入用户名和密码");
|
||||
}
|
||||
if (deviceId.isEmpty()) {
|
||||
throw new BusinessException("缺少设备ID,请在桌面端打开");
|
||||
}
|
||||
|
||||
LoginUserEntity user = loginUserMapper.selectOne(new LambdaQueryWrapper<LoginUserEntity>()
|
||||
.eq(LoginUserEntity::getUsername, username)
|
||||
.last("LIMIT 1"));
|
||||
if (user == null || !passwordEncoder.matches(password, user.getPasswordHash())) {
|
||||
throw new BusinessException("用户名或密码错误");
|
||||
}
|
||||
|
||||
boolean isAdmin = user.getIsAdmin() != null && user.getIsAdmin() == 1;
|
||||
String stored = user.getMachine() == null ? "" : user.getMachine().trim();
|
||||
if (stored.isEmpty()) {
|
||||
loginUserMapper.update(null, new LambdaUpdateWrapper<LoginUserEntity>()
|
||||
.eq(LoginUserEntity::getId, user.getId())
|
||||
.set(LoginUserEntity::getMachine, deviceId));
|
||||
stored = deviceId;
|
||||
log.info("[auth] first-login bind userId={} device={}", user.getId(), deviceId);
|
||||
} else if (!stored.equals(deviceId)) {
|
||||
if (isAdmin) {
|
||||
log.warn("[auth] device mismatch but admin bypass userId={} stored={} current={}",
|
||||
user.getId(), stored, deviceId);
|
||||
} else {
|
||||
log.warn("[auth] device mismatch reject userId={} stored={} current={}",
|
||||
user.getId(), stored, deviceId);
|
||||
throw new BusinessException("当前设备与首次登录设备不一致,请在原设备上登录");
|
||||
}
|
||||
} else {
|
||||
log.info("[auth] device match userId={} isAdmin={} device={}",
|
||||
user.getId(), isAdmin, deviceId);
|
||||
}
|
||||
|
||||
return buildResult(user, stored, isAdmin);
|
||||
}
|
||||
|
||||
public LoginResultVo checkLogin(String token, String currentDeviceId) {
|
||||
if (token == null || token.isBlank()) {
|
||||
throw new BusinessException(401, "未登录");
|
||||
}
|
||||
Claims claims = jwtService.parse(token);
|
||||
if (claims == null) {
|
||||
throw new BusinessException(401, "登录已过期,请重新登录");
|
||||
}
|
||||
Long userId;
|
||||
try {
|
||||
userId = Long.parseLong(claims.getSubject());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BusinessException(401, "登录态无效");
|
||||
}
|
||||
LoginUserEntity user = loginUserMapper.selectById(userId);
|
||||
if (user == null) {
|
||||
throw new BusinessException(401, "用户不存在");
|
||||
}
|
||||
boolean isAdmin = user.getIsAdmin() != null && user.getIsAdmin() == 1;
|
||||
String stored = user.getMachine() == null ? "" : user.getMachine().trim();
|
||||
String device = trim(currentDeviceId);
|
||||
if (device.isEmpty()) {
|
||||
// 没传设备 ID 时,回落到 token 内 deviceId
|
||||
Object claimDevice = claims.get("deviceId");
|
||||
device = claimDevice == null ? "" : claimDevice.toString().trim();
|
||||
}
|
||||
if (!stored.isEmpty() && !device.isEmpty() && !stored.equals(device)) {
|
||||
if (isAdmin) {
|
||||
log.warn("[auth] check_login device mismatch but admin bypass userId={} stored={} current={}",
|
||||
user.getId(), stored, device);
|
||||
} else {
|
||||
log.warn("[auth] check_login device mismatch reject userId={} stored={} current={}",
|
||||
user.getId(), stored, device);
|
||||
throw new BusinessException(401, "当前设备与首次登录设备不一致");
|
||||
}
|
||||
}
|
||||
return buildResult(user, stored.isEmpty() ? device : stored, isAdmin);
|
||||
}
|
||||
|
||||
public ResponseCookie buildAuthCookie(String token) {
|
||||
ResponseCookie.ResponseCookieBuilder builder = ResponseCookie.from(authProperties.getCookieName(), token)
|
||||
.httpOnly(true)
|
||||
.path("/")
|
||||
.maxAge(Duration.ofSeconds(jwtService.ttlSeconds()))
|
||||
.sameSite(authProperties.getCookieSameSite());
|
||||
if (authProperties.isCookieSecure()) {
|
||||
builder.secure(true);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public ResponseCookie buildClearCookie() {
|
||||
return ResponseCookie.from(authProperties.getCookieName(), "")
|
||||
.httpOnly(true)
|
||||
.path("/")
|
||||
.maxAge(Duration.ZERO)
|
||||
.sameSite(authProperties.getCookieSameSite())
|
||||
.secure(authProperties.isCookieSecure())
|
||||
.build();
|
||||
}
|
||||
|
||||
public String cookieName() {
|
||||
return authProperties.getCookieName();
|
||||
}
|
||||
|
||||
private LoginResultVo buildResult(LoginUserEntity user, String deviceId, boolean isAdmin) {
|
||||
String token = jwtService.issue(user.getId(), user.getUsername(), deviceId);
|
||||
LoginResultVo vo = new LoginResultVo();
|
||||
vo.setUserId(user.getId());
|
||||
vo.setUsername(user.getUsername());
|
||||
vo.setRole(user.getRole());
|
||||
vo.setIsAdmin(isAdmin);
|
||||
vo.setDeviceId(deviceId);
|
||||
vo.setToken(token);
|
||||
vo.setExpiresIn(jwtService.ttlSeconds());
|
||||
vo.setAppColumns(permissionMenuService.getUserColumnPermissions(user.getId(), PermissionMenuService.MENU_TYPE_APP));
|
||||
vo.setAdminColumns(permissionMenuService.getUserColumnPermissions(user.getId(), PermissionMenuService.MENU_TYPE_ADMIN));
|
||||
return vo;
|
||||
}
|
||||
|
||||
private static String trim(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.nanri.aiimage.modules.auth.service;
|
||||
|
||||
import com.nanri.aiimage.modules.auth.config.AuthProperties;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class JwtService {
|
||||
|
||||
private final AuthProperties props;
|
||||
|
||||
private SecretKey signingKey() {
|
||||
byte[] keyBytes = props.getJwtSecret().getBytes(StandardCharsets.UTF_8);
|
||||
if (keyBytes.length < 32) {
|
||||
byte[] padded = new byte[32];
|
||||
System.arraycopy(keyBytes, 0, padded, 0, keyBytes.length);
|
||||
keyBytes = padded;
|
||||
}
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
|
||||
public String issue(Long userId, String username, String deviceId) {
|
||||
Instant now = Instant.now();
|
||||
Instant exp = now.plus(Duration.ofHours(props.getJwtTtlHours()));
|
||||
return Jwts.builder()
|
||||
.subject(String.valueOf(userId))
|
||||
.claim("username", username)
|
||||
.claim("deviceId", deviceId)
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(exp))
|
||||
.signWith(signingKey())
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Claims parse(String token) {
|
||||
try {
|
||||
return Jwts.parser()
|
||||
.verifyWith(signingKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
} catch (JwtException | IllegalArgumentException e) {
|
||||
log.debug("[auth] jwt parse failed: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public long ttlSeconds() {
|
||||
return Duration.ofHours(props.getJwtTtlHours()).toSeconds();
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.nanri.aiimage.modules.auth.util;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.PBEKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* 兼容 Werkzeug `generate_password_hash` 的 PBKDF2-HMAC-SHA256 输出格式。
|
||||
* 形如:pbkdf2:sha256:iterations$salt$hexdigest(Werkzeug 默认 600000 轮、salt 16 位)。
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class WerkzeugPasswordEncoder {
|
||||
|
||||
private static final int DK_BITS = 32 * 8;
|
||||
private static final int DEFAULT_ITERATIONS = 600_000;
|
||||
private static final int SALT_LENGTH = 16;
|
||||
private static final String SALT_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
public String hash(String rawPassword) {
|
||||
if (rawPassword == null) {
|
||||
throw new IllegalArgumentException("password cannot be null");
|
||||
}
|
||||
String salt = generateSalt();
|
||||
try {
|
||||
byte[] derived = pbkdf2Sha256(rawPassword.toCharArray(),
|
||||
salt.getBytes(StandardCharsets.UTF_8), DEFAULT_ITERATIONS, DK_BITS);
|
||||
String hex = HexFormat.of().formatHex(derived);
|
||||
return "pbkdf2:sha256:" + DEFAULT_ITERATIONS + "$" + salt + "$" + hex;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("生成密码摘要失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean matches(String rawPassword, String storedHash) {
|
||||
if (rawPassword == null || storedHash == null || storedHash.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
int firstSep = storedHash.indexOf('$');
|
||||
int secondSep = storedHash.indexOf('$', firstSep + 1);
|
||||
if (firstSep < 0 || secondSep < 0) {
|
||||
return false;
|
||||
}
|
||||
String method = storedHash.substring(0, firstSep);
|
||||
String salt = storedHash.substring(firstSep + 1, secondSep);
|
||||
String expectedHex = storedHash.substring(secondSep + 1);
|
||||
if (!method.startsWith("pbkdf2:sha256")) {
|
||||
log.warn("[auth] unsupported password hash scheme: {}", method);
|
||||
return false;
|
||||
}
|
||||
String[] parts = method.split(":");
|
||||
int iterations = parts.length >= 3 ? Integer.parseInt(parts[2]) : 600_000;
|
||||
byte[] derived = pbkdf2Sha256(rawPassword.toCharArray(), salt.getBytes(StandardCharsets.UTF_8), iterations, DK_BITS);
|
||||
String actualHex = HexFormat.of().formatHex(derived);
|
||||
return constantTimeEquals(actualHex, expectedHex);
|
||||
} catch (Exception e) {
|
||||
log.warn("[auth] verify password failed: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] pbkdf2Sha256(char[] password, byte[] salt, int iterations, int keyBits) throws Exception {
|
||||
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyBits);
|
||||
try {
|
||||
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
|
||||
} finally {
|
||||
spec.clearPassword();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean constantTimeEquals(String a, String b) {
|
||||
if (a == null || b == null || a.length() != b.length()) {
|
||||
return false;
|
||||
}
|
||||
int diff = 0;
|
||||
for (int i = 0; i < a.length(); i++) {
|
||||
diff |= a.charAt(i) ^ b.charAt(i);
|
||||
}
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
private static String generateSalt() {
|
||||
StringBuilder sb = new StringBuilder(SALT_LENGTH);
|
||||
for (int i = 0; i < SALT_LENGTH; i++) {
|
||||
sb.append(SALT_ALPHABET.charAt(RANDOM.nextInt(SALT_ALPHABET.length())));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user