# Auth & token refresh

> Authenticate sync uploads with a static header or an AuthConfig recipe the SDK refreshes itself: the recipe fields, your refresh endpoint's contract, and when refresh happens.

Source: https://docs.getbeekon.com/guide/sync-auth/

Once [sync is on](https://docs.getbeekon.com/guide/sync/), every upload can carry credentials your [ingest endpoint](https://docs.getbeekon.com/guide/payload/#build-your-ingest-endpoint) checks. This page covers the two ways to attach them and how the SDK keeps a rotating token fresh.

**On this topic:** [Turn on sync](https://docs.getbeekon.com/guide/sync/) · [Upload payload & ingest endpoint](https://docs.getbeekon.com/guide/payload/) · Auth & token refresh (this page)

## Static header or declarative refresh

There are two ways to authenticate uploads:

* **Static header:** a fixed API key in `SyncConfig.headers`. It never rotates, and it is stored in plaintext on the device.
* **Declarative refresh:** an `AuthConfig` recipe. The SDK attaches a bearer token and refreshes it against your token endpoint: before it expires, and again after a `401` or `403`. Refresh runs in the background and after a cold launch, with no callback into your app code.

Use the static header for low-stakes keys; use `AuthConfig` for anything that should rotate.

### Configure declarative refresh

* Android

  ```kotlin
  SyncConfig(
    url = "https://api.example.com/locations",
    auth = AuthConfig(
      accessToken = "<initial access token>",      // seed, optional
      refreshToken = "<initial refresh token>",     // seed
      expiresAt = System.currentTimeMillis() / 1000 + 3600, // epoch seconds
      refreshUrl = "https://auth.example.com/oauth/token",
      refreshPayload = mapOf(
        "grant_type" to "refresh_token",
        "refresh_token" to "{refreshToken}",        // substituted at refresh time
      ),
      // strategy = AuthStrategy.Bearer, refreshBodyFormat = AuthBodyFormat.Form,
      // skewMarginSeconds = 60 (all defaults)
    ),
  )
  ```

* iOS

  ```swift
  SyncConfig(
    url: URL(string: "https://api.example.com/locations")!,
    auth: AuthConfig(
      accessToken: "<initial access token>",        // seed, optional
      refreshToken: "<initial refresh token>",       // seed
      expiresAt: Date().timeIntervalSince1970 + 3600, // epoch seconds
      refreshUrl: URL(string: "https://auth.example.com/oauth/token")!,
      refreshPayload: [
        "grant_type": "refresh_token",
        "refresh_token": "{refreshToken}",           // substituted at refresh time
      ]
      // strategy: .bearer, refreshBodyFormat: .form, skewMarginSeconds: 60 (defaults)
    )
  )
  ```

* Flutter

  ```dart
  SyncConfig(
    url: 'https://api.example.com/locations',
    auth: AuthConfig(
      accessToken: '<initial access token>',        // seed, optional
      refreshToken: '<initial refresh token>',       // seed
      expiresAt: DateTime.now().add(const Duration(hours: 1)), // a DateTime
      refreshUrl: 'https://auth.example.com/oauth/token',
      refreshPayload: {
        'grant_type': 'refresh_token',
        'refresh_token': '{refreshToken}',           // substituted at refresh time
      },
      // strategy: AuthStrategy.bearer, refreshBodyFormat: AuthBodyFormat.form,
      // skewMarginSeconds: 60 (defaults)
    ),
  )
  ```

* React Native

  ```ts
  {
    url: 'https://api.example.com/locations',
    auth: {
      accessToken: '<initial access token>',        // seed, optional
      refreshToken: '<initial refresh token>',       // seed
      expiresAt: new Date(Date.now() + 3600 * 1000), // a Date
      refreshUrl: 'https://auth.example.com/oauth/token',
      refreshPayload: {
        grant_type: 'refresh_token',
        refresh_token: '{refreshToken}',             // substituted at refresh time
      },
      // strategy: 'bearer', refreshBodyFormat: 'form', skewMarginSeconds: 60
      // (defaults)
    },
  }
  ```

The tokens you pass are a **seed**. The SDK adopts them once, then keeps and rotates the live tokens in encrypted storage (Keychain on iOS, Keystore on Android). Passing the same or a different seed again later changes nothing while a token is stored, unless you raise `seedEpoch`. Each rotation arrives on the `authChanges` stream (`onAuthTokens` in React Native); copy it into your own session store if you need it.

### The recipe

| Field               | Default                               | Meaning                                                                                                                                                                                                                                                                                                   |
| ------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accessToken`       | none                                  | Seed access token (optional).                                                                                                                                                                                                                                                                             |
| `refreshToken`      | none                                  | Seed refresh token, or another long-lived credential.                                                                                                                                                                                                                                                     |
| `expiresAt`         | none                                  | Seed expiry: epoch seconds on Android (`Long`) and iOS (`TimeInterval`), a `DateTime` in Flutter, a `Date` in React Native. Without it there is no proactive refresh, only the refresh after a `401` or `403`.                                                                                            |
| `strategy`          | `Bearer`                              | How the token is attached: `Bearer` sends `Authorization: Bearer <token>`; `Raw` sends `Authorization: <token>`.                                                                                                                                                                                          |
| `refreshUrl`        | none                                  | Token endpoint. Without it the SDK uses the seed and never refreshes.                                                                                                                                                                                                                                     |
| `refreshPayload`    | `{}`                                  | Request body fields. `{accessToken}` / `{refreshToken}` are substituted with the current tokens.                                                                                                                                                                                                          |
| `refreshHeaders`    | `Authorization: Bearer {accessToken}` | Request headers, same templating.                                                                                                                                                                                                                                                                         |
| `refreshBodyFormat` | `Form`                                | `Form` (`application/x-www-form-urlencoded`) or `Json`.                                                                                                                                                                                                                                                   |
| `responseMapping`   | none                                  | Overrides the keys Beekon reads from the response. Dot paths such as `data.access_token` work.                                                                                                                                                                                                            |
| `skewMarginSeconds` | `60`                                  | Refresh this many seconds before `expiresAt`.                                                                                                                                                                                                                                                             |
| `seedEpoch`         | none                                  | A number you raise to replace the stored tokens with a new seed, for example after the user signs in again. When it is greater than the stored epoch, the SDK adopts the seed you pass. Without it, a seed is adopted only when no token is stored yet. An integer on every platform (`Long` on Android). |

### Your refresh endpoint

To refresh, the SDK sends a `POST` to `refreshUrl` with the templated payload (15 s timeout) and reads the new token from the response. Answer `2xx` with JSON:

```json
{ "access_token": "<new token>", "expires_in": 3600 }
```

Beekon reads the token from the first key present: `responseMapping.accessToken`, then `access_token`, `accessToken`, `token`. It reads the expiry from the first of `responseMapping.expiresAt` (an absolute time in epoch seconds), `responseMapping.expiresIn` (seconds from now), `expires_at` and `expires_in`; it never looks for camelCase expiry keys in the response unless you map them. A numeric string such as `"3600"` works.

| Refresh returns                               | Outcome                                               |
| --------------------------------------------- | ----------------------------------------------------- |
| `2xx` **with** a token                        | Adopt the new token set, retry the upload.            |
| `2xx` **without** a token                     | Dead credentials. Refreshing stops until you re-seed. |
| `408`, `429`, `5xx`, network error or timeout | Transient. Back off and retry.                        |
| `3xx` or any other `4xx`                      | Dead credentials. Refreshing stops until you re-seed. |

After 3 refresh failures in a row, the SDK backs off exponentially so it doesn’t flood your token endpoint. To recover from dead credentials, call `configure()` with a new `accessToken` and a higher `seedEpoch`.

### How it behaves

* **Proactive:** when `expiresAt` is set, the refresh runs at `expiresAt − skewMarginSeconds`, before a request fails.
* **Reactive:** a `401` or `403` triggers one refresh, then the upload is retried once.
* **One refresh at a time:** concurrent requests share one refresh, so a burst sends one request to your endpoint.
* **Stored encrypted:** rotated tokens survive process death. The upload backlog is kept while auth is failing, so no location is lost.

Caution

The recipe itself (URLs, header and payload templates) is stored in **plaintext**. Put only the `{accessToken}` and `{refreshToken}` templates in it, never a static client secret. The secret is the rotating refresh token, which Beekon stores encrypted.

Next: if uploads fail, the [sync checklist](https://docs.getbeekon.com/guide/diagnostics/#sync-keeps-failing) lists the usual causes.
