Authentication, authorization and secrets

Topic 2 of 4 in MCP, security & enterprise24 min readAdvancedFree course

Overview

An enterprise AI agent is more than a conversational interface. It can retrieve confidential documents, update databases, invoke MCP tools, interact with internal APIs, and execute business operations on behalf of users.

These capabilities introduce three fundamental security questions:

  • Authentication: Who is making the request?
  • Authorization: What is that identity permitted to do?
  • Secrets management: How does the application access protected systems without exposing credentials?

Consider an enterprise purchasing assistant. An employee may view purchase orders, a manager may approve them, and a finance administrator may initiate payments. Although all three users interact with the same assistant, their available operations must differ.

The language model cannot be responsible for enforcing these differences.

In the previous lesson, you learned how MCP connects agents to external capabilities. This lesson establishes the security boundaries that determine who may use those capabilities and under what conditions.

Install the dependencies used throughout this lesson:

Terminal
pip install "langgraph>=1,<2" "langchain[openai]>=1,<2" "PyJWT[crypto]>=2,<3" httpx

The deterministic examples require no external LLM calls. The live agent example requires a valid OpenAI API key and access to the specified model.

The golden rule

Never delegate security decisions to a language model.

A system prompt such as the following is not an authorization mechanism:

Text
Only managers may approve purchase orders.
Never reveal confidential information to unauthorized users.

These instructions may improve model behavior, but they do not establish an enforceable security boundary.

A user could falsely claim to be a manager. A retrieved document could contain malicious instructions. The model could misunderstand a request or generate an inappropriate tool call.

Your application must remain secure even when the model proposes the wrong action.

The following diagram illustrates the separation between model reasoning and trusted security enforcement.

The golden rule diagram: User request to Authentication; Authentication to Identity verified?; Identity verified? to Reject request (No); Identity verified? to Agent reasoning (Yes); Agent reasoning to Proposed tool call; Proposed tool call to Action authorized?; Action authorized? to Deny operation (No); Action authorized? to Protected service (Yes); Protected service to Safe result.

The model proposes an operation. Trusted Python code evaluates the operation against verified identity, permissions, resource ownership, and applicable business rules.

Only an authorized operation reaches the protected service.

Note: System prompts are behavioral instructions, not access-control policies. Security must remain effective even if the model completely ignores its instructions.

Authentication

Authentication establishes the identity of a caller before the agent begins processing a request.

In production, authentication commonly occurs at an API gateway, backend application, or LangSmith Agent Server integrated with an identity provider.

Common authentication mechanisms

Mechanism Typical use Important limitation
API key Service-to-service integration Often identifies an application rather than an individual
Session cookie Browser applications Requires secure session handling and CSRF protection
JWT access token Distributed APIs Requires signature and claim verification
OpenID Connect Enterprise user authentication Requires a trusted identity provider
Mutual TLS Workload authentication Does not automatically establish end-user permissions
Workload identity Cloud services and containers Requires appropriate identity and access policies

OAuth 2.0 provides a framework for delegated authorization. OpenID Connect extends OAuth with user authentication capabilities.

An API should accept an access token intended for that API, rather than treating an arbitrary ID token as an API credential.

Validating an access token

A JSON Web Token, or JWT, commonly contains claims describing its subject, issuer, audience, and expiration.

Decoding a JWT without verifying its signature does not authenticate anyone. An attacker can construct arbitrary token contents.

The following standalone example creates and validates a short-lived demonstration token using PyJWT. The signing key is randomly generated for local testing.

Python
import secrets
from datetime import datetime, timedelta, timezone

import jwt

ISSUER = "https://identity.example.com"
AUDIENCE = "enterprise-assistant"
SIGNING_KEY = secrets.token_urlsafe(48)

def authenticate(token: str) -> str:
    claims = jwt.decode(
        token,
        SIGNING_KEY,
        algorithms=["HS256"],
        issuer=ISSUER,
        audience=AUDIENCE,
        options={
            "require": ["sub", "iss", "aud", "exp", "iat"]
        },
    )
    return claims["sub"]

now = datetime.now(timezone.utc)

