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

# API Authentication

> Secure authentication methods for the deployERP API

## Overview

The deployERP API uses Bearer token authentication. All API requests must include a valid API key in the Authorization header. This guide covers authentication setup, best practices, and troubleshooting.

## Authentication Methods

<CardGroup cols={2}>
  <Card title="API Keys" icon="key">
    Long-lived tokens for programmatic access
  </Card>

  <Card title="OAuth 2.0" icon="shield">
    Coming soon: OAuth flow for third-party apps
  </Card>
</CardGroup>

## API Key Management

### Creating API Keys

Generate API keys from your dashboard:

<Steps>
  <Step title="Navigate to API Settings">
    Go to **Settings → API Keys** in your dashboard
  </Step>

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

  <Step title="Configure Permissions">
    Select required permissions for the key
  </Step>

  <Step title="Set Expiration">
    Choose expiration date (optional)
  </Step>

  <Step title="Save Key">
    Copy and securely store the generated key
  </Step>
</Steps>

<Warning>
  API keys are shown only once. Store them securely in a password manager or secrets management system.
</Warning>

### API Key Format

```
Bearer dep_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
```

Key components:

* `dep_` - Prefix identifying deployERP keys
* `live` - Environment (live/test)
* `a1b2c3...` - Unique key identifier

## Using API Keys

### Request Headers

Include your API key in the Authorization header:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET https://api.deployerp.com/v1/servers \
    -H "Authorization: Bearer dep_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6" \
    -H "Content-Type: application/json"
  ```

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

  headers = {
      'Authorization': 'Bearer dep_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6',
      'Content-Type': 'application/json'
  }

  response = requests.get(
      'https://api.deployerp.com/v1/servers',
      headers=headers
  )
  ```

  ```javascript Node.js theme={null}
  const axios = require('axios');

  const config = {
    headers: {
      'Authorization': 'Bearer dep_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6',
      'Content-Type': 'application/json'
    }
  };

  const response = await axios.get(
    'https://api.deployerp.com/v1/servers',
    config
  );
  ```

  ```go Go theme={null}
  client := &http.Client{}
  req, _ := http.NewRequest("GET", "https://api.deployerp.com/v1/servers", nil)
  req.Header.Add("Authorization", "Bearer dep_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6")
  req.Header.Add("Content-Type", "application/json")

  resp, err := client.Do(req)
  ```
</CodeGroup>

### Environment Variables

Best practice: Store API keys in environment variables:

```bash theme={null}
# .env file
DEPLOYERP_API_KEY=dep_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6

# Usage in code
import os
api_key = os.getenv('DEPLOYERP_API_KEY')
```

## API Key Permissions

### Permission Scopes

Configure granular permissions for API keys:

| Scope              | Description             | Operations             |
| ------------------ | ----------------------- | ---------------------- |
| `servers:read`     | View server information | GET /servers           |
| `servers:write`    | Create/update servers   | POST, PATCH /servers   |
| `servers:delete`   | Delete servers          | DELETE /servers        |
| `instances:read`   | View instances          | GET /instances         |
| `instances:write`  | Create/update instances | POST, PATCH /instances |
| `instances:delete` | Delete instances        | DELETE /instances      |
| `backups:read`     | View backups            | GET /backups           |
| `backups:write`    | Create backups          | POST /backups          |
| `teams:read`       | View team info          | GET /teams             |
| `teams:write`      | Manage teams            | POST, PATCH /teams     |
| `billing:read`     | View billing info       | GET /invoices          |

### Permission Examples

<Tabs>
  <Tab title="Read-Only Key">
    ```json theme={null}
    {
      "name": "monitoring-key",
      "permissions": [
        "servers:read",
        "instances:read",
        "backups:read"
      ]
    }
    ```
  </Tab>

  <Tab title="Deployment Key">
    ```json theme={null}
    {
      "name": "ci-deployment",
      "permissions": [
        "servers:read",
        "instances:read",
        "instances:write",
        "backups:write"
      ]
    }
    ```
  </Tab>

  <Tab title="Admin Key">
    ```json theme={null}
    {
      "name": "admin-key",
      "permissions": [
        "servers:*",
        "instances:*",
        "backups:*",
        "teams:*"
      ]
    }
    ```
  </Tab>
