# Authentication

Tokenlio uses API keys to authenticate requests. This page covers everything you need to know about creating, using, and managing your API keys.

## API Key Overview

- **Format**: Keys are prefixed with `sk-` followed by a random string
- **Security**: Keys are encrypted at rest and never logged
- **Visibility**: Full key shown only once at creation
- **Revocation**: Can be disabled or deleted anytime
- **Scope**: Each key belongs to a workspace (personal or organization)

## Creating API Keys

### Via Console

1. Log in to [api.tokenlio.ai](https://api.tokenlio.ai)
2. Navigate to **API Keys**
3. Click **Create New Key**
4. Enter a descriptive name
5. (Optional) Set quota limits
6. Click **Create**
7. **Copy the key immediately** - you won't see it again

### Key Naming Best Practices

Use descriptive names to identify keys later:

- ✅ `production-web-app`
- ✅ `development-local`
- ✅ `data-pipeline-service`
- ✅ `mobile-app-ios`
- ❌ `key1`, `test`, `temp`

## Using API Keys

### HTTP Header

Include your API key in the `Authorization` header as a Bearer token:

```bash
curl https://api.tokenlio.ai/v1/chat/completions \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-4-turbo", "messages": [{"role": "user", "content": "Hello"}]}'
```

### OpenAI SDK

The OpenAI SDK handles authentication automatically:

```python
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.tokenlio.ai/v1"
)

# SDK adds Authorization header automatically
response = client.chat.completions.create(
    model="gpt-4-turbo",
    messages=[{"role": "user", "content": "Hello"}]
)
```

### Environment Variables

**Never hardcode API keys in your source code.** Use environment variables instead:

```bash
# .env file
TOKENLIO_KEY=sk-your-key-here
```

```python
# Python
import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.getenv('TOKENLIO_KEY')
```

```javascript
// Node.js
import 'dotenv/config';
const apiKey = process.env.TOKENLIO_KEY;
```

## Key Quotas and Limits

You can set optional limits when creating a key:

### Request Quota

Limit the total number of requests this key can make:

- Useful for testing or demo keys
- Resets when you update the quota
- Key is disabled when quota is reached

### Rate Limits

Control requests per minute:

- Prevents runaway costs
- Useful for batch processing
- Returns 429 error when exceeded

### Monthly Spend Limit

Cap spending per key per month:

- Calculated in UTC calendar months
- Prevents budget overruns
- Key is disabled when limit is reached

::: tip
Quota and rate limits apply per key. Workspace-level limits are separate and checked first.
:::

## Key Management

### Viewing Keys

In the console, you can see:

- Key name
- Key prefix (e.g., `sk-abc...xyz`)
- Status (active/disabled)
- Created date
- Last used date
- Usage statistics

::: warning
The full key is never shown again after creation. You'll only see a masked version.
:::

### Disabling Keys

Temporarily disable a key without deleting it:

1. Go to **API Keys**
2. Click the key you want to disable
3. Click **Disable**
4. Confirm the action

Disabled keys:
- Return 401 errors immediately
- Can be re-enabled anytime
- Preserve usage history

### Deleting Keys

Permanently remove a key:

1. Go to **API Keys**
2. Click the key you want to delete
3. Click **Delete**
4. Confirm - this cannot be undone

::: danger
Deleted keys cannot be recovered. Any application using this key will immediately fail.
:::

### Rotating Keys

To rotate a key:

1. Create a new key
2. Update your application to use the new key
3. Verify the new key works
4. Delete the old key

::: tip
Use separate keys for dev/staging/production so you can rotate them independently.
:::

## Security Best Practices

### Do's ✅

- **Store keys securely** in environment variables or secrets managers
- **Use separate keys** for development, staging, and production
- **Rotate keys regularly** (every 90 days recommended)
- **Delete unused keys** immediately
- **Monitor key usage** for anomalies
- **Set quota limits** on test and demo keys
- **Use descriptive names** to identify keys later

### Don'ts ❌

- **Never commit keys** to version control (Git, SVN, etc.)
- **Never share keys** via email, Slack, or other messaging
- **Never hardcode keys** in client-side JavaScript
- **Never log keys** in your application logs
- **Never reuse keys** across multiple applications
- **Never use production keys** in development

### If a Key is Compromised

If you suspect a key has been exposed:

1. **Immediately disable the key** in the console
2. **Check usage logs** for unauthorized activity
3. **Create a new key** as a replacement
4. **Update your application** with the new key
5. **Delete the compromised key**
6. **Review your security practices**

Contact [support@tokenlio.ai](mailto:support@tokenlio.ai) if you notice suspicious activity.

## Workspace Context

API keys belong to workspaces:

### Personal Workspace

- Keys you create in your personal workspace
- Charged to your personal balance
- Only you can manage these keys

### Organization Workspace

- Keys created within an organization
- Charged to the organization's balance
- Owner can manage all keys
- Members can only manage their own keys

When making a request, the key determines which balance is charged. You cannot change a key's workspace after creation.

## Authentication Errors

### 401 Unauthorized

**Cause**: Invalid, missing, or disabled API key

**Solutions**:
- Verify the key is correct (check for extra spaces)
- Ensure the key is active in the console
- Check the Authorization header format: `Bearer YOUR_KEY`

### 403 Forbidden

**Cause**: Valid key but insufficient permissions

**Solutions**:
- Verify the model is available in your workspace
- Check if the workspace has access to the requested model
- Contact support if you need access

### 429 Rate Limited

**Cause**: Too many requests

**Solutions**:
- Implement exponential backoff
- Check your key's rate limits
- Spread requests over time
- Contact support for higher limits

## Advanced Topics

### Server-to-Server Authentication

For backend services:

```python
# Read key from secure environment
import os
api_key = os.environ['TOKENLIO_KEY']

# Use in long-running service
client = OpenAI(api_key=api_key, base_url="https://api.tokenlio.ai/v1")
```

### Proxy Authentication

If using a proxy or middleware:

```javascript
// Express middleware example
app.use((req, res, next) => {
  const apiKey = process.env.TOKENLIO_KEY;
  req.openaiClient = new OpenAI({
    apiKey: apiKey,
    baseURL: 'https://api.tokenlio.ai/v1'
  });
  next();
});
```

### Multi-Key Applications

For applications using multiple keys:

```python
# Different keys for different models or rate limits
class APIClients:
    def __init__(self):
        self.gpt4_client = OpenAI(
            api_key=os.getenv('TOKENLIO_GPT4_KEY'),
            base_url="https://api.tokenlio.ai/v1"
        )
        self.claude_client = OpenAI(
            api_key=os.getenv('TOKENLIO_CLAUDE_KEY'),
            base_url="https://api.tokenlio.ai/v1"
        )
```

## Testing Authentication

Verify your authentication setup:

```bash
# Test with curl
curl https://api.tokenlio.ai/v1/models \
  -H "Authorization: Bearer YOUR_API_KEY"

# Should return list of available models
# 401 error means authentication failed
```

## Next Steps

- [Learn about billing and pricing](/guide/billing)
- [Explore available models](https://api.tokenlio.ai/marketplace)
- [Read the API reference](/api/chat)
- [Set up error handling](/guide/making-requests)

## Need Help?

- [FAQ - Authentication Issues](/support/faq#authentication)
- [Contact Support](/support/contact)
- Email: [support@tokenlio.ai](mailto:support@tokenlio.ai)