token = jwt.encode(
    {
        "sub": "employee-123",
        "iss": ISSUER,
        "aud": AUDIENCE,
        "iat": now,
        "exp": now + timedelta(minutes=5),
    },
    SIGNING_KEY,
    algorithm="HS256",
)

print(authenticate(token))

try:
    authenticate(token + ".invalid")
except jwt.InvalidTokenError:
    print("Authentication failed.")

Expected output:

Text
employee-123
Authentication failed.

The verification process checks the signature, permitted signing algorithm, expected issuer, intended audience, required claims, and token expiration.

In production, enterprise identity providers commonly issue asymmetrically signed tokens. Retrieve verification keys from a trusted, configured JWKS endpoint, accommodate signing-key rotation, and use the provider’s supported validation procedures.

Never select an unrestricted verification algorithm or trust an arbitrary key URL supplied by a token. For opaque access tokens, use the provider’s supported introspection mechanism instead.

Map the verified identity to application-specific tenant memberships and permissions using a trusted directory or database. A valid token does not automatically grant access to every application operation.

See the PyJWT verification documentation for supported validation mechanisms.

Passing authenticated identity into LangGraph

After authentication, the backend constructs a trusted runtime context.

Runtime context is appropriate for per-invocation identity information because it is separate from ordinary graph state and is not automatically inserted into model messages.

The following example injects an authenticated identity into a graph node.

Python
from dataclasses import dataclass
from typing import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime

@dataclass(frozen=True)
class Context:
    user_id: str
    tenant_id: str
    role: str

class State(TypedDict):
    request: str
    response: str

def identify_user(
    state: State,
    runtime: Runtime[Context],
) -> dict:
    identity = runtime.context

    if identity is None:
        raise PermissionError("Authentication required.")

    return {
        "response": f"Authenticated as {identity.user_id}"
    }

builder = StateGraph(State, context_schema=Context)
builder.add_node("identify_user", identify_user)
builder.add_edge(START, "identify_user")
builder.add_edge("identify_user", END)

graph = builder.compile()

identity = Context("employee-123", "acme", "employee")

result = graph.invoke(
    {"request": "Who am I?"},
    context=identity,
)

print(result["response"])

Expected output:

Text
Authenticated as employee-123

The graph does not derive identity from the user’s message. The backend supplies it through context.

A context schema is not itself an authentication mechanism. If clients can freely submit their own runtime context, they could assign themselves privileged roles. Therefore, construct or overwrite identity context on the trusted server.

The frozen dataclass prevents ordinary field reassignment, but it is not a sandbox or cryptographic security boundary.

Refer to the LangChain runtime documentation and LangGraph Graph API for context injection patterns.

Authorization and role-based access control

Authentication answers who the caller is. Authorization determines whether that caller may perform a particular operation.

An authenticated employee requesting an administrative action should receive an authorization failure, not additional privileges.

At the HTTP layer, 401 Unauthorized generally indicates missing or invalid authentication, while 403 Forbidden indicates that access is not permitted. Some applications deliberately return 404 Not Found for inaccessible resources to avoid disclosing their existence.

Understanding RBAC

Role-based access control, or RBAC, associates users with roles and roles with permissions.

Instead of maintaining individual permission lists for thousands of employees, administrators assign users to predefined business roles.

An example enterprise permission matrix is shown below.

Permission Employee Manager Finance administrator
Read purchase orders Allow Allow Allow
Create purchase orders Allow Allow Allow
Approve purchase orders Deny Allow Allow
Initiate payments Deny Deny Allow
Export financial reports Deny Deny Allow

These permissions are illustrative. Real organizations must also enforce spending limits, separation of duties, ownership restrictions, and approval requirements.

Implementing deterministic authorization

The following example combines role permissions with tenant-specific resource access.

Python
from dataclasses import dataclass

@dataclass(frozen=True)
class Principal:
    user_id: str
    tenant_id: str
    role: str

PERMISSIONS = {
    "employee": {"orders:read"},
    "manager": {"orders:read", "orders:approve"},
    "finance_admin": {
        "orders:read",
        "orders:approve",
        "payments:create",
    },
}