</Tabs>

## Security Features

### IP Whitelisting

Restrict API key usage by IP address:

```json theme={null}
{
  "name": "production-key",
  "permissions": ["instances:*"],
  "ip_whitelist": [
    "203.0.113.0/24",    // Office network
    "198.51.100.45",     // CI/CD server
    "2001:db8::/32"      // IPv6 range
  ]
}
```

### Key Expiration

Set expiration dates for enhanced security:

```json theme={null}
{
  "name": "temporary-key",
  "permissions": ["servers:read"],
  "expires_at": "2024-12-31T23:59:59Z",
  "auto_rotate": true,
  "rotation_period": "90d"
}
```

### Rate Limiting per Key

Different rate limits based on key type:

| Key Type    | Requests/Hour | Burst Limit | Use Case     |
| ----------- | ------------- | ----------- | ------------ |
| Standard    | 1,000         | 100/min     | Normal usage |
| High Volume | 10,000        | 1,000/min   | Automation   |
| Limited     | 100           | 10/min      | Testing      |
| Unlimited   | No limit      | No limit    | Enterprise   |

## Authentication Errors

### Common Error Responses

<Tabs>
  <Tab title="Missing Authentication">
    ```json theme={null}
    {
      "error": {
        "code": "authentication_required",
        "message": "No authentication token provided",
        "status": 401
      }
    }
    ```
  </Tab>

  <Tab title="Invalid Token">
    ```json theme={null}
    {
      "error": {
        "code": "invalid_token",
        "message": "The provided API key is invalid",
        "status": 401
      }
    }
    ```
  </Tab>

  <Tab title="Expired Token">
    ```json theme={null}
    {
      "error": {
        "code": "token_expired",
        "message": "The API key has expired",
        "status": 401,
        "expired_at": "2024-01-01T00:00:00Z"
      }
    }
    ```
  </Tab>

  <Tab title="Insufficient Permissions">
    ```json theme={null}
    {
      "error": {
        "code": "insufficient_permissions",
        "message": "This API key lacks required permissions",
        "status": 403,
        "required": ["instances:write"],
        "provided": ["instances:read"]
      }
    }
    ```
  </Tab>

  <Tab title="IP Restricted">
    ```json theme={null}
    {
      "error": {
        "code": "ip_not_allowed",
        "message": "Request from this IP is not allowed",
        "status": 403,
        "your_ip": "192.0.2.1",
        "allowed_ips": ["203.0.113.0/24"]
      }
    }
    ```
  </Tab>
</Tabs>

### Error Handling

Implement proper error handling:

<CodeGroup>
  ```python Python theme={null}
  import requests
  from requests.exceptions import RequestException

  def make_api_request(endpoint, api_key):
      headers = {
          'Authorization': f'Bearer {api_key}',
          'Content-Type': 'application/json'
      }
      
      try:
          response = requests.get(
              f'https://api.deployerp.com/v1/{endpoint}',
              headers=headers
          )
          response.raise_for_status()
          return response.json()
      
      except requests.exceptions.HTTPError as e:
          if e.response.status_code == 401:
              print("Authentication failed. Check your API key.")
          elif e.response.status_code == 403:
              print("Permission denied. Check key permissions.")
          else:
              print(f"HTTP error: {e}")
          return None
      
      except RequestException as e:
          print(f"Request failed: {e}")
          return None
  ```

  ```javascript JavaScript theme={null}
  async function makeApiRequest(endpoint, apiKey) {
    try {
      const response = await fetch(
        `https://api.deployerp.com/v1/${endpoint}`,
        {
          headers: {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
          }
        }
      );
      
      if (!response.ok) {
        const error = await response.json();
        
        switch (response.status) {
          case 401:
            throw new Error('Authentication failed');
          case 403:
            throw new Error('Permission denied');
          default:
            throw new Error(error.message);
        }
      }
      
      return await response.json();
      
    } catch (error) {
      console.error('API request failed:', error);
      throw error;
    }
  }
  ```
</CodeGroup>

## Key Rotation

### Automatic Rotation

Enable automatic key rotation:

```json theme={null}
{
  "rotation_enabled": true,
  "rotation_period": "90d",
  "notification_email": "admin@company.com",
  "grace_period": "7d"
}
```

### Manual Rotation

Rotate keys programmatically:

```bash theme={null}
# Rotate API key
curl -X POST https://api.deployerp.com/v1/api-keys/{key_id}/rotate \
  -H "Authorization: Bearer CURRENT_API_KEY" \
  -H "Content-Type: application/json"

