A demonstration project showing how to add custom authentication to your LangChain agents using LangGraph's authentication system.
This project demonstrates how to implement custom authentication for LangChain agents, allowing you to:
- Validate API keys and authenticate users
- Inject user-specific secrets and tokens into your agent context
- Filter resources by user ownership
- Customize behavior for LangSmith Studio users vs. API users
sequenceDiagram
participant Client as Client App
participant Auth as Auth Provider
participant LG as Agent Server
Client->>Auth: 1. Login (username/password)
Auth-->>Client: 2. Return token
Client->>LG: 3. Request with token
Note over LG: 4. Validate token (@auth.authenticate)
LG-->>Auth: 5. Fetch user info
Auth-->>LG: 6. Confirm validity
Note over LG: 7. Apply access control (@auth.on.*)
LG-->>Client: 8. Return resources
langchain-custom-auth/
├── agents/
│ ├── agent_01_basic.py # Example calendar agent
│ └── models.py # Model configuration
├── auths/
│ └── basic_auth.py # Custom authentication logic
├── langgraph.json # LangGraph configuration
└── pyproject.toml # Project dependencies
Point LangGraph to your custom auth module in langgraph.json:
{
"dependencies": ["."],
"graphs": {
"agent_01_basic": "./agents/agent_01_basic.py:agent"
},
"env": ".env",
"auth": {
"path": "./auths/basic_auth.py:auth"
}
}Optional: Disable Authentication in Studio
For development and testing, you can disable authentication requirements in LangSmith Studio while keeping them enabled for API calls:
{
"auth": {
"disable_studio_auth": true
}
}This allows you to test your agent in Studio without providing authentication headers, while still requiring authentication for production API usage.
The auths/basic_auth.py file contains two key components:
Use the @auth.authenticate decorator to validate incoming requests and return user information:
from langgraph_sdk.auth import Auth
auth = Auth()
@auth.authenticate
async def authenticate(headers: dict) -> Auth.types.MinimalUserDict:
# Extract API key from headers
api_key = headers.get(b"x-api-key")
# Validate the API key
if not api_key or not is_valid_key(api_key):
raise Auth.exceptions.HTTPException(
status_code=401,
detail="Invalid API key"
)
# Return user identity and custom secrets
return {
"identity": api_key,
"github_token": "github_token",
"jira_token": "jira_token",
# Add any custom fields/secrets here
}Key points:
- Extract authentication credentials from request headers
- Validate credentials against your authentication system
- Return a dictionary containing:
identity: Required field identifying the user- Custom fields: Any user-specific tokens, secrets, or configuration
Use the @auth.on decorator to filter resources and add metadata based on the authenticated user:
from langgraph_sdk.auth import is_studio_user
@auth.on
async def add_owner(
ctx: Auth.types.AuthContext,
value: dict
) -> dict:
# Check if request is from LangSmith Studio
if is_studio_user(ctx.user):
print("Studio user - no filtering")
return {}
# For API users, filter resources by owner
filters = {"owner": ctx.user.identity}
metadata = value.setdefault("metadata", {})
metadata.update(filters)
return filtersKey points:
- Use
is_studio_user(ctx.user)to detect Studio users - Return empty filters
{}for Studio users (full access for testing) - For API users, add ownership filters to restrict access to their resources
- Automatically inject metadata into requests
- Install dependencies:
pip install -e .- Set up your environment variables in
.env:
OPENAI_API_KEY=your_openai_key
ANTHROPIC_API_KEY=your_anthropic_key- Start the LangGraph development server:
langgraph dev- Open LangSmith Studio in your browser and connect to your local agent
The is_studio_user() function enables different behavior for testing vs. production:
| Context | Detected By | Behavior |
|---|---|---|
| LangSmith Studio | is_studio_user() returns True |
Full access, no filtering (for testing) |
| API Calls | is_studio_user() returns False |
Filtered by user ownership |
This allows you to:
- Test your agent graphically in Studio with full access to all data
- Ensure production API users only see their own resources
- Debug authentication issues in a user-friendly interface
The project includes a basic calendar agent (agents/agent_01_basic.py) that demonstrates:
- Tool definition with
@tooldecorator - Agent creation with
create_agent() - Integration with the authentication system
- LangSmith Authentication Overview
- LangSmith Custom Authentication for Studio
- LangGraph SDK Authentication API Reference
MIT