ORDERS = {
    "PO-101": {"tenant_id": "acme", "amount": 250},
    "PO-202": {"tenant_id": "globex", "amount": 900},
}

def authorize(
    principal: Principal,
    permission: str,
    order_id: str,
) -> bool:
    granted = PERMISSIONS.get(principal.role, set())

    if permission not in granted:
        return False

    order = ORDERS.get(order_id)

    return (
        order is not None
        and order["tenant_id"] == principal.tenant_id
    )

employee = Principal("u1", "acme", "employee")
manager = Principal("u2", "acme", "manager")
unknown = Principal("u3", "acme", "unknown")

print(authorize(employee, "orders:read", "PO-101"))
print(authorize(employee, "orders:approve", "PO-101"))
print(authorize(manager, "orders:approve", "PO-101"))
print(authorize(manager, "orders:read", "PO-202"))
print(authorize(unknown, "orders:read", "PO-101"))

Expected output:

Text
True
False
True
False
False

The policy follows deny by default: an operation is forbidden unless an explicit rule permits it.

A manager cannot access another organization’s purchase orders merely because their role permits reading orders.

Beyond roles

RBAC is useful but insufficient for contextual business decisions.

Attribute-based access control, or ABAC, considers additional properties of the user, resource, action, or environment.

For example:

  • A manager can approve purchases below $5,000.
  • Employees cannot approve their own reimbursement requests.
  • Contractors cannot access confidential financial records.
  • Suspended accounts cannot perform any operation.
  • Certain actions require recent multifactor authentication.

These restrictions should be implemented through deterministic policy functions or a centralized authorization service.

For sensitive writes, enforce resource conditions and execute the operation atomically where possible. Otherwise, permissions or resource attributes could change between authorization and execution.

Tool permission management

Tools are particularly important security boundaries because they connect model-generated decisions to real-world effects.

A model-generated tool call is an untrusted operation proposal, not proof that an action is permitted.

A secure tool architecture uses multiple layers:

  1. Restrict which tools are presented to the model.
  2. Authorize every actual tool invocation.
  3. Check the specific resource and operation arguments.
  4. Enforce permissions again in the downstream service.

Using ToolRuntime for trusted identity

LangChain’s ToolRuntime provides application-supplied runtime information to tools without requiring the model to generate it as part of the tool arguments.

For example, a document-reading tool should accept a document identifier from the model, but obtain the caller’s identity and tenant from runtime.context.

This prevents a model from selecting an arbitrary tenant or privileged identity through ordinary tool arguments.

The following complete agent combines dynamic tool filtering, execution-time middleware, and resource-level authorization.

Python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.agents.middleware import (
    wrap_model_call,
    wrap_tool_call,
)
from langchain.chat_models import init_chat_model
from langchain.messages import ToolMessage
from langchain.tools import tool, ToolRuntime

@dataclass(frozen=True)
class Context:
    user_id: str
    tenant_id: str
    role: str

PERMISSIONS = {
    "employee": {"read_order"},
    "manager": {"read_order", "approve_order"},
}

ORDERS = {
    ("acme", "PO-101"): "Laptop purchase: $1,200",
    ("globex", "PO-202"): "Server purchase: $8,000",
}

APPROVALS = set()

def allowed(context: Context, action: str) -> bool:
    return (
        isinstance(context, Context)
        and action in PERMISSIONS.get(context.role, set())
    )

@tool
def read_order(order_id: str, runtime: ToolRuntime) -> str:
    """Read a purchase order in the current organization."""
    context = runtime.context

    if not allowed(context, "read_order"):
        return "Access denied."

    return ORDERS.get(
        (context.tenant_id, order_id),
        "Order unavailable.",
    )

@tool
def approve_order(order_id: str, runtime: ToolRuntime) -> str:
    """Approve a purchase order in the current organization."""
    context = runtime.context

    if not allowed(context, "approve_order"):
        return "Access denied."

    key = (context.tenant_id, order_id)

    if key not in ORDERS:
        return "Order unavailable."

    APPROVALS.add(key)
    return f"Approved {order_id}."

