agentic_huge_data_base / wiki
页面 Onyx · 9.4 会话管理·DeepWiki 中文全文译文

9.4 · 会话管理(Session Management)

企业连接器与统一搜索 · 本章是 Onyx DeepWiki 中文译文的独立章节页,保留原始链接、源码锚点、模块标签和章节层级。

项目Onyx 章节9.4 状态全文译文 模块存储与持久化、配置治理、文档对象与元数据、系统架构
源码线索
  • backend/alembic/versions/74379b447d4c_add_paste_as_tile_to_user.py
  • backend/ee/onyx/main.py
  • backend/ee/onyx/server/auth_check.py
  • backend/ee/onyx/server/enterprise_settings/api.py
  • backend/ee/onyx/server/enterprise_settings/store.py
  • backend/onyx/auth/schemas.py
  • backend/onyx/auth/users.py
  • backend/onyx/db/enums.py
  • backend/onyx/db/models.py
  • backend/onyx/db/user_preferences.py
模块标签
  • 存储与持久化
  • 配置治理
  • 文档对象与元数据
  • 系统架构
  • 测试、发布与运维

中文译文

会话管理(中文译文)

原始 DeepWiki 页面:https://deepwiki.com/onyx-dot-app/onyx/9.4-session-management
翻译时间:2026-05-27T08:44:48.668Z
翻译模型:deepseek-chat
原文字符数:11478
项目:Onyx (onyx)

---

会话管理

相关源文件

以下文件被用作生成此 Wiki 页面的上下文:

  • backend/alembic/versions/74379b447d4c_add_paste_as_tile_to_user.py
  • backend/ee/onyx/main.py
  • backend/ee/onyx/server/auth_check.py
  • backend/ee/onyx/server/enterprise_settings/api.py
  • backend/ee/onyx/server/enterprise_settings/store.py
  • backend/onyx/auth/schemas.py
  • backend/onyx/auth/users.py
  • backend/onyx/db/enums.py
  • backend/onyx/db/models.py
  • backend/onyx/db/user_preferences.py
  • backend/onyx/main.py
  • backend/onyx/server/auth_check.py
  • backend/onyx/server/manage/get_state.py
  • backend/onyx/server/manage/models.py
  • backend/onyx/server/manage/users.py
  • backend/onyx/server/runtime/onyx_runtime.py
  • backend/onyx/server/saml.py
  • backend/onyx/utils/file.py
  • backend/static/images/logo.png
  • backend/tests/api/test_api.py
  • backend/tests/unit/onyx/auth/test_single_tenant_jwt_strategy.py
  • backend/tests/unit/onyx/server/scim/test_admin.py
  • deployment/aws_ecs_fargate/cloudformation/services/onyx_nginx_service_template.yaml
  • deployment/aws_ecs_fargate/cloudformation/services/onyx_web_server_service_template.yaml
  • web/src/app/auth/saml/callback/route.ts
  • web/src/hooks/useTokenRefresh.test.tsx
  • web/src/hooks/useTokenRefresh.ts
  • web/src/lib/redirectSS.ts
  • web/src/providers/UserProvider.tsx

目的与范围

本文档描述了 Onyx 中的会话管理系统,该系统负责处理跨 HTTP 请求的用户认证状态。系统支持多种后端存储选项(Redis、PostgreSQL 和 JWT),使用仅 HTTP 的 Cookie 传输会话令牌,并通过 SESSION_EXPIRE_TIME_SECONDS 实现可配置的令牌过期策略。

关于认证方法(OAuth、OIDC、SAML)的信息,请参见认证方法。关于用户角色和权限,请参见用户角色与权限。关于多租户架构和租户隔离,请参见多租户架构

---

会话架构总览

Onyx 利用 fastapi-users 库管理用户会话。系统通过 AUTH_BACKEND 配置支持可插拔的后端存储,允许部署选择 Redis(默认)、PostgreSQL 或 JWT 进行会话持久化 backend/onyx/auth/users.py:86

会话生命周期图

