diff --git a/src/webui/auth.py b/src/webui/auth.py index 86621714..deecbf1e 100644 --- a/src/webui/auth.py +++ b/src/webui/auth.py @@ -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: diff --git a/src/webui/routes.py b/src/webui/routes.py index bb92d6cc..7f9909c1 100644 --- a/src/webui/routes.py +++ b/src/webui/routes.py @@ -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}