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

# Authentication

> Understand how authentication works across the CollabKit platform.

Sign up at the [CollabKit dashboard](https://dash.collab-kit.com) to create your organization. Once logged in, go to **Settings** to find your **Account ID** and **API Key**.

CollabKit uses two authentication mechanisms:

| Mechanism        | Used For                                                        | Format                                             |
| ---------------- | --------------------------------------------------------------- | -------------------------------------------------- |
| **Bearer Token** | All REST API calls (rooms, users, storage, webhooks, workflows) | `Authorization: Bearer <base64(accountId:apiKey)>` |
| **JWT Token**    | Client SDK WebSocket connections                                | Passed to the Client SDK manullay                  |

## Bearer Authentication

All REST API endpoints require Bearer authentication.

### Constructing the Token

The Bearer token is a Base64-encoded string combining your `accountId` and `apiKey`:

<Tabs>
  <Tab title="Bash">
    ```bash theme={null}
    TOKEN=$(echo -n "${ACCOUNT_ID}:${API_KEY}" | base64)
    ```
  </Tab>

  <Tab title="Javascript">
    ```typescript theme={null}
    const token = btoa(`${accountId}:${apiKey}`);
    ```
  </Tab>
</Tabs>

### Using the Token

Include it in the `Authorization` header:

<Tabs>
  <Tab title="Bash">
    ```bash theme={null}
      curl -X GET https://api.collab-kit.com/v1/accounts/${ACCOUNT_ID}/rooms \
        -H "Authorization: Bearer ${TOKEN}"
    ```
  </Tab>

  <Tab title="Javascript">
    ```typescript theme={null}
    const res = await fetch(`https://api.collab-kit.com/v1/accounts/${accountId}/rooms`, {
      headers: { 'Authorization': `Bearer ${token}` },
    });
    const { data } = await res.json();
    ```
  </Tab>
</Tabs>

## JWT Authentication (Client SDK)

The client SDK authenticates over WebSocket using a JWT token. You get this token when you [create a user](/api-reference/users/create-user) via the REST API.

### Getting a JWT

<Tabs>
  <Tab title="Bash">
    ```bash theme={null}
      curl -X POST https://api.collab-kit.com/v1/accounts/${ACCOUNT_ID}/users \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d '{
          "name": "Alice",
          "roomId": "room-id-here"
        }'
    ```
  </Tab>

  <Tab title="Javascript">
    ```typescript theme={null}
    const res = await fetch(`https://api.collab-kit.com/v1/accounts/${accountId}/users`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: 'Alice',
        roomId: 'room-id-here',
      }),
    });
    const { data } = await res.json();
    ```
  </Tab>
</Tabs>

The response includes a `token` field containing the JWT:

```json theme={null}
{
  "success": true,
  "data": {
    "user": { "id": "f47ac10b-58cc-4372-...", "name": "Alice", "status": "offline" },
    "token": "eyJhbGciOiJIUzI1NiIs..."
  }
}
```

### Using the JWT

Pass the JWT when constructing the client:

```typescript theme={null}
const client = new CollabKitClient({
  serverUrl: 'https://api.collab-kit.com',
  authToken: 'eyJhbGciOiJIUzI1NiIs...',
});

await client.join(); // defaults to { role: 'editor' }
// await client.join({ role: 'viewer' });
```

The SDK sends the JWT with the `JOIN_ROOM` message, which performs both authentication and room join in a single step. If the token is invalid or expired, the `authFailed` socket event fires:

```typescript theme={null}
client.socket.on('authFailed', () => {
  console.error('Authentication failed - token may be expired');
  // Redirect to login or refresh the token
});
```

### Token Lifecycle

* Tokens are valid for **90 days** from creation
* Each call to `POST /users` generates a new token for that user
* Each call to `POST /users` creates a new user with a server-generated UUID
* There is no refresh endpoint -- create a new user entry to get a new token

## Error Responses

Authentication failures return a standard error response:

```json theme={null}
{
  "type": "response",
  "success": false,
  "description": "Unauthorized",
  "data": {},
  "error": {
    "module": "Auth",
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing authentication credentials"
  }
}
```

| HTTP Status | Cause                                                        |
| ----------- | ------------------------------------------------------------ |
| `401`       | Missing, malformed, or invalid Bearer token / session cookie |
| `403`       | Valid credentials but insufficient permissions               |