sequenceDiagram
    participant Client as "Web 浏览器"
    participant API as "FastAPI 服务器"
    participant Auth as "认证后端"
    participant Storage as "Redis / PostgreSQL / JWT"
    participant Cookie as "Cookie 传输"

    Client->>API: POST /auth/login (凭据)
    API->>Auth: authenticate()
    Auth->>Auth: verify_password()
    Auth->>Storage: create_session_token()
    Storage-->>Auth: token_id
    Auth->>Cookie: set_login_cookie()
    Cookie-->>Client: Set-Cookie: fastapiusersauth=token
    Client->>API: GET /chat (携带 Cookie)
    API->>Cookie: read_token_from_cookie()
    Cookie->>Auth: get_strategy().read_token()
    Auth->>Storage: lookup_token(token_id)
    Storage-->>Auth: user_id + expiry
    Auth->>API: 返回 User 对象
    API-->>Client: 200 OK (响应)
    Client->>API: POST /auth/logout
    API->>Auth: logout()
    Auth->>Storage: delete_token(token_id)
    Auth->>Cookie: delete_cookie()
    Cookie-->>Client: Set-Cookie: fastapiusersauth=; Max-Age=0

来源: backend/onyx/auth/users.py:45-53, backend/onyx/configs/app_configs.py:86-101

---

后端存储选项

会话后端通过 AUTH_BACKEND 环境变量进行配置 backend/onyx/configs/app_configs.py:86。系统支持 AuthBackend 枚举中定义的三种后端实现 backend/onyx/auth/schemas.py:76-80

后端存储位置使用场景配置
Redis(默认)内存键值存储高性能部署、水平扩展AUTH_BACKEND=redis
PostgreSQL数据库中的 AccessToken简化基础设施、单数据库部署AUTH_BACKEND=postgres
JWT无状态客户端数据库查询开销较大的微服务场景AUTH_BACKEND=jwt

后端选择架构

graph TB
    subgraph "配置"
        EnvVar["AUTH_BACKEND<br/>环境变量"]
        AuthBackendEnum["AuthBackend 枚举<br/>onyx.auth.schemas.AuthBackend"]
    end

    subgraph "策略层"
        AuthBackend["AuthenticationBackend<br/>fastapi_users.authentication.AuthenticationBackend"]
        CookieTransport["CookieTransport<br/>fastapi_users.authentication.CookieTransport"]
        StrategyFactory["get_strategy()"]
    end

    subgraph "Redis 后端"
        RedisStrategy["RedisStrategy<br/>fastapi_users.authentication.RedisStrategy"]
        RedisClient["get_async_redis_connection()"]
    end

    subgraph "PostgreSQL 后端"
        DatabaseStrategy["DatabaseStrategy<br/>fastapi_users.authentication.strategy.db.DatabaseStrategy"]
        AccessTokenTable["AccessToken 表<br/>onyx.db.models.AccessToken"]
    end

    subgraph "JWT 后端"
        JWTStrategy["JWTStrategy<br/>fastapi_users.authentication.JWTStrategy"]
    end

    EnvVar --> AuthBackendEnum
    AuthBackendEnum --> StrategyFactory
    StrategyFactory -->|"AUTH_BACKEND=redis"| RedisStrategy
    StrategyFactory -->|"AUTH_BACKEND=postgres"| DatabaseStrategy
    StrategyFactory -->|"AUTH_BACKEND=jwt"| JWTStrategy

    AuthBackend --> CookieTransport
    AuthBackend --> StrategyFactory

来源: backend/onyx/auth/schemas.py:76-80, backend/onyx/auth/users.py:45-53, backend/onyx/db/models.py:126

---

令牌过期与生命周期

会话持续时间由 SESSION_EXPIRE_TIME_SECONDS 控制 backend/onyx/configs/app_configs.py:99。该值决定了 Redis 键的 TTL 以及数据库支持令牌的有效期窗口。