@wrap_model_call
def filter_tools(request, handler):
    context = request.runtime.context

    visible_tools = [
        candidate
        for candidate in request.tools
        if allowed(context, candidate.name)
    ]

    return handler(
        request.override(tools=visible_tools)
    )

@wrap_tool_call
def enforce_permissions(request, handler):
    context = request.runtime.context
    call = request.tool_call

    if not allowed(context, call["name"]):
        return ToolMessage(
            content="Access denied.",
            tool_call_id=call["id"],
            status="error",
        )

    return handler(request)

model = init_chat_model("openai:gpt-5.4-mini")

agent = create_agent(
    model=model,
    tools=[read_order, approve_order],
    context_schema=Context,
    middleware=[filter_tools, enforce_permissions],
    system_prompt=(
        "You are a purchasing assistant. "
        "Use available tools for business operations. "
        "Never claim an operation succeeded unless "
        "the tool confirms success."
    ),
)

employee = Context("u1", "acme", "employee")

result = agent.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "Read and approve PO-101.",
            }
        ]
    },
    config={"recursion_limit": 20},
    context=employee,
)

print(result["messages"][-1].content)
assert not APPROVALS

Expected behavior: the employee can retrieve PO-101, but cannot approve it. The exact natural-language response varies with the model.

The assertion checks the security outcome rather than depending on the model’s wording.

The middleware uses the current create_agent interface documented in the LangChain custom middleware guide.

Understanding the execution lifecycle

Before a model invocation, filter_tools selects tool definitions allowed for the current identity.

If a model produces a tool call, enforce_permissions independently evaluates that call before executing it.

The tool then checks its own permission and obtains the tenant from trusted context.

Finally, the resource lookup restricts access to data belonging to that tenant.

These layers serve different purposes. Tool filtering improves model behavior and reduces unnecessary exposure. Execution guards enforce permissions. Resource checks prevent cross-tenant access.

Tip: Hiding a tool is not sufficient authorization. Test forbidden tool calls directly, independently of whether the model is likely to generate them.

Securing MCP tools

MCP tool discovery establishes which capabilities a server advertises. It does not establish that a particular user may invoke every advertised capability.

When integrating MCP servers:

  • Maintain approved tool and server inventories.
  • Map tool identifiers to application permissions.
  • Deny newly discovered tools until their access policy is established.
  • Authorize each invocation, including its target resource.
  • Isolate user-specific credentials and sessions.
  • Require the MCP server to enforce its own authorization policies.

For asynchronous MCP integrations, use asynchronous tool middleware and invoke the agent asynchronously.

Protected HTTP-based MCP integrations should follow the protocol’s OAuth authorization requirements. Access tokens must be intended for the receiving MCP resource server. Do not blindly forward an incoming application token to unrelated downstream APIs.

Local STDIO servers rely on process and environment security rather than the HTTP authorization flow. Restrict inherited environment variables and operating-system permissions.

See the MCP authorization specification.

Least privilege for credentials

The principle of least privilege requires granting an identity only the permissions necessary to perform its intended operation.

There are two separate permission boundaries in an enterprise agent:

Boundary Example
User authorization An employee may read orders
Service credential authorization The order-reading service may execute read-only queries

Both must permit the operation. Neither should substitute for the other.

An agent connected to a database through a superuser account presents unnecessary risk, even if its Python tools normally execute harmless queries.

Prefer narrowly scoped credentials:

  • Read-only database accounts for retrieval tools.
  • Dedicated write permissions for specific business operations.
  • Short-lived access tokens restricted to their intended audiences.
  • Separate development and production identities.
  • Workload identities instead of permanent cloud access keys.

The following diagram illustrates isolated credential usage.

Least privilege for credentials diagram: Agent tools to Read service; Agent tools to Approval service; Secrets manager to Read service; Secrets manager to Approval service; Read service to Read database; Approval service to Approval API.

The model never receives either service’s credentials.

Delegated identity versus service identity

A delegated access token represents authorization granted to an application on behalf of a user. A service identity represents the application or workload itself.

When supported, delegated authorization lets downstream services enforce user-specific permissions directly.

When service credentials are necessary, the application must enforce the originating user’s permissions before using those credentials.

