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

# Authentication

> Learn how to authenticate with the Kaie API

## Authentication Methods

The Kaie API supports multiple authentication methods to secure your API requests and ensure only authorized access to your workflows and data.

## API Key Authentication

The most common method for authenticating with the Kaie API is using API keys.

### Getting Your API Key

1. Log in to your Kaie dashboard
2. Navigate to **Settings** > **API Keys**
3. Click **Create New API Key**
4. Give your key a descriptive name
5. Select the appropriate permissions
6. Copy the generated API key

<Warning>
  API keys are only shown once when created. Make sure to copy and store your API key securely.
</Warning>

### Using API Keys

Include your API key in the `Authorization` header of your requests:

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://api.kaie.ai/v1/workflows
```

### API Key Permissions

API keys can be configured with different permission levels:

<AccordionGroup>
  <Accordion title="Read Only">
    * View workflows and analytics
    * Access read-only endpoints
    * Cannot modify or create resources
  </Accordion>

  <Accordion title="Read/Write">
    * All read permissions
    * Create and update workflows
    * Manage triggers and integrations
    * Cannot delete resources
  </Accordion>

  <Accordion title="Full Access">
    * All read/write permissions
    * Delete workflows and resources
    * Manage API keys and settings
    * Access admin endpoints
  </Accordion>
</AccordionGroup>

## OAuth 2.0 Authentication

For applications that need to access user data on behalf of users, OAuth 2.0 is recommended.

### OAuth Flow

1. **Authorization Request**: Redirect users to the authorization endpoint
2. **User Consent**: Users grant permission to your application
3. **Authorization Code**: Receive an authorization code
4. **Token Exchange**: Exchange the code for access and refresh tokens
5. **API Access**: Use the access token to make API requests

### Authorization Endpoint

```
GET https://api.kaie.ai/oauth/authorize
```

**Parameters:**

* `client_id`: Your application's client ID
* `redirect_uri`: Where to redirect after authorization
* `response_type`: Must be `code`
* `scope`: Requested permissions (space-separated)
* `state`: Random string to prevent CSRF attacks

### Token Endpoint

```
POST https://api.kaie.ai/oauth/token
```

**Parameters:**

* `grant_type`: Must be `authorization_code`
* `code`: Authorization code from the previous step
* `redirect_uri`: Same redirect URI used in authorization
* `client_id`: Your application's client ID
* `client_secret`: Your application's client secret

### Using Access Tokens

Include the access token in the `Authorization` header:

```bash theme={null}
curl -H "Authorization: Bearer ACCESS_TOKEN" \
  https://api.kaie.ai/v1/workflows
```

### Refresh Tokens

Access tokens expire after 1 hour. Use refresh tokens to get new access tokens:

```bash theme={null}
curl -X POST https://api.kaie.ai/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token&refresh_token=REFRESH_TOKEN&client_id=CLIENT_ID&client_secret=CLIENT_SECRET"
```

## JWT Authentication

For server-to-server communication, JWT (JSON Web Token) authentication is supported.

### Creating JWT Tokens

JWT tokens must be signed with your private key and include the following claims:

```json theme={null}
{
  "iss": "your-application-id",
  "sub": "user-or-service-id",
  "aud": "kaie-api",
  "exp": 1640995200,
  "iat": 1640908800,
  "scope": "workflows:read workflows:write"
}
```

### Using JWT Tokens

Include the JWT token in the `Authorization` header:

```bash theme={null}
curl -H "Authorization: Bearer JWT_TOKEN" \
  https://api.kaie.ai/v1/workflows
```

## Webhook Authentication

Webhooks use HMAC-SHA256 signatures to verify the authenticity of incoming requests.

### Verifying Webhook Signatures

The webhook signature is included in the `X-Kaie-Signature` header:

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

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature, 'hex'),
    Buffer.from(expectedSignature, 'hex')
  );
}
```

## Rate Limiting

API requests are subject to rate limiting to ensure fair usage and system stability.

### Rate Limits

* **API Key**: 1000 requests per hour
* **OAuth Token**: 1000 requests per hour
* **JWT Token**: 1000 requests per hour
* **Webhook**: 100 requests per minute

### Rate Limit Headers

Rate limit information is included in response headers:

```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
```

### Handling Rate Limits

When you exceed the rate limit, you'll receive a `429 Too Many Requests` response:

```json theme={null}
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded",
    "retry_after": 3600
  }
}
```

Wait for the specified `retry_after` seconds before making new requests.

## Security Best Practices

### API Key Security

<AccordionGroup>
  <Accordion title="Storage">
    * Store API keys securely (environment variables, secret management)
    * Never commit API keys to version control
    * Use different keys for different environments
    * Rotate keys regularly
  </Accordion>

  <Accordion title="Transmission">
    * Always use HTTPS for API requests
    * Include API keys in headers, not URLs
    * Use secure communication channels
    * Validate SSL certificates
  </Accordion>
</AccordionGroup>

### Token Security

<AccordionGroup>
  <Accordion title="Access Tokens">
    * Store access tokens securely
    * Use short-lived access tokens
    * Implement token refresh logic
    * Revoke tokens when no longer needed
  </Accordion>

  <Accordion title="Refresh Tokens">
    * Store refresh tokens securely
    * Use long-lived refresh tokens
    * Implement secure token exchange
    * Monitor token usage
  </Accordion>
</AccordionGroup>

## Error Handling

### Authentication Errors

Common authentication errors and their meanings:

| Status Code | Error Code                 | Description                        |
| ----------- | -------------------------- | ---------------------------------- |
| 401         | `INVALID_API_KEY`          | API key is invalid or expired      |
| 401         | `MISSING_AUTHENTICATION`   | No authentication provided         |
| 401         | `INVALID_TOKEN`            | Access token is invalid or expired |
| 403         | `INSUFFICIENT_PERMISSIONS` | API key lacks required permissions |
| 403         | `SCOPE_INSUFFICIENT`       | Token scope is insufficient        |

### Error Response Format

```json theme={null}
{
  "error": {
    "code": "INVALID_API_KEY",
    "message": "The provided API key is invalid",
    "details": "API key 'ak_1234567890' was not found"
  }
}
```

## Testing Authentication

### Test Your API Key

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://api.kaie.ai/v1/me
```

### Test OAuth Flow

Use the OAuth playground to test your OAuth implementation:

<Card title="OAuth Playground" icon="play" href="https://api.kaie.ai/oauth/playground">
  Test OAuth authentication flows
</Card>

## Next Steps

Now that you understand authentication, explore the API endpoints:

<CardGroup cols={2}>
  <Card title="Workflows API" icon="diagram-project" href="/api-reference/workflows">
    Manage workflows programmatically
  </Card>

  <Card title="Analytics API" icon="chart-line" href="/api-reference/analytics">
    Access analytics data via API
  </Card>

  <Card title="Webhooks API" icon="webhook" href="/api-reference/webhooks">
    Set up webhook integrations
  </Card>

  <Card title="Triggers API" icon="bolt" href="/api-reference/triggers">
    Manage workflow triggers
  </Card>
</CardGroup>
