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

# Authentication

> Learn how to authenticate with the Tokencraft API

# Authentication

All Tokencraft API requests require authentication using Bearer tokens. This guide explains how to create and use API tokens securely.

## Creating an API Token

1. Log in to your [Tokencraft dashboard](https://app.tokencraft.dev)
2. Navigate to **API** in the sidebar
3. Click **"New Token"**
4. Enter a descriptive name for your token
5. Click **"Create Token"**
6. **Copy the token immediately** - you won't be able to see it again!

<Warning>
  API tokens are shown only once. Store them securely in a password manager or environment variable.
</Warning>

## Token Format

Tokencraft API tokens follow this format:

```
tkc_[random_string]
```

Example: `tkc_1234567890abcdef1234567890abcdef12345678`

## OAuth Tokens (MCP Integrations)

When you connect an MCP client (Cursor, Claude remote MCP, Figma plugin) via OAuth, Tokencraft issues an access token automatically after you approve the consent screen at `/mcp/authorize`.

### How OAuth tokens differ

| Property          | Manual API token       | OAuth token                             |
| ----------------- | ---------------------- | --------------------------------------- |
| Format            | `tkc_` + hex string    | 64-character hex (no prefix)            |
| Created by        | You, in API Settings   | Issued after OAuth consent              |
| Name in dashboard | Your chosen name       | `MCP OAuth — {client name}`             |
| Expiry            | No automatic expiry    | 30 days                                 |
| Revocation        | API Settings or delete | API Settings or `/api/oauth/mcp/revoke` |

### Using OAuth tokens

OAuth tokens authenticate the same way as manual tokens:

```
Authorization: Bearer <access_token>
```

They respect the same scopes (`read:tokens`, `write:tokens`, `export:tokens`), workspace write rules, and rate limits (100 req/min).

### Revoking OAuth tokens

1. Go to [API Settings](https://app.tokencraft.dev/api-settings)
2. Find the token named `MCP OAuth — …`
3. Click the delete button

Or call `POST /api/oauth/mcp/revoke` with the token value. See [MCP OAuth](/mcp/oauth) for details.

<Note>
  OAuth is for interactive MCP clients. For CI/CD and automation, create a manual `tkc_` token instead.
</Note>

## Using Your Token

Include your API token in the `Authorization` header of every request:

```
Authorization: Bearer tkc_your_token_here
```

### Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl -H "Authorization: Bearer tkc_your_token_here" \
    https://app.tokencraft.dev/api/v1/workspaces
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://app.tokencraft.dev/api/v1/workspaces', {
    headers: {
      'Authorization': 'Bearer tkc_your_token_here'
    }
  });
  ```

  ```python Python theme={null}
  import requests

  headers = {'Authorization': 'Bearer tkc_your_token_here'}
  response = requests.get(
      'https://app.tokencraft.dev/api/v1/workspaces',
      headers=headers
  )
  ```

  ```go Go theme={null}
  client := &http.Client{}
  req, _ := http.NewRequest("GET", "https://app.tokencraft.dev/api/v1/workspaces", nil)
  req.Header.Set("Authorization", "Bearer tkc_your_token_here")
  resp, _ := client.Do(req)
  ```
</CodeGroup>

## Environment Variables

Store your token as an environment variable for security:

<CodeGroup>
  ```bash .env theme={null}
  TOKENCRAFT_TOKEN=tkc_your_token_here
  ```

  ```bash Usage (Bash) theme={null}
  curl -H "Authorization: Bearer $TOKENCRAFT_TOKEN" \
    https://app.tokencraft.dev/api/v1/workspaces
  ```

  ```javascript Usage (Node.js) theme={null}
  const token = process.env.TOKENCRAFT_TOKEN;

  const response = await fetch(`https://app.tokencraft.dev/api/v1/workspaces`, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  ```

  ```python Usage (Python) theme={null}
  import os

  token = os.environ['TOKENCRAFT_TOKEN']

  headers = {'Authorization': f'Bearer {token}'}
  response = requests.get(f'{api_base}/workspaces', headers=headers)
  ```
</CodeGroup>

## Token Permissions

Each API token can access resources according to its scopes and workspace membership context.

* `read:tokens`: read workspace/tokenset/mode/token resources
* `write:tokens`: create/update/delete resources
* `export:tokens`: export endpoints

<Note>
  Scopes are necessary but not sufficient for write access.
  Workspace-level authorization rules also apply:

  * TEAM-owned workspace: `owner`, `admin`, `editor` can write; `viewer` cannot.
  * Non-TEAM workspace: owner-only write behavior.
  * If the workspace owner plan does not include API write (for example FREE), write is blocked with `403`.
</Note>

## Token Management

### Viewing Active Tokens

See all your active API tokens in the Settings page:

* Token name
* Creation date
* Last used date
* Partial token display (first 12 characters)

### Revoking Tokens

To revoke a token:

1. Go to **Settings**
2. Find the token in the list
3. Click the trash icon
4. Confirm deletion

<Warning>
  Revoking a token is immediate and cannot be undone. Any applications using the revoked token will stop working immediately.
</Warning>

## Security Best Practices

### ✅ Do's

* Store tokens in environment variables
* Use different tokens for different environments (dev, staging, production)
* Rotate tokens regularly
* Revoke tokens immediately if compromised
* Use secret management services (AWS Secrets Manager, HashiCorp Vault, etc.)

### ❌ Don'ts

* Never commit tokens to version control
* Never share tokens via email or chat
* Never log tokens in plain text
* Never use production tokens in development
* Never hard-code tokens in your application

## Error Responses

### 401 Unauthorized

Missing or invalid token:

```json theme={null}
{
  "error": "Invalid API token"
}
```

**Causes:**

* Token not provided in Authorization header
* Token format is incorrect
* Token has been revoked
* Token doesn't exist

**Solution:**

* Verify your token is correct
* Check the Authorization header format
* Generate a new token if necessary

### 429 Too Many Requests

Rate limit exceeded:

```json theme={null}
{
  "error": "Rate limit exceeded. Please try again later."
}
```

See [Rate Limits](/api-reference/rate-limits) for more information.

## CI/CD Integration

### GitHub Actions

Store your token as a secret:

```yaml .github/workflows/sync-tokens.yml theme={null}
name: Sync Design Tokens

on:
  schedule:
    - cron: '0 0 * * *'  # Daily

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Download tokens
        run: |
          curl -H "Authorization: Bearer ${{ secrets.TOKENCRAFT_TOKEN }}" \
            "https://app.tokencraft.dev/api/v1/tokensets/${{ secrets.TOKENSET_ID }}/modes/light/export?format=css" \
            -o src/tokens.css
      
      - name: Commit changes
        run: |
          git config user.name "GitHub Actions"
          git config user.email "actions@github.com"
          git add src/tokens.css
          git diff --staged --quiet || git commit -m "Update design tokens"
          git push
```

### GitLab CI

```yaml .gitlab-ci.yml theme={null}
sync-tokens:
  script:
    - curl -H "Authorization: Bearer $TOKENCRAFT_TOKEN"
        "https://app.tokencraft.dev/api/v1/tokensets/$TOKENSET_ID/modes/light/export?format=css"
        -o src/tokens.css
  only:
    - schedules
```

## Rate Limiting

Each API token is subject to rate limiting:

* **100 requests per minute** per token
* Rate limit resets every 60 seconds
* Headers include rate limit information

See [Rate Limits](/api-reference/rate-limits) for details.

## Next Steps

<CardGroup cols={2}>
  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Explore all available endpoints
  </Card>

  <Card title="Rate Limits" icon="gauge" href="/api-reference/rate-limits">
    Understand rate limiting
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/api-reference/errors">
    Learn about error responses
  </Card>

  <Card title="GitHub Actions" icon="github" href="/integrations/github-actions">
    Automate token syncing
  </Card>
</CardGroup>
