Source: https://developers.tokportal.com/authentication/
Markdown: https://developers.tokportal.com/authentication.md

# Authentication

The TokPortal API uses API keys to authenticate requests. Include your key in the `X-API-Key` header on every request.

## API Key Format

Keys follow the format:

```
sk_<64 lowercase hexadecimal characters>
```

Example:

```
sk_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4
```

## Generating an API Key

1. Sign in to your TokPortal account.
2. Navigate to **Developer > API Keys** at [app.tokportal.com/developer/api-keys](https://app.tokportal.com/developer/api-keys).
3. Click **Create New Key**.
4. Copy the key immediately — it is shown only once.

You can create **multiple keys** per account. This is useful for separating keys across environments (development, staging, production) or across different services.

## Environments, Scopes, and Expiry

When you create a key, tag it with an environment:

| Environment   | Recommended use                            |
| ------------- | ------------------------------------------ |
| `production`  | Live servers and partner integrations      |
| `staging`     | Pre-production validation                  |
| `development` | Local development                          |
| `test`        | Short-lived experiments and CI smoke tests |

Keys also support broad access scopes:

| Scope   | Allows                                                   |
| ------- | -------------------------------------------------------- |
| `*`     | Full access. This is the default for existing keys.      |
| `read`  | `GET` requests only.                                     |
| `write` | Mutating requests: `POST`, `PUT`, `PATCH`, and `DELETE`. |

Use read-only keys for dashboards and sync jobs that never mutate TokPortal state. Use expiring keys for contractors, temporary scripts, and tests.

You can update a key's display name, environment tag, access scope, and expiry date from **Developer > API Keys** without rotating the secret. Rotate when the secret itself may be exposed or when you need a fresh value for deployment.

## Key Storage and Security

API keys are **hashed with SHA-256** before being stored. TokPortal never retains the plain-text version of your key. If you lose a key, you must revoke it and generate a new one.

## Legacy key transition

Current keys use the `sk_` format above. If an older integration still uses a key issued in a retired legacy format, rotate it before relying on this release:

1. Create a current key in **Developer > API Keys** with the required scope.
2. Deploy the new key to the integration without revoking the old key yet.
3. Verify successful authenticated requests and inspect the new key's usage log.
4. Revoke the old key only after every service has moved.

TokPortal contacts owners of active legacy key records separately. There is no dedicated runtime error that identifies a legacy key safely. A retired or otherwise unrecognized key returns the ordinary `401 AUTH_INVALID_KEY`, so do not build fallback logic that scans or retries old secrets. Never send either key to support.

## Request IDs and Usage Logs

Every public API response includes `X-TokPortal-Request-ID`. Store this value in your logs and include it when contacting support.

TokPortal also records request usage per API key in the Developer Portal. Open **Developer > API Keys**, choose a key, and inspect recent requests, status codes, latency, credits charged, and request IDs. This makes it easier to debug one integration without mixing production, staging, and local traffic.

## API Key Audit Trail

TokPortal records key lifecycle events separately from request logs:

- key created
- key metadata updated
- key rotated
- rotation replacement key created
- key revoked

Open **Developer > API Keys**, choose a key, and inspect **Key audit trail** to see when the key changed and which metadata was attached at the time, including environment, scopes, expiry, and rotation links.

## Making Authenticated Requests

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

```bash
curl -X GET https://app.tokportal.com/api/ext/me \
  -H "X-API-Key: sk_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4"
```

**Success response:**

```json
{
  "data": {
    "email": "you@example.com",
    "credits": 1250
  }
}
```

**Invalid or missing key:**

```json
{
  "error": {
    "code": "AUTH_INVALID_KEY",
    "message": "The provided API key is invalid."
  }
}
```

## Error Codes

| Code                   | HTTP Status | Description                                                    |
| ---------------------- | ----------- | -------------------------------------------------------------- |
| `AUTH_MISSING_KEY`     | 401         | No `X-API-Key` header was provided.                            |
| `AUTH_INVALID_KEY`     | 401         | The key does not match any account.                            |
| `AUTH_REVOKED_KEY`     | 401         | The key has been revoked. Generate a new one.                  |
| `AUTH_EXPIRED_KEY`     | 401         | The key has expired. Generate or rotate to a new key.          |
| `AUTH_FORBIDDEN_SCOPE` | 403         | The key does not include the required `read` or `write` scope. |

## Security Best Practices

- **Use environment variables.** Never hard-code API keys in source code.

  ```bash
  export TOKPORTAL_API_KEY="sk_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4"
  ```

  ```bash
  curl -X GET https://app.tokportal.com/api/ext/me \
    -H "X-API-Key: $TOKPORTAL_API_KEY"
  ```

- **Never expose keys client-side.** API keys must only be used in server-side code. Never include them in frontend JavaScript, mobile apps, or public repositories.

- **Rotate keys regularly.** Create a new key, migrate your services, then revoke the old one.

- **Use separate keys per environment.** Keep production and development keys distinct so revoking one does not affect the other.

- **Use narrow scopes.** Prefer read-only keys for analytics/reporting jobs and full-access keys only for services that create or update resources.

- **Set expiry dates for temporary access.** Expiring keys are useful for tests, agencies, contractors, and short-lived scripts.

- **Review the audit trail.** Check key lifecycle events during incident response or before deleting old integrations.

- **Revoke compromised keys immediately.** If a key is exposed, revoke it from the developer dashboard and generate a replacement.
