feat: 更新认证 Cookie 设置和状态检查日志记录

pull/1451/head
墨梓柒 2025-12-16 12:50:13 +08:00
parent 6d26d9a484
commit 4482be7142
No known key found for this signature in database
GPG Key ID: 4A65B9DBA35F7635
2 changed files with 17 additions and 4 deletions

View File

@ -88,16 +88,19 @@ def set_auth_cookie(response: Response, token: str) -> None:
# 根据环境决定安全设置
is_secure = _is_secure_environment()
# 设置 Cookie
response.set_cookie(
key=COOKIE_NAME,
value=token,
max_age=COOKIE_MAX_AGE,
httponly=True, # 防止 JS 读取,阻止 XSS 窃取
samesite="strict" if is_secure else "lax", # 生产环境使用 strict 防止 CSRF
samesite="lax", # 使用 lax 以兼容更多场景(开发和生产)
secure=is_secure, # 生产环境强制 HTTPS
path="/", # 确保 Cookie 在所有路径下可用
)
logger.debug(f"已设置认证 Cookie: {token[:8]}... (secure={is_secure})")
logger.info(f"已设置认证 Cookie: {token[:8]}... (secure={is_secure}, samesite=lax, httponly=True, path=/, max_age={COOKIE_MAX_AGE})")
logger.debug(f"完整 token 前缀: {token[:20]}...")
def clear_auth_cookie(response: Response) -> None:

View File

@ -195,23 +195,33 @@ async def check_auth_status(
"""
try:
token = None
# 记录请求信息用于调试
logger.debug(f"检查认证状态 - Cookie: {maibot_session[:20] if maibot_session else 'None'}..., Authorization: {'Present' if authorization else 'None'}")
# 优先从 Cookie 获取
if maibot_session:
token = maibot_session
logger.debug("使用 Cookie 中的 token")
# 其次从 Header 获取
elif authorization and authorization.startswith("Bearer "):
token = authorization.replace("Bearer ", "")
logger.debug("使用 Header 中的 token")
if not token:
logger.debug("未找到 token返回未认证")
return {"authenticated": False}
token_manager = get_token_manager()
if token_manager.verify_token(token):
is_valid = token_manager.verify_token(token)
logger.debug(f"Token 验证结果: {is_valid}")
if is_valid:
return {"authenticated": True}
else:
return {"authenticated": False}
except Exception:
except Exception as e:
logger.error(f"认证检查失败: {e}", exc_info=True)
return {"authenticated": False}