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

# Authentication

> Secure your API requests

All Chatbot Platform API requests require authentication using API keys. This guide covers how to create, manage, and use API keys securely.

## API Keys

API keys are bearer tokens that authenticate requests to the Chatbot Platform API.

### Creating an API Key

<Steps>
  <Step title="Go to Settings">
    Navigate to your team settings in the dashboard.
  </Step>

  <Step title="Open API Keys">
    Click **API Keys** in the sidebar.
  </Step>

  <Step title="Create New Key">
    Click **Create API Key**.

    Provide:

    * **Name**: Descriptive name (e.g., "Production Server")
    * **Permissions**: Select scopes (all by default)
  </Step>

  <Step title="Copy Key">
    Copy the generated key immediately - it won't be shown again.

    Format: `sk_live_abc123xyz...`
  </Step>

  <Step title="Store Securely">
    Save the key in your environment variables or secrets manager.
  </Step>
</Steps>

<Callout type="warning">
  API keys provide full access to your team's resources. Never share them or commit them to version control.
</Callout>

## Using API Keys

Include your API key in the `Authorization` header:

```bash theme={null}
curl https://api.chatbotplatform.io/v1/bots \
  -H "Authorization: Bearer sk_live_abc123xyz..."
```

### Environment Variables

Store keys as environment variables:

**Bash**:

```bash theme={null}
export CHATBOT_API_KEY="sk_live_abc123xyz..."
```

**Node.js**:

```javascript theme={null}
const apiKey = process.env.CHATBOT_API_KEY;

fetch('https://api.chatbotplatform.io/v1/bots', {
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  }
});
```

**Python**:

```python theme={null}
import os
import requests

api_key = os.environ['CHATBOT_API_KEY']

response = requests.get(
    'https://api.chatbotplatform.io/v1/bots',
    headers={
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }
)
```

## Key Types

### Live Keys

Production keys with full access:

```
sk_live_abc123xyz...
```

Use for production environments only.

### Test Keys (Coming Soon)

Sandbox keys for development:

```
sk_test_abc123xyz...
```

Use for development and testing without affecting production data.

## Permissions and Scopes

API keys can have restricted permissions:

| Scope                 | Access                     |
| --------------------- | -------------------------- |
| `bots:read`           | View bots                  |
| `bots:write`          | Create/update bots         |
| `integrations:read`   | View integrations          |
| `integrations:write`  | Create/update integrations |
| `channels:read`       | View channels              |
| `channels:write`      | Create/update channels     |
| `conversations:read`  | View conversations         |
| `conversations:write` | Delete conversations       |
| `agent-loops:read`    | View agent loops           |
| `agent-loops:write`   | Create/run agent loops     |
| `admin`               | Full access to everything  |

### Creating Restricted Keys

For security, create keys with minimal required permissions:

```
Production API Key:
Permissions:
  ✓ bots:read
  ✓ conversations:read
  ✗ bots:write
  ✗ admin
```

This key can view but not modify resources.

## Authentication Errors

### Invalid Key

```json theme={null}
{
  "error": {
    "code": "INVALID_API_KEY",
    "message": "The provided API key is invalid"
  }
}
```

**Status**: 401 Unauthorized

**Causes**:

* Key is incorrect
* Key was deleted
* Wrong key format

### Expired Key (Coming Soon)

```json theme={null}
{
  "error": {
    "code": "API_KEY_EXPIRED",
    "message": "This API key has expired"
  }
}
```

**Status**: 401 Unauthorized

### Insufficient Permissions

```json theme={null}
{
  "error": {
    "code": "INSUFFICIENT_PERMISSIONS",
    "message": "API key does not have permission to perform this action",
    "required_scope": "bots:write"
  }
}
```

**Status**: 403 Forbidden

## Key Management

### Rotating Keys

Periodically rotate API keys for security:

<Steps>
  <Step title="Create New Key">
    Generate a new API key with the same permissions.
  </Step>

  <Step title="Update Applications">
    Deploy the new key to all services using it.
  </Step>

  <Step title="Verify">
    Confirm all services are using the new key successfully.
  </Step>

  <Step title="Delete Old Key">
    Remove the old key to prevent unauthorized access.
  </Step>
</Steps>

### Revoking Keys

Immediately revoke a key if compromised:

<Steps>
  <Step title="Go to API Keys">
    Navigate to API Keys settings.
  </Step>

  <Step title="Find Key">
    Locate the compromised key.
  </Step>

  <Step title="Delete">
    Click **Delete** to revoke immediately.
  </Step>

  <Step title="Create New">
    Generate a replacement key.
  </Step>
</Steps>

Deleted keys stop working immediately.

## Webhook Authentication

For incoming webhooks (callbacks, bot messages), verify requests using signatures:

### Webhook Signature

Incoming webhooks include a signature header:

```
X-Chatbot-Signature: sha256=abc123...
```

### Verifying Signatures (Coming Soon)

```javascript theme={null}
const crypto = require('crypto');

function verifySignature(payload, signature, secret) {
  const hmac = crypto.createHmac('sha256', secret);
  const computed = 'sha256=' + hmac.update(payload).digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(computed)
  );
}

app.post('/webhook', (req, res) => {
  const signature = req.headers['x-chatbot-signature'];
  const payload = JSON.stringify(req.body);

  if (!verifySignature(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  // Process webhook...
});
```

## Security Best Practices

<CardGroup cols={2}>
  <Card title="Use Environment Variables" icon="key">
    Never hardcode API keys in source code
  </Card>

  <Card title="Rotate Regularly" icon="rotate">
    Change keys every 90 days or when employees leave
  </Card>

  <Card title="Minimal Permissions" icon="shield">
    Grant only necessary scopes per key
  </Card>

  <Card title="Secure Storage" icon="vault">
    Store keys in environment variables or secrets managers
  </Card>
</CardGroup>

### Secure Storage

**Do**:

* Use environment variables
* Store in secrets managers (AWS Secrets Manager, HashiCorp Vault)
* Encrypt at rest
* Restrict access to keys

**Don't**:

* Commit to Git
* Store in plaintext files
* Share via email or chat
* Use same key across all environments

### Production vs Development

Use separate keys for each environment:

```
Development: sk_live_dev_...
Staging: sk_live_staging_...
Production: sk_live_prod_...
```

This isolates environments and limits blast radius if compromised.

## Rate Limiting

API keys are subject to rate limits. See [API Introduction](/api-reference/introduction) for details.

## Troubleshooting

### Authentication Fails

**Check**:

* Key is correct and complete
* Authorization header format: `Bearer YOUR_KEY`
* No extra spaces or characters
* Key hasn't been deleted

### Intermittent Failures

**Possible Causes**:

* Rate limiting
* Clock skew (for signatures)
* Network issues

**Solutions**:

* Implement exponential backoff
* Sync system clock
* Add retry logic

### Key Not Working After Creation

**Wait a few seconds**: Keys may take 5-10 seconds to propagate.

## Next Steps

<CardGroup cols={2}>
  <Card title="API Introduction" icon="book" href="/api-reference/introduction">
    Learn about API basics
  </Card>

  <Card title="Bot Management" icon="robot">
    API endpoints for bots (coming soon)
  </Card>
</CardGroup>
