# API Key Authentication Guide

Source: https://docs.qvoice.net/api/api-key-auth/

This document explains how to use API keys to authenticate your requests to the GoPortal Backend API. API keys provide a secure and convenient way to access the API without managing user sessions or JWT tokens.

## Overview

API keys are long-lived credentials that grant access to specific accounts within the system. They are ideal for:
- Server-to-server communication
- Automated scripts and integrations
- Third-party applications
- Continuous integration/deployment pipelines

## Authentication Methods

The API supports multiple authentication methods. API keys are used alongside the `X-API-Key` header:

1. **JWT Token** (existing): `Authorization: Bearer <token>`
2. **API Key** (new): `X-API-Key: <api_key>`
3. **Mobile Auth** (existing): Query parameters with username/password

## Getting Started

### 1. Create an API Key

First, you need to create an API key through the API management endpoints. You'll need to be authenticated with a JWT token to create API keys.

```
curl -X POST "https://your-domain.com/api/apikeys" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "X-Account-ID: YOUR_ACCOUNT_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My Integration API Key",
    "description": "API key for my external integration",
    "expires_at": 1735689600
  }'
```

**Response:**

```
{
  "id": "api_key_123456",
  "key": "abc123def456ghi789jkl012mno345pqr678stu901vwx234yz",
  "account_id": "account_123",
  "name": "My Integration API Key",
  "description": "API key for my external integration",
  "created_by": "user_456",
  "created_at": "2024-01-15T10:30:00Z",
  "is_revoked": false,
  "expires_at": 1735689600
}
```

⚠️ **Important**: The `key` field is only returned once when the API key is created. Store it securely as it cannot be retrieved later.

### 2. Using the API Key

Once you have your API key, you can use it to authenticate requests by including it in the `X-API-Key` header:

```
curl -X GET "https://your-domain.com:9443/api/v2/config/users" \
  -H "X-API-Key: abc123def456ghi789jkl012mno345pqr678stu901vwx234yz" \
  -H "X-Account-ID: account_123"
```

## Required Headers

When using API key authentication, you must include:

### X-API-Key

- **Required**: Yes
- **Type**: String
- **Description**: Your API key value
- **Example**: `abc123def456ghi789jkl012mno345pqr678stu901vwx234yz`

### X-Account-ID

- **Required**: Yes
- **Type**: String
- **Description**: The account ID you want to access
- **Example**: `account_123`

## Code Examples

### JavaScript/Node.js

```
const axios = require('axios');

const apiKey = 'abc123def456ghi789jkl012mno345pqr678stu901vwx234yz';
const accountId = 'account_123';

const config = {
  headers: {
    'X-API-Key': apiKey,
    'X-Account-ID': accountId,
    'Content-Type': 'application/json'
  }
};

// Get users
axios.get('https://your-domain.com:9443/api/v2/config/users', config)
  .then(response => {
    console.log('Users:', response.data);
  })
  .catch(error => {
    console.error('Error:', error.response.data);
  });

// Create a user
const userData = {
  username: 'john.doe',
  email: 'john.doe@example.com',
  first_name: 'John',
  last_name: 'Doe'
};

axios.post('https://your-domain.com/api/users', userData, config)
  .then(response => {
    console.log('User created:', response.data);
  })
  .catch(error => {
    console.error('Error:', error.response.data);
  });
```

### Python

```
import requests

api_key = 'abc123def456ghi789jkl012mno345pqr678stu901vwx234yz'
account_id = 'account_123'

headers = {
    'X-API-Key': api_key,
    'X-Account-ID': account_id,
    'Content-Type': 'application/json'
}

## Get users
response = requests.get('https://your-domain.com:9443/api/v2/config/users', headers=headers)
if response.status_code == 200:
    users = response.json()
    print('Users:', users)
else:
    print('Error:', response.text)

## Create a user
user_data = {
    'username': 'john.doe',
    'email': 'john.doe@example.com',
    'first_name': 'John',
    'last_name': 'Doe'
}

response = requests.post('https://your-domain.com:9443/api/v2/config/users',
                        json=user_data, headers=headers)
if response.status_code == 201:
    user = response.json()
    print('User created:', user)
else:
    print('Error:', response.text)
```

### Go

```
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

type User struct {
    Username  string `json:"username"`
    Email     string `json:"email"`
    FirstName string `json:"first_name"`
    LastName  string `json:"last_name"`
}

func main() {
    apiKey := "abc123def456ghi789jkl012mno345pqr678stu901vwx234yz"
    accountID := "account_123"

    // Create HTTP client
    client := &http.Client{}

    // Get users
    req, err := http.NewRequest("GET", "https://your-domain.com:9442/api/v2/config/users", nil)
    if err != nil {
        panic(err)
    }

    req.Header.Set("X-API-Key", apiKey)
    req.Header.Set("X-Account-ID", accountID)

    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    if resp.StatusCode == 200 {
        var users []User
        json.NewDecoder(resp.Body).Decode(&users)
        fmt.Printf("Users: %+v\n", users)
    }

    // Create a user
    user := User{
        Username:  "john.doe",
        Email:     "john.doe@example.com",
        FirstName: "John",
        LastName:  "Doe",
    }

    userData, _ := json.Marshal(user)
    req, err = http.NewRequest("POST", "https://your-domain.com:9443/api/v2/config/users",
                              bytes.NewBuffer(userData))
    if err != nil {
        panic(err)
    }

    req.Header.Set("X-API-Key", apiKey)
    req.Header.Set("X-Account-ID", accountID)
    req.Header.Set("Content-Type", "application/json")

    resp, err = client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    if resp.StatusCode == 201 {
        var createdUser User
        json.NewDecoder(resp.Body).Decode(&createdUser)
        fmt.Printf("User created: %+v\n", createdUser)
    }
}
```

## API Key Management

### List API Keys

```
curl -X GET "https://your-domain.com:9443/api/v2/apikeys" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "X-Account-ID: YOUR_ACCOUNT_ID"
```

### Get API Key Details

```
curl -X GET "https://your-domain.com:9443/api/v2/apikeys/api_key_123456" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "X-Account-ID: YOUR_ACCOUNT_ID"
```

### Revoke API Key

```
curl -X POST "https://your-domain.com:9443/api/v2/apikeys/api_key_123456/revoke" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "X-Account-ID: YOUR_ACCOUNT_ID"
```

### Update API Key Expiration

```
curl -X PUT "https://your-domain.com:9443/api/v2/apikeys/api_key_123456/expiration" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "X-Account-ID: YOUR_ACCOUNT_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "expires_at": 1735689600
  }'
```

### Delete API Key

```
curl -X DELETE "https://your-domain.com:9443/api/v2/apikeys/api_key_123456" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "X-Account-ID: YOUR_ACCOUNT_ID"
```

## Security Best Practices

### 1. Secure Storage

- Store API keys in environment variables or secure configuration management systems
- Never commit API keys to version control
- Use different API keys for different environments (development, staging, production)

### 2. Key Rotation

- Regularly rotate your API keys
- Set expiration dates for API keys when possible
- Revoke unused or compromised keys immediately

### 3. Access Control

- API keys have admin-level access within their account scope
- Only create API keys for accounts that need access
- Use the principle of least privilege

### 4. Monitoring

- Monitor API key usage for unusual patterns
- Set up alerts for failed authentication attempts
- Regularly review and audit API key access

## Error Handling

### Common Error Responses

#### 401 Unauthorized

```
{
  "error": {
    "code": "USER_NO_AUTH_IN_DOC",
    "message": "Authentication failed"
  }
}
```

**Causes:**
- Invalid or expired API key
- Missing X-API-Key header
- API key is revoked

#### 400 Bad Request

```
{
  "error": "X-Account-ID header is required"
}
```

**Causes:**
- Missing X-Account-ID header
- Invalid account ID format

#### 403 Forbidden

```
{
  "error": "Access denied"
}
```

**Causes:**
- API key doesn't have access to the specified account
- Account access validation failed

### Troubleshooting

1. **"Invalid API key" error**
2. Verify the API key is correct and not truncated
3. Check if the API key has been revoked
4. Ensure the API key hasn't expired
5. **"X-Account-ID header is required" error**
6. Include the X-Account-ID header in your request
7. Verify the account ID is correct
8. Ensure the API key has access to the specified account
9. **"Access denied" error**
10. Verify the API key belongs to the account you're trying to access
11. Check if the account hierarchy allows access
12. Contact your system administrator if needed

## Migration from JWT Tokens

If you're currently using JWT tokens, you can migrate to API keys:

1. **Create API keys** for your integrations
2. **Update your code** to use the X-API-Key header instead of Authorization
3. **Test thoroughly** in a staging environment
4. **Deploy gradually** to production
5. **Monitor** for any issues
6. **Revoke old JWT tokens** once migration is complete

## See also

- [Download Call Recordings](https://docs.qvoice.net/how-to/download-call-recordings/) — Archive call recording files locally using the API (pull) or external storage (push).

## Support

If you encounter issues with API key authentication:

1. Check this documentation for common solutions
2. Verify your API key and account ID are correct
3. Review the error messages for specific guidance
4. Contact your system administrator or support team

## API Reference

For complete API documentation, including all available endpoints and their parameters, refer to the OpenAPI specification at:

- `https://cad.fonouc.com/tmp/goportalbackend/master.html` - Complete API documentation
- `https://cad.fonouc.com/tmp/goportalbackend/master.html#tag/API-Keys` - API key management endpoints

---

**Note**: This documentation is for API key authentication. For other authentication methods, refer to the main API documentation.
