---
title: "Authentication"
description: "Comprehensive guide to authenticating with the TraceRTM API using API keys, OAuth 2.0, JWT, SAML, and MFA"
---

# Authentication

TraceRTM provides multiple authentication methods to secure access to your traceability data. Choose the method that best fits your use case, from simple API keys for scripts to enterprise SAML/SSO for large organizations.

## Authentication Methods Overview

| Method | Best For | Security Level | Setup Complexity |
|--------|----------|----------------|------------------|
| [API Keys](/docs/api-reference/authentication/api-keys) | Scripts, CLI, CI/CD | Medium | Low |
| [OAuth 2.0](/docs/api-reference/authentication/oauth) | Web apps, third-party integrations | High | Medium |
| [JWT](/docs/api-reference/authentication/jwt) | Microservices, API-to-API | High | Medium |
| [SAML/SSO](/docs/api-reference/authentication/saml) | Enterprise single sign-on | Very High | High |
| [MFA](/docs/api-reference/authentication/mfa) | Enhanced security (add-on) | Very High | Low |

## Quick Start

### Using API Keys (Simplest)

```bash
# Set your API key
export TRACERTM_API_KEY="rtm_live_abc123..."

# Make authenticated requests
curl -H "Authorization: Bearer $TRACERTM_API_KEY" \
  https://api.tracertm.dev/v1/projects
```

### Using the Python SDK

```python
from tracertm import TraceRTMClient

# API key authentication (from environment or explicit)
client = TraceRTMClient()  # Uses TRACERTM_API_KEY env var

# Or explicitly
client = TraceRTMClient(api_key="rtm_live_abc123...")

# OAuth token authentication
client = TraceRTMClient(access_token="eyJhbGciOiJSUzI1NiIs...")

# Make authenticated requests
projects = await client.projects.list()
```

### Using the JavaScript SDK

```typescript
import { TraceRTMClient } from '@tracertm/sdk'

// API key authentication
const client = new TraceRTMClient({
  apiKey: process.env.TRACERTM_API_KEY
})

// OAuth token authentication
const client = new TraceRTMClient({
  accessToken: 'eyJhbGciOiJSUzI1NiIs...'
})

// Make authenticated requests
const projects = await client.projects.list()
```

## Authentication Flow

```
┌─────────────────────────────────────────────────────────────────────────┐
│                      Authentication Flow                                 │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│   Client                    API Gateway                   Auth Service   │
│     │                           │                              │         │
│     │──[1] Request + Creds─────>│                              │         │
│     │                           │──[2] Validate Credentials───>│         │
│     │                           │<─[3] User/Agent Identity─────│         │
│     │                           │                              │         │
│     │                           │──[4] Check Permissions───────│         │
│     │                           │<─[5] Authorization Result────│         │
│     │                           │                              │         │
│     │<─[6] Response─────────────│                              │         │
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘
```

## Authorization Headers

All authenticated requests must include credentials in the `Authorization` header:

### Bearer Token (API Key or JWT)

```http
Authorization: Bearer rtm_live_abc123...
```

### OAuth Access Token

```http
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
```

### Basic Authentication (Limited)

```http
Authorization: Basic base64(username:password)
```

> **Note**: Basic authentication is only available for specific endpoints and is not recommended for production use.

## Permission Scopes

TraceRTM uses granular permission scopes to control access:

| Scope | Description | API Key | OAuth | JWT |
|-------|-------------|---------|-------|-----|
| `read:projects` | List and view projects | Yes | Yes | Yes |
| `write:projects` | Create, update, delete projects | Yes | Yes | Yes |
| `read:items` | List and view items | Yes | Yes | Yes |
| `write:items` | Create, update, delete items | Yes | Yes | Yes |
| `read:links` | List and view traceability links | Yes | Yes | Yes |
| `write:links` | Create, update, delete links | Yes | Yes | Yes |
| `read:agents` | View agent information | Yes | Yes | Yes |
| `write:agents` | Register and manage agents | Yes | Yes | Yes |
| `admin:*` | Full administrative access | Limited | Yes | Yes |

### Requesting Scopes

```python
# Python SDK - specify scopes when creating client
client = TraceRTMClient(
    api_key="rtm_live_...",
    scopes=["read:projects", "write:items"]
)
```

```typescript
// JavaScript SDK
const client = new TraceRTMClient({
  apiKey: process.env.TRACERTM_API_KEY,
  scopes: ['read:projects', 'write:items']
})
```

## Rate Limiting