# Response
{
  "old_key": {
    "id": "key_abc123",
    "expires_at": "2024-02-07T00:00:00Z"
  },
  "new_key": {
    "id": "key_xyz789",
    "value": "dep_live_new_key_value",
    "created_at": "2024-01-31T00:00:00Z"
  }
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Secure Storage">
    * Never commit API keys to version control
    * Use environment variables or secret managers
    * Encrypt keys at rest
    * Rotate keys regularly
  </Accordion>

  <Accordion title="Least Privilege">
    * Grant minimum required permissions
    * Create separate keys for different purposes
    * Review permissions regularly
    * Remove unused keys
  </Accordion>

  <Accordion title="Monitoring">
    * Track API key usage
    * Set up alerts for unusual activity
    * Review access logs
    * Monitor failed authentication attempts
  </Accordion>

  <Accordion title="Key Hygiene">
    * Name keys descriptively
    * Document key purposes
    * Set expiration dates
    * Use IP whitelisting when possible
  </Accordion>
</AccordionGroup>

## Testing Authentication

### Test Endpoint

Verify your authentication setup:

```bash theme={null}
# Test authentication
curl -X GET https://api.deployerp.com/v1/auth/test \
  -H "Authorization: Bearer YOUR_API_KEY"

# Success response
{
  "authenticated": true,
  "key_id": "key_abc123",
  "permissions": ["servers:read", "instances:*"],
  "rate_limit": {
    "limit": 1000,
    "remaining": 999,
    "reset": "2024-01-31T15:00:00Z"
  }
}
```

### Debug Headers

Enable debug headers for troubleshooting:

```bash theme={null}
curl -X GET https://api.deployerp.com/v1/servers \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "X-Debug-Auth: true"

# Response headers
X-Auth-Key-ID: key_abc123
X-Auth-Permissions: servers:read,instances:*
X-Auth-IP-Check: passed
X-Auth-Rate-Limit: 999/1000
```

## SDK Authentication

### Python SDK

```python theme={null}
from deployerp import Client

# Initialize client with API key
client = Client(api_key="dep_live_your_api_key")

# Or use environment variable
client = Client()  # Reads from DEPLOYERP_API_KEY env var

# Test authentication
try:
    client.auth.test()
    print("Authentication successful")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
```

### Node.js SDK

```javascript theme={null}
const { DeployERPClient } = require('@deployerp/sdk');

// Initialize with API key
const client = new DeployERPClient({
  apiKey: 'dep_live_your_api_key'
});

// Or use environment variable
const client = new DeployERPClient();
// Reads from process.env.DEPLOYERP_API_KEY

// Test authentication
try {
  await client.auth.test();
  console.log('Authentication successful');
} catch (error) {
  console.error('Authentication failed:', error);
}
```

## Related Documentation

* [API Overview](/api/overview)
* [Rate Limiting](/api/rate-limits)
* [Error Handling](/api/errors)
* [Security Best Practices](/security/overview)