The latter prevents the agent from becoming a confused deputy: a privileged intermediary that performs operations an unprivileged caller could not execute independently.

Secrets management

A secret is a sensitive value that grants access to a protected system. Examples include API keys, passwords, OAuth refresh tokens, database credentials, and private signing keys.

Secrets have a broader exposure surface in agentic applications because intermediate data may be persisted, streamed, traced, or forwarded to a model provider.

Where secrets should and should not live

Location Store raw secrets?
Source code No
System prompts No
Graph state and messages No
Checkpoints No
Long-term agent memory No
Tool arguments and responses No
Logs and traces No
Environment variables Acceptable for controlled development or deployment
Dedicated secrets manager Preferred for managed static secrets
Short-lived workload credentials Preferred when supported

Runtime context is separate from graph state, but it is not automatically a secure vault. Instrumentation or application code could still expose its contents.

Prefer injecting credential-provider interfaces or restricted service clients rather than raw credentials.

Keeping credentials inside the service layer

The following example uses HTTPX with a mocked external service. It demonstrates attaching a credential to an HTTP request without returning that credential to the agent.

No network connection or real credential is required.

Python
import os
import secrets

import httpx

def read_order(client: httpx.Client) -> dict:
    api_key = os.environ["ORDERS_READ_API_KEY"]

    try:
        response = client.get(
            "/orders/PO-101",
            headers={"Authorization": f"Bearer {api_key}"},
        )
        response.raise_for_status()
        data = response.json()

        return {
            "order_id": data["order_id"],
            "status": data["status"],
        }

    except httpx.HTTPError:
        raise RuntimeError(
            "Order service unavailable."
        ) from None

def mock_service(request: httpx.Request) -> httpx.Response:
    expected = f"Bearer {os.environ['ORDERS_READ_API_KEY']}"

    if request.headers.get("Authorization") != expected:
        return httpx.Response(401)

    return httpx.Response(
        200,
        json={"order_id": "PO-101", "status": "pending"},
    )

os.environ["ORDERS_READ_API_KEY"] = secrets.token_urlsafe(32)

try:
    with httpx.Client(
        base_url="https://orders.example.com",
        transport=httpx.MockTransport(mock_service),
        timeout=10.0,
        follow_redirects=False,
    ) as client:
        print(read_order(client))
finally:
    os.environ.pop("ORDERS_READ_API_KEY", None)

Expected output:

Text
{'order_id': 'PO-101', 'status': 'pending'}

The credential is used exclusively by the HTTP service layer. The returned object contains only selected business fields.

This example demonstrates credential isolation, not user authorization. Combine it with the authorization checks developed earlier before exposing the service through an agent tool.

In production, use an approved HTTPS destination, validated certificates, a dedicated credential provider, restricted network egress, and sanitized exception handling.

Production secrets managers

Common enterprise options include HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, and Google Cloud Secret Manager.

A secrets manager centralizes credential storage, access policies, lifecycle management, and access auditing.

Prefer retrieving secrets through workload identity so that the application does not require another permanent secret merely to authenticate to the secrets manager.

Implement rotation as an operational process: provision the replacement credential, test it, refresh consumers, and revoke the old credential. Short-lived credentials reduce the exposure window but still require proper expiration and revocation enforcement.

If a credential is accidentally exposed, revoke or rotate it immediately. Deleting it from a source file is insufficient because copies may exist in repository history, traces, checkpoints, or backups.

The OWASP Secrets Management Cheat Sheet provides additional lifecycle guidance.

Security in persistent and deployed agents

LangGraph persistence introduces additional access-control requirements.

A thread_id identifies persisted execution history. It does not establish who owns that history or who may access it.

Before reading, updating, streaming, or resuming a thread, authenticate the caller and verify ownership or explicitly delegated access.

When using human-in-the-loop interrupts, reconstruct trusted context on resume and reauthorize sensitive actions. A permission granted yesterday may have been revoked today. Human approval does not override an authorization denial.

Similarly, avoid caching authorization-sensitive responses unless the cache incorporates the relevant security context and supports appropriate invalidation.

LangSmith Agent Server supports custom authentication through @auth.authenticate handlers and resource authorization through @auth.on handlers. These deployment-level controls complement business authorization inside graph nodes and tools.

