> ## Documentation Index
> Fetch the complete documentation index at: https://tokenlayer-2a53bba4.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Learn how to authenticate your API requests

## Overview

The Thrust API uses **JWT tokens** or **API Key** for authentication. Most endpoints require a valid JWT token passed as a Bearer token in the Authorization header.

## Getting a JWT Token

To authenticate with the Thrust API, you need to:

1. **Create an thrust identity** or log in through the Thrust application at onthrust.com
2. However your username in top right corner at onthrust.com and click the API Key to copy it.
3. **Include the API key** in all API requests as Bearer API\_KEY

### Authentication Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Thrust App
    participant Ory
    participant API

    User->>Thrust App: Login
    Thrust App->>Ory: Authenticate
    Ory-->>Thrust App: JWT Token
    Thrust App->>API: Request with Bearer Token
    API-->>Thrust App: Response
```

## Using the API Key

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

```bash theme={null}
curl -X POST "https://yppncslmsswqydhhgygz.supabase.co/functions/v1/get-tokens" \
  -H "Authorization: Bearer API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "filter": "trending",
    "limit": 20
  }'
```

## Using the Token

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

```bash theme={null}
curl -X POST "https://yppncslmsswqydhhgygz.supabase.co/functions/v1/get-tokens" \
  -H "Authorization: Bearer API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "filter": "trending",
    "limit": 20
  }'
```

### Header Format

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

## Token Claims

The JWT token contains the following claims:

| Claim | Description                       |
| ----- | --------------------------------- |
| `sub` | User ID (used throughout the API) |
| `iat` | Issued at timestamp               |
| `exp` | Expiration timestamp              |
| `iss` | Token issuer (Ory)                |

## Authentication Examples

<CodeGroup>
  ```javascript JavaScript/TypeScript theme={null}
  const fetchWithAuth = async (endpoint, data) => {
    const token = localStorage.getItem('jwt_token');

    const response = await fetch(
      `https://yppncslmsswqydhhgygz.supabase.co/functions/v1/${endpoint}`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      }
    );

    return response.json();
  };

  // Example usage
  const tokens = await fetchWithAuth('get-tokens', {
    filter: 'trending',
    limit: 20
  });
  ```

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

  def fetch_with_auth(endpoint, data):
      token = get_jwt_token()  # Your token retrieval method

      response = requests.post(
          f"https://yppncslmsswqydhhgygz.supabase.co/functions/v1/{endpoint}",
          headers={
              "Authorization": f"Bearer {token}",
              "Content-Type": "application/json"
          },
          json=data
      )

      return response.json()

  # Example usage
  tokens = fetch_with_auth("get-tokens", {
      "filter": "trending",
      "limit": 20
  })
  ```

  ```bash cURL theme={null}
  #!/bin/bash

  JWT_TOKEN="API_KEY_here"
  API_URL="https://yppncslmsswqydhhgygz.supabase.co/functions/v1"

  curl -X POST "${API_URL}/get-tokens" \
    -H "Authorization: Bearer ${JWT_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
      "filter": "trending",
      "limit": 20
    }'
  ```
</CodeGroup>

## Token Lifecycle

### Token Expiration

JWT tokens expire after a set period. When a token expires:

1. The API returns a `401 Unauthorized` error
2. Error message: `"Invalid or expired authentication token"`
3. Your application should refresh the token or prompt re-authentication

### Handling Expired Tokens

```javascript theme={null}
const apiCall = async (endpoint, data) => {
  let response = await fetchWithAuth(endpoint, data);

  if (response.error && response.error.includes('expired')) {
    // Refresh token or re-authenticate
    await refreshToken();

    // Retry request
    response = await fetchWithAuth(endpoint, data);
  }

  return response;
};
```

## Optional Authentication

Some endpoints support **optional authentication**:

* `/get-tokens` - Returns public token data, with user-specific vote data if authenticated
* `/get-posts` - Shows public posts, with user votes if authenticated
* `/get-topics` - Returns topics, with user-specific data if authenticated

For these endpoints, you can make requests without a token, but you'll receive limited data.

## Security Best Practices

<Warning>
  Never expose your JWT tokens in client-side code, public repositories, or logs.
</Warning>

### Recommended Practices

1. **Store tokens securely**
   * Use secure storage (localStorage with encryption, or httpOnly cookies)
   * Never commit tokens to version control

2. **Implement token refresh**
   * Refresh tokens before they expire
   * Handle token expiration gracefully

3. **Use HTTPS only**
   * Always use HTTPS for API requests
   * Tokens sent over HTTP can be intercepted

4. **Validate on the server**
   * The API validates all tokens server-side
   * Never trust client-side validation alone

## Common Authentication Errors

| Status Code | Error Message                           | Solution                                       |
| ----------- | --------------------------------------- | ---------------------------------------------- |
| 401         | Missing authorization header            | Include `Authorization: Bearer {token}` header |
| 401         | Invalid or expired authentication token | Refresh your token or re-authenticate          |
| 401         | No user ID in token                     | Token is malformed, obtain a new token         |
| 403         | Insufficient permissions                | User doesn't have access to this resource      |

## Testing Authentication

Use the `/get-notifications` endpoint to test your authentication:

```bash theme={null}
curl -X POST "https://yppncslmsswqydhhgygz.supabase.co/functions/v1/get-notifications" \
  -H "Authorization: Bearer API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"limit": 1}'
```

If authentication is successful, you'll receive your notifications. Otherwise, you'll get a `401` error.

## Next Steps

<CardGroup cols={2}>
  <Card title="Quickstart" icon="rocket" href="/quickstart">
    Make your first authenticated API call
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference">
    Explore available endpoints
  </Card>
</CardGroup>
