> ## 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.

# API Server Authentication

> Authentication for auto-generated API servers created by praisonai deploy

API servers generated by `praisonai deploy run --type api` require bearer token authentication by default as of PraisonAI 4.6.34.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "API Authentication Flow"
        A[📝 Request] --> B[🔍 Auth Check]
        B -->|Valid Token| C[✅ 200 OK]
        B -->|Invalid/Missing| D[❌ 401 Unauthorized]
    end
    
    classDef request fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef process fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef success fill:#10B981,stroke:#7C90A0,color:#fff
    classDef error fill:#8B0000,stroke:#7C90A0,color:#fff
    
    class A request
    class B process
    class C success
    class D error
```

## Quick Start

<Steps>
  <Step title="Default (auth on)">
    Start the API server and capture the auto-generated token from stderr:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai deploy run --type api
    # Look for output like:
    # [praisonai-api] generated API token: abc123def456ghi789...
    ```

    Then make authenticated requests:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    curl -H "Authorization: Bearer abc123def456ghi789..." \
         http://127.0.0.1:8080/agents
    ```
  </Step>

  <Step title="Bring your own token">
    Set your own bearer token before starting:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    export PRAISONAI_API_TOKEN=your-secret-token
    praisonai deploy run --type api
    ```

    Use your token in requests:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    curl -H "Authorization: Bearer your-secret-token" \
         http://127.0.0.1:8080/agents
    ```
  </Step>

  <Step title="Disable auth (legacy)">
    <Warning>
      Not recommended for production. Only use in trusted private networks.
    </Warning>

    Disable authentication explicitly:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    export PRAISONAI_API_AUTH=disabled
    export PRAISONAI_API_HOST=0.0.0.0  # Optional: bind to all interfaces
    praisonai deploy run --type api
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Client
    participant API Server
    participant Auth Check
    
    Client->>API Server: GET /agents
    API Server->>Auth Check: Validate Authorization header
    Auth Check-->>API Server: Check Bearer token
    API Server-->>Client: 401 Unauthorized (no token)
    
    Client->>API Server: GET /agents<br/>Authorization: Bearer token123
    API Server->>Auth Check: Validate Bearer token123
    Auth Check-->>API Server: ✅ Valid token
    API Server-->>Client: 200 OK + agent list
```

| Component                    | Purpose                                     |
| ---------------------------- | ------------------------------------------- |
| **Bearer Token**             | Secret key required in Authorization header |
| **Constant-time Comparison** | Prevents timing oracle attacks              |
| **stderr Output**            | Auto-generated tokens printed securely      |
| **Environment Override**     | `PRAISONAI_API_TOKEN` for custom tokens     |

***

## Environment Variables

| Variable              | Default          | Purpose                                                                                                                              |
| --------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `PRAISONAI_API_AUTH`  | `enabled`        | `enabled` (default) or `disabled`                                                                                                    |
| `PRAISONAI_API_TOKEN` | *auto-generated* | Bearer token required when auth is enabled. If unset, a 32-byte URL-safe random token is generated at startup and printed to stderr. |
| `PRAISONAI_API_HOST`  | `127.0.0.1`      | Bind host. Set to `0.0.0.0` only behind an authenticating proxy.                                                                     |
| `PRAISONAI_API_PORT`  | `8080`           | Bind port.                                                                                                                           |

### Configuration Examples

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Default secure setup
praisonai deploy run --type api

# Custom token
export PRAISONAI_API_TOKEN=my-secret-key-123
praisonai deploy run --type api

# Disable auth (not recommended)
export PRAISONAI_API_AUTH=disabled
praisonai deploy run --type api

# Bind to all interfaces with auth
export PRAISONAI_API_HOST=0.0.0.0
export PRAISONAI_API_TOKEN=secure-token
praisonai deploy run --type api
```

***

## APIConfig Reference

The `APIConfig` class in `praisonai.deploy.models` now defaults to secure settings:

```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
deploy:
  type: api
  api:
    host: 127.0.0.1        # Changed from 0.0.0.0
    port: 8080
    workers: 1
    cors_enabled: true
    auth_enabled: true     # Changed from false
```

### Before vs After 4.6.34

```diff theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
 deploy:
   type: api
   api:
-    host: 0.0.0.0
+    host: 127.0.0.1
     port: 8080
     workers: 1
     cors_enabled: true
-    auth_enabled: false
+    auth_enabled: true
```

***

## Security Details

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Client
    participant Server
    participant Validator
    
    Note over Client,Validator: Security Flow
    Client->>Server: POST /chat<br/>Authorization: Bearer token123
    Server->>Validator: secrets.compare_digest(token, expected)
    Validator-->>Server: True/False (constant-time)
    alt Valid Token
        Server-->>Client: 200 OK + response
    else Invalid Token
        Server-->>Client: 401 Unauthorized
    end
```