关键配置变量
  1. SESSION_EXPIRE_TIME_SECONDS:会话长度的主要控制参数(默认值:1 天或 86400 秒)backend/onyx/configs/app_configs.py:99
  2. AUTH_COOKIE_EXPIRE_TIME_SECONDS:专门控制认证 Cookie 的 Max-Age 属性 backend/onyx/configs/app_configs.py:87
令牌创建追踪

系统会追踪当前会话令牌的创建时间,通过 UserInfo 模型为前端提供安全上下文 backend/onyx/server/manage/models.py:123-140UserInfo.from_model 工厂方法会填充这些字段 backend/onyx/server/manage/models.py:141-153

get_current_token_creation 的实现因后端而异:

  • PostgreSQL:通过 get_latest_access_token_for_user 查询特定用户的 AccessToken 模型 backend/onyx/db/user_preferences.py:115-131
  • 前端使用UserInfo 对象包含 current_token_created_atcurrent_token_expiry_length,允许客户端处理会话警告或自动刷新 backend/onyx/server/manage/models.py:133-134

来源: backend/onyx/configs/app_configs.py:87-99, backend/onyx/server/manage/models.py:123-153, backend/onyx/db/user_preferences.py:115-131

---

PostgreSQL 后端实现

PostgreSQL 后端使用 AccessToken 模型持久化会话。这对于不希望为认证单独管理 Redis 实例的部署场景非常有用。

数据模型:AccessToken

定义在 backend/onyx/db/models.py 中,它继承自 SQLAlchemyBaseAccessTokenTableUUID backend/onyx/db/models.py:126

字段类型描述
token字符串会话标识符(主键)
user_idUUID指向 User 表的外键
created_at日期时间会话创建的时间戳
策略实现

DatabaseStrategy 通过 get_access_token_db 初始化,该方法会生成一个链接到 AccessToken 模型的 AccessTokenDatabase backend/onyx/db/auth.py:116

来源: backend/onyx/db/models.py:126, backend/onyx/db/auth.py:116, backend/onyx/auth/users.py:52-53

---

其他令牌类型

除了标准 Web 会话外,Onyx 还通过专用令牌支持程序化访问:

个人访问令牌(PAT)

用于特定用户的长期 API 访问。

  • 验证fetch_user_for_pat 验证哈希令牌并检查过期状态 backend/onyx/db/pat.py:130
API 密钥

用于服务账户风格的访问。

  • 验证fetch_user_for_api_key 查找关联的虚拟用户 backend/onyx/db/api_key.py:115

令牌验证流程

graph TD
    subgraph "认证中间件"
        Request["传入请求"]
        CheckHeader{"检查请求头"}
    end

    subgraph "PAT 流程"
        HashedPAT["get_hashed_pat_from_request()"]
        VerifyPAT["fetch_user_for_pat()"]
    end

    subgraph "API 密钥流程"
        HashedKey["get_hashed_api_key_from_request()"]
        VerifyKey["fetch_user_for_api_key()"]
    end

    Request -->|Authorization: Bearer| CheckHeader
    CheckHeader -->|以 'onyx_pat_' 开头| HashedPAT
    CheckHeader -->|以 'onyx_api_key_' 开头| HashedKey

    HashedPAT --> VerifyPAT
    HashedKey --> VerifyKey

    VerifyPAT -->|"有效且未过期"| User["注入用户对象"]
    VerifyKey -->|"有效"| User

来源: backend/onyx/auth/users.py:74-81, backend/onyx/db/pat.py:130, backend/onyx/db/api_key.py:115

---

会话销毁

会话通过 /auth/logout 端点(由 FastAPIUsers 提供)销毁。

  • Redis:与 REDIS_AUTH_KEY_PREFIX 关联的键会被失效 backend/onyx/auth/users.py:97
  • PostgreSQL:从 accesstoken 表中删除具有匹配 token 的行 backend/onyx/db/auth.py:116
  • Cookie:浏览器被指示清除 FASTAPI_USERS_AUTH_COOKIE_NAME backend/onyx/configs/constants.py:110

来源: backend/onyx/auth/users.py:45-53, backend/onyx/configs/constants.py:110, backend/onyx/configs/app_configs.py:97