Skip to content

langchain-samples/langchain-custom-auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LangChain Custom Authentication

A demonstration project showing how to add custom authentication to your LangChain agents using LangGraph's authentication system.

Overview

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

Authentication Flow

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
Loading

Project Structure

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

Custom Authentication Setup

1. Configure Authentication in langgraph.json

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.

2. Implement Authentication Logic

The auths/basic_auth.py file contains two key components:

a. Authentication Handler

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

b. Authorization and Resource Filtering

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 filters

Key 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

Testing with LangSmith Studio

Running the Agent Locally

  1. Install dependencies:
pip install -e .
  1. Set up your environment variables in .env:
OPENAI_API_KEY=your_openai_key
ANTHROPIC_API_KEY=your_anthropic_key
  1. Start the LangGraph development server:
langgraph dev
  1. Open LangSmith Studio in your browser and connect to your local agent

Studio vs. API Behavior

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

Example Agent

The project includes a basic calendar agent (agents/agent_01_basic.py) that demonstrates:

  • Tool definition with @tool decorator
  • Agent creation with create_agent()
  • Integration with the authentication system

References

License

MIT

About

Teamplate to get started with LangChain Auth

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages