将基于Authentification校验替换成基于Cookie校验
This commit is contained in:
parent
6b042eed63
commit
c95565e1dd
@ -3,6 +3,7 @@ package com.doc.parser.infrastructure.north.controller;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@ -28,7 +29,7 @@ public class LoginController {
|
||||
private static final long TOKEN_EXPIRE_MS = 24 * 60 * 60 * 1000L; // 24 小时
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<?> login(@RequestBody Map<String, String> body) {
|
||||
public ResponseEntity<?> login(@RequestBody Map<String, String> body, HttpServletResponse response) {
|
||||
String username = body.getOrDefault("username", "").trim();
|
||||
String password = body.getOrDefault("password", "").trim();
|
||||
|
||||
@ -36,19 +37,29 @@ public class LoginController {
|
||||
return ResponseEntity.status(401).body(Map.of("message", "用户名或密码错误"));
|
||||
}
|
||||
|
||||
String token = UUID.randomUUID().toString();
|
||||
token = token.replace("-", "");
|
||||
String token = UUID.randomUUID().toString().replace("-", "");
|
||||
tokenStore.put(token, System.currentTimeMillis());
|
||||
userMap.put(token, username);
|
||||
|
||||
javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("auth_token", token);
|
||||
cookie.setPath("/");
|
||||
cookie.setHttpOnly(false); // 建议生产环境为 true,这里为兼容前端 JS 读写可设为 false
|
||||
cookie.setMaxAge((int)(TOKEN_EXPIRE_MS / 1000));
|
||||
response.addCookie(cookie);
|
||||
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"token", token,
|
||||
"username", username
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("/check")
|
||||
public ResponseEntity<?> check(@RequestHeader("Authorization") String token) {
|
||||
public ResponseEntity<?> check(
|
||||
@CookieValue(value = "auth_token", required = false) String cookieToken,
|
||||
@RequestHeader(value = "Authorization", required = false) String headerToken
|
||||
) {
|
||||
String token = headerToken != null ? headerToken : cookieToken;
|
||||
if (isValidToken(token)) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("code", 0);
|
||||
@ -61,6 +72,7 @@ public class LoginController {
|
||||
return ResponseEntity.status(401).body(result);
|
||||
}
|
||||
|
||||
|
||||
public static boolean isValidToken(String token) {
|
||||
if (token == null || !tokenStore.containsKey(token)) return false;
|
||||
long loginAt = tokenStore.get(token);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user