Skip to content
LangSmith 文档版本 跟随上游 源快照 947ea832 更新于 2026-10-18

添加自定义认证

本指南展示如何为你的 LangSmith 应用添加自定义认证。本页步骤同时适用于 cloud 和 self-hosted 部署,不适用于在你自己的自定义服务器中单独使用 LangGraph 开源库 的场景。

为你的部署添加自定义认证

为了利用自定义认证并在部署中访问用户级元数据,请设置自定义认证,通过自定义认证处理器自动填充 config["configurable"]["langgraph_auth_user"] 对象。之后,你可以在图中通过 langgraph_auth_user 键访问该对象,从而允许 agent 代表用户执行已认证的操作。

  1. 实现认证:

NOTE

如果没有自定义的 @auth.authenticate 处理器,LangGraph 只能看到 API key 的拥有者(通常是开发者),因此请求不会按最终用户区分。要传播自定义 token,你必须实现自己的处理器。

python
from langgraph_sdk import Auth
import requests

auth = Auth()

def is_valid_key(api_key: str) -> bool:
    is_valid = # your API key validation logic
    return is_valid

@auth.authenticate # (1)!
async def authenticate(headers: dict) -> Auth.types.MinimalUserDict:
    api_key = headers.get(b"x-api-key")
    if not api_key or not is_valid_key(api_key):
        raise Auth.exceptions.HTTPException(status_code=401, detail="Invalid API key")

    # Fetch user-specific tokens from your secret store
    user_tokens = await fetch_user_tokens(api_key)

    return { # (2)!
        "identity": api_key,  #  fetch user ID from LangSmith
        "github_token" : user_tokens.github_token
        "jira_token" : user_tokens.jira_token
        # ... custom fields/secrets here
    }
  • 该处理器接收请求(headers 等),验证用户,并返回一个至少包含 identity 字段的字典。
  • 你可以添加任意自定义字段(例如 OAuth token、roles、org ID 等)。
  1. 在你的 langgraph.json 中,添加认证文件的路径:

    json
    {
        "dependencies": ["."],
        "graphs": {
        "agent": "./agent.py:graph"
        },
        "env": ".env",
        "auth": {
            "path": "./auth.py:my_auth"
        }
    }
  2. 在服务器中设置好认证后,请求必须根据你选择的方案包含所需的授权信息。假设你使用 JWT token 认证,可以通过以下任意方式访问你的部署:

python
from langgraph_sdk import get_client

my_token = "your-token" # In practice, you would generate a signed token with your auth provider
client = get_client(
    url="http://localhost:2024",
    headers={"Authorization": f"Bearer {my_token}"}
)
threads = await client.threads.search()

有关 RemoteGraph 的更多细节,请参阅使用 RemoteGraph 指南。

启用 agent 认证

认证完成后,平台会创建一个特殊的配置对象(config),并将其传递给 LangSmith 部署。该对象包含当前用户的信息,包括你从 @auth.authenticate 处理器返回的任何自定义字段。

要允许 agent 代表用户执行已认证的操作,请在图中通过 langgraph_auth_user 键访问该对象:

python
def my_node(state, config):
    user_config = config["configurable"].get("langgraph_auth_user")
    # token was resolved during the @auth.authenticate function
    token = user_config.get("github_token","")
    ...

NOTE

从安全的密钥存储中获取用户凭据。不建议将密钥存储在图的 state 中。

为 Studio 授权用户

默认情况下,如果你为资源添加了自定义授权,这也适用于从 Studio 发起的交互。如果需要,你可以通过检查 is_studio_user() 来区别对待已登录的 Studio 用户。

NOTE

is_studio_user 是在 langgraph-sdk 0.1.73 版本中加入的。如果你使用的是更早的版本,仍可以检查 isinstance(ctx.user, StudioUser)。

python
from langgraph_sdk.auth import is_studio_user, Auth
auth = Auth()

# ... Setup authenticate, etc.

@auth.on
async def add_owner(
    ctx: Auth.types.AuthContext,
    value: dict  # The payload being sent to this access method
) -> dict:  # Returns a filter dict that restricts access to resources
    if is_studio_user(ctx.user):
        return {}

    filters = {"owner": ctx.user.identity}
    metadata = value.setdefault("metadata", {})
    metadata.update(filters)
    return filters

仅当你希望允许开发者访问托管在 LangSmith SaaS 上的图时,才使用这种方式。

了解更多


BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。