### Security Features

* **Constant-time token comparison** using `secrets.compare_digest()` prevents timing oracle attacks
* **Auto-generated tokens** are cryptographically secure (32 bytes, URL-safe)
* **stderr output only** - tokens never appear in HTTP responses or logs
* **Localhost binding by default** - reduces attack surface
* **Unauthenticated health endpoint** at `/health` for monitoring

### Token Generation

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Equivalent to the auto-generation process
import secrets
token = secrets.token_urlsafe(32)  # 43 character URL-safe string
```

***

## Common Patterns

### cURL Examples

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Get available agents
curl -H "Authorization: Bearer YOUR_TOKEN" \
     http://127.0.0.1:8080/agents

# Chat with agent
curl -X POST http://127.0.0.1:8080/chat \
     -H "Authorization: Bearer YOUR_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"message": "Hello, how can you help me?"}'

# Health check (no auth required)
curl http://127.0.0.1:8080/health
```

### Python Requests

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

# Set up session with auth
session = requests.Session()
session.headers.update({
    "Authorization": "Bearer YOUR_TOKEN",
    "Content-Type": "application/json"
})

# Get agents
response = session.get("http://127.0.0.1:8080/agents")
agents = response.json()

# Chat with agent
response = session.post("http://127.0.0.1:8080/chat", json={
    "message": "What is artificial intelligence?"
})
chat_response = response.json()
```

### Environment File Setup

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# .env file
PRAISONAI_API_TOKEN=your-secure-token-here
PRAISONAI_API_HOST=127.0.0.1
PRAISONAI_API_PORT=8080
PRAISONAI_API_AUTH=enabled
```

***

## Migration from \< 4.6.34

<AccordionGroup>
  <Accordion title="I just want my old setup back" icon="arrow-left">
    **Quick fix** for existing deployments:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Disable auth and bind to all interfaces (like before)
    export PRAISONAI_API_AUTH=disabled
    export PRAISONAI_API_HOST=0.0.0.0
    praisonai deploy run --type api
    ```

    <Warning>
      This removes security protections. Only use in trusted environments.
    </Warning>
  </Accordion>

  <Accordion title="I want to keep auth on but rotate the token" icon="key">
    **Recommended approach**:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Generate your own token
    export PRAISONAI_API_TOKEN=$(openssl rand -base64 32)
    praisonai deploy run --type api
    echo "Your token: $PRAISONAI_API_TOKEN"
    ```

    Store the token securely and update your clients.
  </Accordion>

  <Accordion title="I want my server reachable on the LAN" icon="network-wired">
    **Secure LAN deployment**:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Bind to all interfaces but keep auth enabled
    export PRAISONAI_API_HOST=0.0.0.0
    export PRAISONAI_API_TOKEN=your-secure-shared-token
    praisonai deploy run --type api
    ```

    Share the token only with trusted clients on your network.
  </Accordion>
</AccordionGroup>

***

## Best Practices

<AccordionGroup>
  <Accordion title="Token Management" icon="key">
    * **Generate strong tokens**: Use `openssl rand -base64 32` or similar
    * **Rotate tokens regularly**: Update `PRAISONAI_API_TOKEN` and restart
    * **Store securely**: Never commit tokens to version control
    * **Use environment variables**: Keep tokens out of configuration files
    * **Scope tokens appropriately**: Different tokens for dev/staging/prod
  </Accordion>

  <Accordion title="Network Security" icon="network-wired">
    * **Default localhost binding**: Keep `host: 127.0.0.1` unless necessary
    * **TLS termination**: Front with nginx/cloudflare for HTTPS
    * **Firewall rules**: Restrict port 8080 access to known sources
    * **VPN access**: Use VPN instead of public exposure when possible
  </Accordion>

  <Accordion title="Development vs Production" icon="flask">
    * **Development**: Use auto-generated tokens, localhost binding
    * **Staging**: Custom tokens, restricted network access
    * **Production**: Strong tokens, TLS frontend, monitoring
    * **CI/CD**: Separate tokens per environment, secret management
  </Accordion>

  <Accordion title="Monitoring and Logging" icon="chart-bar">
    * **Monitor `/health`**: Unauthenticated endpoint for status checks
    * **Log 401 responses**: Track authentication failures
    * **Alert on token exposure**: Watch for tokens in logs/errors
    * **Audit token usage**: Track which clients use which tokens
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Security Best Practices" icon="shield-check" href="/security">
    Overall security guidance for PraisonAI deployments
  </Card>

  <Card title="Agents API Reference" icon="server" href="/deploy/api/agents-api">
    HTTP API endpoints for Agent.launch() servers (different authentication)
  </Card>
</CardGroup>
