---
title: "Authentication"
description: "Security and authentication methods for TraceRTM API"
---

# Authentication

TraceRTM API provides multiple authentication methods to securely access your data. Choose the method that best fits your use case.

## Authentication Methods

<Cards>
  <Card title="JWT Bearer Tokens" icon={<IconKey />}>
    User-based authentication with JWT tokens
  </Card>

  <Card title="API Keys" icon={<IconApi />}>
    Programmatic access with API keys
  </Card>

  <Card title="OAuth 2.0" icon={<IconShield />}>
    Third-party integrations and delegated access
  </Card>
</Cards>

## JWT Bearer Tokens

JWT (JSON Web Token) bearer authentication is used for user-based authentication.

### How It Works

1. User logs in via the web interface or authentication endpoint
2. Server issues a JWT token with user claims
3. Client includes token in `Authorization` header for subsequent requests
4. Token expires after 24 hours (refresh required)

### Usage

```bash
curl -X GET "https://api.tracertm.com/api/v1/items" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```

### Token Structure

```json
{
  "header": {
    "alg": "HS256",
    "typ": "JWT"
  },
  "payload": {
    "sub": "user-id",
    "email": "user@example.com",
    "org_id": "org-id",
    "permissions": ["read:items", "write:items"],
    "exp": 1640995200,
    "iat": 1640908800
  }
}
```

### Token Lifecycle

<Steps>

### Obtain Token

```bash
POST /api/v1/auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "your-password"
}
```

Response:
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "expires_in": 86400,
  "token_type": "Bearer"
}
```

### Use Token

```bash
curl -H "Authorization: Bearer YOUR_TOKEN" \
  https://api.tracertm.com/api/v1/items
```

### Refresh Token

```bash
POST /api/v1/auth/refresh
Content-Type: application/json

{
  "refresh_token": "eyJhbGciOiJIUzI1NiIs..."
}
```

</Steps>

## API Keys

API keys provide programmatic access without requiring user credentials. Ideal for server-to-server integrations.

### Creating API Keys

Generate API keys from your dashboard:

1. Navigate to **Settings → API Keys**
2. Click **Generate New Key**
3. Name your key and set permissions
4. Copy and securely store the key (shown only once)

### Usage

Include your API key in the `X-API-Key` header:

```bash
curl -X GET "https://api.tracertm.com/api/v1/items" \
  -H "X-API-Key: sk_live_abc123def456..."
```

### Key Types

<Tabs items={["Live Keys", "Test Keys"]}>

<Tab value="Live Keys">

**Live keys** access production data:

- Prefix: `sk_live_`
- Used in production environments
- Full access to live data
- Rate limit: 1000 requests/hour

```bash
X-API-Key: sk_live_abc123def456ghi789
```

</Tab>

<Tab value="Test Keys">

**Test keys** access sandbox data:

- Prefix: `sk_test_`
- Used in development/testing
- Separate test data environment
- Rate limit: 100 requests/hour

```bash
X-API-Key: sk_test_abc123def456ghi789
```

</Tab>

</Tabs>

### Key Permissions

API keys can be scoped to specific permissions:

| Permission | Description |
|------------|-------------|
| `read:items` | Read items and metadata |
| `write:items` | Create and update items |
| `delete:items` | Delete items |
| `read:links` | Read link relationships |
| `write:links` | Create and update links |
| `admin` | Full administrative access |

### Best Practices

<Callout type="warning">
  **Security Best Practices**

  - Never commit API keys to version control
  - Rotate keys regularly (every 90 days recommended)
  - Use environment variables for key storage
  - Limit key permissions to minimum required
  - Monitor key usage in dashboard
</Callout>

```bash
# ❌ Don't do this
const apiKey = "sk_live_abc123def456";

# ✅ Do this instead
const apiKey = process.env.TRACERTM_API_KEY;
```

### Revoking Keys

Revoke compromised or unused keys immediately:

1. Go to **Settings → API Keys**
2. Find the key to revoke
3. Click **Revoke**
4. Confirm revocation

Revoked keys are immediately invalidated.

## OAuth 2.0

OAuth 2.0 enables third-party applications to access TraceRTM on behalf of users.

### Supported Flows

TraceRTM supports the following OAuth 2.0 flows:

<Cards>
  <Card title="Authorization Code">
    For web applications with server-side backend
  </Card>

  <Card title="PKCE">
    For single-page apps and mobile applications
  </Card>

  <Card title="Client Credentials">
    For machine-to-machine communication
  </Card>
</Cards>

### Authorization Code Flow

<Steps>

### Register Application

Register your OAuth app in the TraceRTM dashboard:

- **Client ID**: Your application identifier
- **Client Secret**: Keep this confidential
- **Redirect URI**: Where to send users after authorization

### Authorization Request

Direct users to the authorization endpoint:

```bash
GET https://api.tracertm.com/oauth/authorize
  ?client_id=YOUR_CLIENT_ID
  &redirect_uri=https://yourapp.com/callback
  &response_type=code
  &scope=read:items write:items
  &state=random_state_string
