> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# A2A Security

> Secure A2A endpoints with authentication, authorization, and access control

A2A security enables authentication and authorization for agent-to-agent communication, protecting endpoints while maintaining protocol compliance.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "A2A Security Flow"
        Client[🧠 Agent Client] --> Auth{🔒 Auth Check}
        Auth -->|Valid| A2A[📡 A2A Endpoint]
        Auth -->|Invalid| Deny[❌ 401 Denied]
        A2A --> Response[✅ Response]
        Discovery[🔍 Discovery] --> Card[📋 Agent Card]
    end
    
    classDef client fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef auth fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef endpoint fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef response fill:#10B981,stroke:#7C90A0,color:#fff
    classDef discovery fill:#8B0000,stroke:#7C90A0,color:#fff
    
    class Client client
    class Auth,Deny auth
    class A2A endpoint
    class Response response
    class Discovery,Card discovery
```

***

## Quick Start

<Steps>
  <Step title="Basic Bearer Token">
    Protect your A2A endpoint with a simple bearer token:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent
    from praisonaiagents.ui.a2a import A2A

    agent = Agent(
        name="Secure Agent", 
        role="Helper", 
        goal="Help users securely"
    )

    a2a = A2A(
        agent=agent,
        auth_token="sk-my-secret-key"
    )

    a2a.serve(port=8000)
    ```
  </Step>

  <Step title="Client Authentication">
    Connect to protected endpoints using authorization headers:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    import requests

    # Authenticated request
    response = requests.post(
        "http://localhost:8000/a2a",
        headers={
            "Authorization": "Bearer sk-my-secret-key",
            "Content-Type": "application/json"
        },
        json={
            "jsonrpc": "2.0",
            "method": "message/send",
            "id": "1",
            "params": {
                "message": {
                    "role": "user",
                    "parts": [{"text": "Hello"}]
                }
            }
        }
    )
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Client as Agent Client
    participant A2A as A2A Server
    participant Agent as PraisonAI Agent
    
    Note over Client,Agent: Discovery (Always Public)
    Client->>A2A: GET /.well-known/agent.json
    A2A-->>Client: Agent Card (no auth required)
    
    Note over Client,Agent: Authenticated Interaction
    Client->>A2A: POST /a2a + Bearer Token
    A2A->>A2A: Verify Token
    alt Valid Token
        A2A->>Agent: Process Request
        Agent-->>A2A: Response
        A2A-->>Client: Success Response
    else Invalid Token
        A2A-->>Client: 401 Unauthorized
    end
```

| Component              | Security Level | Purpose                     |
| ---------------------- | -------------- | --------------------------- |
| **Discovery Endpoint** | Public         | Agent card per A2A spec     |
| **A2A Endpoint**       | Protected      | Authenticated communication |
| **Status Endpoint**    | Public         | Health checks               |

***

## Security Configurations

### Bearer Token Authentication

The simplest authentication method using a shared secret:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents.ui.a2a import A2A

# Basic bearer token setup
a2a = A2A(
    agent=agent,
    auth_token="sk-prod-your-secure-token-here"
)
```

### Client Example

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Valid request with token
curl -X POST http://localhost:8000/a2a \
  -H "Authorization: Bearer sk-prod-your-secure-token-here" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "message/send",
    "id": "1",
    "params": {
      "message": {
        "role": "user",
        "parts": [{"text": "Hello"}]
      }
    }
  }'

# Invalid token returns 401
curl -X POST http://localhost:8000/a2a \
  -H "Authorization: Bearer invalid-token" \
  -H "Content-Type: application/json" \
  -d '{...}'
# Returns: {"error": {"code": 401, "message": "Invalid token"}}
```

### Extended Agent Card

When authentication is enabled, the agent card can indicate security requirements:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Agent card includes security metadata
agent_card = a2a.get_agent_card()
# Discovery endpoint remains public per A2A specification
```

***

## Common Patterns

### Environment-Based Tokens

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import os
from praisonaiagents import Agent
from praisonaiagents.ui.a2a import A2A

agent = Agent(name="Production Agent", role="Assistant", goal="Help users")

a2a = A2A(
    agent=agent,
    auth_token=os.getenv("A2A_AUTH_TOKEN"),  # From environment
    url="https://api.example.com/a2a"
)
```

### FastAPI Integration

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from fastapi import FastAPI
from praisonaiagents import Agent
from praisonaiagents.ui.a2a import A2A

app = FastAPI()
agent = Agent(name="API Agent", role="Helper", goal="Serve requests")

a2a = A2A(
    agent=agent,
    auth_token="sk-api-secure-token",
    prefix="/api/v1"  # Mount at /api/v1/a2a
)

app.include_router(a2a.get_router())

# Discovery: GET /api/v1/.well-known/agent.json (public)
# A2A: POST /api/v1/a2a (protected)
```

### Multi-Environment Setup

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents.ui.a2a import A2A

def create_secured_agent(env: str):
    """Create agent with environment-specific security."""
    
    tokens = {
        "development": "sk-dev-token",
        "staging": "sk-staging-secure-token", 
        "production": "sk-prod-highly-secure-token"
    }
    
    agent = Agent(
        name=f"{env.title()} Agent",
        role="Environment Helper",
        goal=f"Handle {env} requests securely"
    )
    
    return A2A(
        agent=agent,
        auth_token=tokens.get(env),
        url=f"https://{env}.example.com/a2a"
    )

# Usage
prod_a2a = create_secured_agent("production")
prod_a2a.serve(port=8000)
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Token Security">
    * Use cryptographically secure random tokens (32+ characters)
    * Store tokens in environment variables, never in code
    * Rotate tokens regularly in production environments
    * Use different tokens for different environments
    * Consider using prefixes like `sk-prod-`, `sk-dev-` for identification
  </Accordion>

  <Accordion title="Discovery Compliance">
    * Keep `/.well-known/agent.json` public per A2A specification
    * Only protect the `/a2a` endpoint with authentication
    * Ensure agent cards don't expose sensitive information
    * Status endpoints can remain public for health checks
  </Accordion>

  <Accordion title="Error Handling">
    * Return standard HTTP 401 for invalid/missing tokens
    * Use consistent error message format
    * Log authentication attempts for monitoring
    * Implement rate limiting for failed authentication attempts
  </Accordion>

  <Accordion title="Production Deployment">
    * Use HTTPS in production environments
    * Implement proper logging and monitoring
    * Consider API gateways for additional security layers
    * Set up proper CORS policies for web clients
    * Monitor token usage patterns for anomalies
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="A2A Protocol" icon="handshake" href="/features/a2a">
    Learn the A2A protocol basics and setup
  </Card>

  <Card title="Agent API" icon="api" href="/features/agent-api-launch">
    RESTful API endpoints for agent services
  </Card>
</CardGroup>