Consult the Agent Server authentication and access-control guide when configuring a deployment.

Observability systems require independent access controls. Avoid capturing raw authorization headers, credentials, sensitive client objects, or unrestricted request bodies. Verify redaction before enabling production tracing.

Common mistakes and production practices

Common mistake Correct practice
Trusting a role stated in chat Resolve roles from verified identity
Accepting a model-generated tenant ID Inject tenant identity through trusted context
Relying on system prompts for security Enforce deterministic authorization
Hiding forbidden tools only Check permission at execution time
Sharing administrator credentials Use narrowly scoped service identities
Saving tokens in graph state Keep credentials in the service layer
Trusting an old approval indefinitely Reauthorize before executing
Treating thread IDs as passwords Enforce resource ownership
Caching results across identities Apply security-aware cache isolation
Returning raw upstream errors Return sanitized error information

Security testing should include missing identities, expired tokens, unknown roles, cross-tenant identifiers, forbidden tool calls, revoked permissions, and credential leakage through logs or exceptions.

Test authorization directly without an LLM wherever possible. Security properties should hold deterministically across all model behaviors.

The examples in this lesson use synthetic identities, in-memory records, and mocked infrastructure to isolate the security mechanisms. Their APIs were checked against current documentation; live model execution and external identity-provider integration were not tested here.

Connection to the next lesson

For this chapter’s secure MCP-enabled enterprise assistant, establish authenticated identity, server-controlled runtime context, explicit tool permissions, resource-level authorization, and isolated credential handling before enabling real enterprise integrations.

These mechanisms control which operations an agent can perform, but authorized operations can still process malicious instructions or inappropriate data.

The next lesson, Prompt injection, validation and PII protection, examines how to protect agents against hostile content, validate model-generated inputs and tool outputs, and prevent sensitive information from reaching unauthorized destinations.

Exercise

Build a permission-aware enterprise assistant

Build a LangGraph workflow that enforces role-based tool permissions using trusted runtime context. Implement employee and manager roles with tenant-specific document access, ensuring that only managers can approve documents. Test authorized requests, unauthorized requests, cross-tenant access attempts, and unknown roles without making any external LLM calls.

Python
from dataclasses import dataclass

from langchain.messages import AIMessage
from langchain.tools import tool, ToolRuntime
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode

@dataclass(frozen=True)
class Context:
    user_id: str
    tenant_id: str
    role: str

PERMISSIONS = {
    "employee": {"read_document"},
    "manager": {"read_document", "approve_document"},
}

DOCUMENTS = {
    ("acme", "DOC-101"): "Pending purchase order",
    ("globex", "DOC-202"): "Confidential purchase order",
}

APPROVALS = set()

def is_allowed(context: Context, action: str) -> bool:
    # TODO: Implement deny-by-default authorization.
    raise NotImplementedError

@tool
def read_document(document_id: str, runtime: ToolRuntime) -> str:
    """Read a document belonging to the current organization."""
    # TODO: Check permission and enforce tenant isolation.
    raise NotImplementedError

@tool
def approve_document(document_id: str, runtime: ToolRuntime) -> str:
    """Approve a document belonging to the current organization."""
    # TODO: Check permission before modifying APPROVALS.
    raise NotImplementedError

# TODO: Build and compile a StateGraph using ToolNode.
# TODO: Pass authenticated identity through context_schema.
# TODO: Simulate tool calls with AIMessage.
# TODO: Test successful and denied operations.

Summary

  • Authentication establishes the caller's identity while authorization determines which operations that identity may perform.
  • Language models propose actions, but deterministic application code must enforce security policies.
  • Trusted runtime context carries verified identity and permissions independently of model-generated tool arguments.
  • Tool visibility reduces unnecessary exposure, but every sensitive operation still requires execution-time authorization.
  • Role-based permissions must be combined with resource ownership and tenant-specific access checks.
  • Least-privilege credentials limit the consequences of compromised tools, services, and agent executions.
  • Secrets must remain outside prompts, graph state, checkpoints, tool responses, and unprotected observability systems.