# Token lifecycle (/docs/guides/token-lifecycle)

AISquare supports a token-based authentication flow built on access tokens and
refresh tokens. Tokens let you authenticate users without resending the API key
on every request. This page covers the flow, how to refresh safely, and how to
handle failures in a production system.

## Token types [#token-types]

| Token         | Purpose                     | Expiry  |
| ------------- | --------------------------- | ------- |
| Access token  | Authenticates API requests  | 7 days  |
| Refresh token | Generates new access tokens | 30 days |

## The flow [#the-flow]

```text
API key  ->  login  ->  access token + refresh token
   |
use access token for requests
   |
access token expires
   |
use refresh token to get a new access token
```

<Steps>
  <Step>
    ### Obtain tokens [#obtain-tokens]

    Call the login endpoint with the user's API key. You receive an access token and
    a refresh token.
  </Step>

  <Step>
    ### Use the access token [#use-the-access-token]

    Send the access token on every authenticated request.

    ```text
    Authorization: Bearer <access_token>
    ```
  </Step>

  <Step>
    ### Handle expiration [#handle-expiration]

    The access token expires after 7 days. When a request fails with an
    authentication error, detect it and trigger a refresh.
  </Step>

  <Step>
    ### Refresh the token [#refresh-the-token]

    Use the refresh token to mint a new access token, then replace the expired one.

    ```text
    refresh_token  ->  new access_token
    ```
  </Step>
</Steps>

## Where to manage tokens [#where-to-manage-tokens]

<Callout type="info" title="Manage tokens on the backend">
  Store and refresh tokens on your server, not in the browser. A backend keeps
  credentials out of client code, centralizes refresh logic, and avoids token
  leakage. See [Integration patterns](/docs/guides/integration-patterns).
</Callout>

A backend-managed flow looks like this:

```text
user request
   |
backend checks token validity
   |
if expired -> refresh token
   |
call AISquare API
```

Storing tokens in a frontend app risks leakage, makes refresh hard to
coordinate, and widens your attack surface. Avoid it.

## Refresh strategies [#refresh-strategies]

Pick the strategy that matches how long your sessions run.

* **Reactive.** Make the request; if it fails on expiry, refresh and retry.
  Simple, and fine for low-traffic paths.

* **Proactive.** Track the expiry time and refresh just before it lapses.

  ```text
  if current_time > expiry_time - buffer:
      refresh token
  ```

* **Background.** Refresh on a schedule so long-running sessions never block on a
  refresh.

## Handling failures [#handling-failures]

| Situation             | What to do                                          |
| --------------------- | --------------------------------------------------- |
| Access token expired  | Refresh with the refresh token, then retry.         |
| Refresh token expired | Re-authenticate with the API key to get new tokens. |
| Invalid token         | Clear stored tokens and restart the flow.           |

See [Errors](/docs/reference/errors) for the status codes behind these cases.

## Storage best practices [#storage-best-practices]

* **Store securely.** Use encrypted storage; never keep tokens in plain text.

* **Associate with the user.** Keep tokens keyed to your user ID.

  ```text
  user_id  ->  access_token + refresh_token
  ```

* **Rotate safely.** Replace old tokens immediately after a refresh and never
  reuse a stale one.

## API key or tokens [#api-key-or-tokens]

| Scenario             | Recommended               |
| -------------------- | ------------------------- |
| Simple backend calls | API key                   |
| User sessions        | Access and refresh tokens |
| Long-running apps    | Tokens with refresh       |

## Putting it together [#putting-it-together]

1. Register the user and get an API key.
2. Log in to get tokens.
3. Use the access token for requests.
4. Refresh when it expires.
5. Repeat.

## Next steps [#next-steps]

<Cards>
  <Card title="Authentication" href="/docs/getting-started/authentication" description="All supported auth methods, including JWT and SSO." />

  <Card title="User onboarding" href="/docs/guides/user-onboarding" description="Register users and get their API keys." />

  <Card title="Integration patterns" href="/docs/guides/integration-patterns" description="Where token management lives in your architecture." />

  <Card title="Errors" href="/docs/reference/errors" description="Handle 401 and token expiry responses." />
</Cards>