Authentication impacts rate limiting:

| Auth Method | Requests/Minute | Burst Limit |
|-------------|-----------------|-------------|
| API Key (Free) | 60 | 10 |
| API Key (Pro) | 1,000 | 100 |
| API Key (Enterprise) | 10,000 | 1,000 |
| OAuth Token | Varies by plan | Varies |
| Service Account | 50,000 | 5,000 |

Rate limit headers are included in every response:

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

## Error Responses

Authentication errors follow a consistent format:

### 401 Unauthorized

```json
{
  "error": {
    "code": "AUTHENTICATION_REQUIRED",
    "message": "Valid authentication credentials are required",
    "details": {
      "hint": "Include an API key or OAuth token in the Authorization header"
    }
  }
}
```

### 403 Forbidden

```json
{
  "error": {
    "code": "INSUFFICIENT_PERMISSIONS",
    "message": "You don't have permission to perform this action",
    "details": {
      "required_scope": "write:projects",
      "your_scopes": ["read:projects", "read:items"]
    }
  }
}
```

### 429 Rate Limited

```json
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests",
    "details": {
      "retry_after": 60,
      "limit": 1000,
      "reset_at": "2024-01-15T12:00:00Z"
    }
  }
}
```

## Security Best Practices

### API Key Security

```bash
# GOOD: Use environment variables
export TRACERTM_API_KEY="rtm_live_..."

# BAD: Hard-coded in source code
api_key = "rtm_live_..."  # Never do this!
```

### Token Storage

```typescript
// GOOD: Secure storage for web apps
sessionStorage.setItem('tracertm_token', token)

// BAD: localStorage for sensitive tokens
localStorage.setItem('tracertm_token', token)  // Vulnerable to XSS
```

### Credential Rotation

```python
# Rotate API keys regularly
from tracertm.admin import rotate_api_key

new_key = await rotate_api_key(
    current_key="rtm_live_old...",
    grace_period_hours=24  # Both keys work for 24 hours
)
```

## Multi-Tenant Authentication

For organizations with multiple teams or projects:

```python
# Organization-level authentication
client = TraceRTMClient(
    api_key="rtm_live_...",
    organization_id="org_123"
)

# Access specific project
project = await client.projects.get("proj_456")

# Impersonate user (admin only)
client.impersonate(user_id="user_789")
items = await client.items.list(project_id="proj_456")
```

## Agent Authentication

AI agents use dedicated authentication:

```python
from tracertm import AgentClient

# Agent-specific authentication
agent = AgentClient(
    agent_id="agent_claude_001",
    agent_secret="ags_...",
    capabilities=["read", "write", "suggest"]
)

# Register agent with project
await agent.register(project_id="proj_123")

# Agent operations are tracked
item = await agent.items.create(
    project_id="proj_123",
    data={"title": "New Feature", "type": "FEATURE"}
)
# Item metadata includes: created_by_agent: "agent_claude_001"
```

## CLI Authentication

```bash
# Interactive login
rtm auth login

# API key login
rtm auth login --api-key rtm_live_...

# OAuth login (opens browser)
rtm auth login --oauth

# Check authentication status
rtm auth status

# Logout
rtm auth logout
```

## Troubleshooting

### Common Issues

**"Invalid API key" error**
- Verify the key hasn't expired
- Check for extra whitespace or newlines
- Ensure you're using the correct environment (live vs test)

**"Token expired" error**
- Refresh OAuth tokens before expiry
- JWT tokens typically expire after 1 hour
- Implement automatic token refresh in your application

**"Insufficient permissions" error**
- Check the required scopes for the endpoint
- Verify your API key or OAuth app has the necessary permissions
- Contact your organization admin for elevated access

### Debug Mode

```python
import logging

# Enable debug logging for authentication
logging.getLogger('tracertm.auth').setLevel(logging.DEBUG)

client = TraceRTMClient(api_key="rtm_live_...")
# Logs will show authentication flow details
```

## Related Documentation

- [API Keys](/docs/api-reference/authentication/api-keys) - Create and manage API keys
- [OAuth 2.0](/docs/api-reference/authentication/oauth) - Implement OAuth flows
- [JWT](/docs/api-reference/authentication/jwt) - JSON Web Token authentication
- [SAML/SSO](/docs/api-reference/authentication/saml) - Enterprise single sign-on
- [MFA](/docs/api-reference/authentication/mfa) - Multi-factor authentication
- [Security Best Practices](/docs/wiki/guides/security) - Comprehensive security guide