```

### Exchange Code for Token

After user authorizes, exchange the authorization code for tokens:

```bash
POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=AUTHORIZATION_CODE
&client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRET
&redirect_uri=https://yourapp.com/callback
```

Response:
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "read:items write:items"
}
```

### Use Access Token

```bash
curl -H "Authorization: Bearer ACCESS_TOKEN" \
  https://api.tracertm.com/api/v1/items
```

</Steps>

### Scopes

OAuth scopes define permission levels:

| Scope | Description |
|-------|-------------|
| `read:items` | Read items |
| `write:items` | Create/update items |
| `delete:items` | Delete items |
| `read:links` | Read links |
| `write:links` | Create/update links |
| `read:projects` | Read projects |
| `write:projects` | Create/update projects |
| `admin` | Full access (requires approval) |

Request minimal scopes needed for your application.

## Error Responses

Authentication errors return appropriate HTTP status codes:

### 401 Unauthorized

Missing or invalid credentials:

```json
{
  "detail": "Authentication required",
  "code": "UNAUTHORIZED"
}
```

### 403 Forbidden

Valid credentials but insufficient permissions:

```json
{
  "detail": "Insufficient permissions",
  "code": "FORBIDDEN",
  "required_permission": "write:items"
}
```

### 429 Too Many Requests

Rate limit exceeded:

```json
{
  "detail": "Rate limit exceeded",
  "code": "RATE_LIMIT_EXCEEDED",
  "retry_after": 3600
}
```

## Rate Limits

Authentication method affects rate limits:

| Method | Rate Limit | Window |
|--------|------------|--------|
| JWT Bearer | 1000 requests | 1 hour |
| API Key (Live) | 1000 requests | 1 hour |
| API Key (Test) | 100 requests | 1 hour |
| OAuth 2.0 | 1000 requests | 1 hour |
| Unauthenticated | 100 requests | 1 hour |

### Rate Limit Headers

Every response includes rate limit information:

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

## Security Best Practices

<Callout type="info">
  **Production Security Checklist**

  - ✅ Use HTTPS for all API requests
  - ✅ Store credentials in environment variables
  - ✅ Rotate API keys every 90 days
  - ✅ Use minimal required permissions
  - ✅ Monitor API usage for anomalies
  - ✅ Implement token refresh logic
  - ✅ Handle authentication errors gracefully
  - ✅ Never log or expose credentials
</Callout>

### Secure Storage

```javascript
// ❌ Bad - Hardcoded credentials
const token = "eyJhbGciOiJIUzI1NiIs...";

// ✅ Good - Environment variables
const token = process.env.TRACERTM_TOKEN;

// ✅ Good - Secure credential store
const token = await credentialStore.get('tracertm_token');
```

### Token Rotation

Implement automatic token refresh:

```javascript
async function refreshTokenIfNeeded(currentToken) {
  const decoded = jwt.decode(currentToken);
  const expiresIn = decoded.exp - Date.now() / 1000;

  // Refresh if expiring in less than 5 minutes
  if (expiresIn < 300) {
    return await refreshToken(currentToken);
  }

  return currentToken;
}
```

## Testing Authentication

Use test mode for development:

```bash
# Test with test API key
curl -H "X-API-Key: sk_test_abc123" \
  https://api.tracertm.com/api/v1/items

# Test with test OAuth app
# Sandbox environment with isolated data
```

## Support

Questions about authentication?

- **Documentation**: [Security Overview](/docs/security)
- **Support Email**: security@tracertm.com
- **Report Security Issues**: security@tracertm.com (PGP key available)

## Next Steps

<Cards>
  <Card title="Make Your First Request" href="/docs/api/rest-api">
    Explore the REST API endpoints
  </Card>

  <Card title="Use an SDK" href="/docs/sdk">
    Get started with official SDKs
  </Card>

  <Card title="Set Up Webhooks" href="/docs/api/webhooks">
    Receive real-time notifications
  </Card>
</Cards>
