跳到内容

添加自定义身份验证

本指南介绍如何为 LangGraph Platform 应用程序添加自定义身份验证。本指南适用于 LangGraph Platform 和自托管部署。它不适用于您自己的自定义服务器中 LangGraph 开源库的独立使用。

注意

所有托管 LangGraph Platform 部署以及企业版自托管计划都支持自定义身份验证。精简版自托管计划不支持此功能。

为您的部署添加自定义身份验证

要在部署中利用自定义身份验证并访问用户级元数据,请设置自定义身份验证,通过自定义身份验证处理程序自动填充config["configurable"]["langgraph_auth_user"]对象。然后,您可以通过langgraph_auth_user键在图中访问此对象,以允许代理代表用户执行经过身份验证的操作

  1. 实现身份验证

    注意

    如果没有自定义的 @auth.authenticate 处理程序,LangGraph 只会看到 API 密钥所有者(通常是开发者),因此请求不会限定于单个最终用户。要传播自定义令牌,您必须实现自己的处理程序。

    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("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
        }
    
    1. 此处理程序接收请求(标头等),验证用户,并返回一个至少包含身份字段的字典。
    2. 您可以添加任何自定义字段(例如,OAuth 令牌、角色、组织 ID 等)。
  2. 在您的 langgraph.json 中,添加您的身份验证文件路径

    {
      "dependencies": ["."],
      "graphs": {
        "agent": "./agent.py:graph"
      },
      "env": ".env",
      "auth": {
        "path": "./auth.py:my_auth"
      }
    }
    
  3. 在服务器中设置身份验证后,请求必须根据您选择的方案包含所需的授权信息。假设您正在使用 JWT 令牌身份验证,您可以通过以下任何方法访问您的部署

    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="https://:2024",
        headers={"Authorization": f"Bearer {my_token}"}
    )
    threads = await client.threads.search()
    
    from langgraph.pregel.remote import RemoteGraph
    
    my_token = "your-token" # In practice, you would generate a signed token with your auth provider
    remote_graph = RemoteGraph(
        "agent",
        url="https://:2024",
        headers={"Authorization": f"Bearer {my_token}"}
    )
    threads = await remote_graph.ainvoke(...)
    
    import { Client } from "@langchain/langgraph-sdk";
    
    const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
    const client = new Client({
    apiUrl: "https://:2024",
    defaultHeaders: { Authorization: `Bearer ${my_token}` },
    });
    const threads = await client.threads.search();
    
    import { RemoteGraph } from "@langchain/langgraph/remote";
    
    const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
    const remoteGraph = new RemoteGraph({
    graphId: "agent",
    url: "https://:2024",
    headers: { Authorization: `Bearer ${my_token}` },
    });
    const threads = await remoteGraph.invoke(...);
    
    curl -H "Authorization: Bearer ${your-token}" https://:2024/threads
    

启用代理身份验证

身份验证后,平台会创建一个特殊的配置对象(config),该对象会传递给 LangGraph Platform 部署。此对象包含有关当前用户的信息,包括您从 @auth.authenticate 处理程序返回的任何自定义字段。

要允许代理代表用户执行经过身份验证的操作,请在图中通过 langgraph_auth_user 键访问此对象

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","")
    ...

注意

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

授权 Studio 用户

默认情况下,如果您在资源上添加自定义授权,这也将应用于从 Studio 进行的交互。如果您愿意,可以通过检查 is_studio_user() 来区别处理已登录的 Studio 用户。

注意

is_studio_user 是在 langgraph-sdk 0.1.73 版本中添加的。如果您使用的是旧版本,仍然可以检查 isinstance(ctx.user, StudioUser)

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

仅当您希望允许开发者访问部署在托管 LangGraph Platform SaaS 上的图时,才使用此功能。

了解更多