本指南向您展示如何向 LangSmith 应用程序添加自定义身份验证。本页的步骤适用于 云 和 self-hosted 部署。它不适用于在您自己的自定义服务器中独立使用 LangGraph 开源库 的情况。
向您的部署添加自定义身份验证
要利用自定义身份验证并访问部署中的用户级元数据,请设置自定义身份验证以自动填充 config["configurable"]["langgraph_auth_user"] 对象通过自定义身份验证处理程序。然后您可以使用 langgraph_auth_user 密钥来 允许代理代表用户执行已身份验证的操作.
- 实现身份验证:
from langgraph_sdk import Auth
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
}
- - 此处理程序接收请求(标头等),验证用户,并返回至少包含身份字段的字典。
- - 您可以添加所需的任何自定义字段(例如 OAuth 令牌、角色、组织 ID 等)。
- 在您的
langgraph.json中添加身份验证文件的路径:
{
"dependencies": ["."],
"graphs": {
"agent": "./agent.py:graph"
},
"env": ".env",
"auth": {
"path": "./auth.py:my_auth"
}
}
- 在服务器中设置身份验证后,请求必须根据您选择的方案包含所需的授权信息。假设您使用 JWT 令牌身份验证,您可以使用以下任一方法访问您的部署:
Python Client
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()
Python RemoteGraph
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="http://localhost:2024",
headers={"Authorization": f"Bearer {my_token}"}
)
threads = await remote-graph.ainvoke(...)
JavaScript Client
const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
const client = new Client({
apiUrl: "http://localhost:2024",
defaultHeaders: { Authorization: `Bearer ${my_token}` },
});
const threads = await client.threads.search();
JavaScript RemoteGraph
const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
const remoteGraph = new RemoteGraph({
graphId: "agent",
url: "http://localhost:2024",
headers: { Authorization: `Bearer ${my_token}` },
});
const threads = await remoteGraph.invoke(...);
CURL
curl -H "Authorization: Bearer ${your-token}" http://localhost:2024/threads
有关 RemoteGraph 的更多详细信息,请参阅 使用 RemoteGraph guide.
启用代理身份验证
在 身份验证之后,平台会创建一个特殊配置对象(config)传递给 LangSmith 部署。此对象包含当前用户的信息,包括您从 @auth.authenticate handler.
返回的任何自定义字段。为了允许代理代表用户执行已身份验证的操作,请在图形中使用 langgraph_auth_user key:
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进行的交互。如果您希望不同处理已登录的 Studio 用户,可以检查 is_studio_用户()。.
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 上部署的图形时使用。
了解更多
- * 身份验证与访问控制
- * 设置自定义身份验证教程