第 9 讲:用户认证与权限管理

OpenHands 源码解析 · 第 9 讲

OpenHands 源码解析系列 第 9 讲:用户认证与权限管理 基于 OpenHands 源码 · 2026-08-05 一、认证架构总览 OpenHands 的认证体系分为两个世界: 🔹 OSS 模式(开源版) :单用户,无多租户,使用 DefaultUserAuth 🔹 SaaS 模式(企业版) :多租户 + Keycloak SSO,使用 SaasUserAuth 两者共享同一个抽象基类 UserAuth ,通过配置切换实现。 📦 核心文件 openhands/app_server/user_auth/user_auth.py — 抽象基类 openhands/app_server/user_auth/default_user_auth.py — OSS 默认实现 enterprise/server/auth/saas_user_auth.py — SaaS Keycloak 实现 enterprise/server/auth/authorization.py — 权限模型 enterprise/server/routes/auth.py — 认证路由 二、UserAuth 抽象基类 UserAuth 是整个认证系统的核心抽象。它定义了所有认证实现必须提供的接口: 📄 openhands/app_server/user_auth/user_auth.py (第 30-125 行) class AuthType(Enum): COOKIE = 'cookie' BEARER = 'bearer' class UserAuth(ABC): """Abstract base class for user authentication. This is an extension point in OpenHands that allows applications to provide their own authentication mechanisms. Applications can substitute their own implementation by: 1. Creating a class that inherits from UserAuth 2. Implementing all required methods 3. Setting server_config.user_auth_class to the fully qualified name of the class The class is instantiated via get_impl() in openhands.app_server.shared.py. """ _settings: Settings | None _resolved_settings: Settings | None = None @abstractmethod async def get_user_id(self) -> str | None: """Get the unique identifier for the current user""" @abstractmethod async def get_user_email(self) -> str | None: """Get the email for the current user""" @abstractmethod async def get_access_token(self) -> SecretStr | None: """Get the access token for the current user""" @abstractmethod async def get_provider_tokens(self) -> PROVIDER_TOKEN_TYPE | None: """Get the provider tokens for the current user.""" @abstractmethod async def get_user_settings_store(self) -> SettingsStore: """Get the settings store for the curren…

阅读全文:OpenHands 源码解析 第 9 讲