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

# Rotate an internal connection's API token

> Set up a scheduled job that replaces an internal connection's API token before it expires.

With **token exchange**, a scheduled job trades an internal connection's current API token for a new one. Each request is signed with a private key that only you hold. For how lifetimes, signing keys, and revocation work, read [How token rotation works](https://developers.notion.com/guides/connections-and-tokens/token-rotation.md).

## Before you begin

You need:

* An [internal connection](https://developers.notion.com/guides/connections-and-tokens/internal-connections.md) and its current API token.
* Permission to manage the connection: you're one of its owners or a workspace owner. If nobody was added on the connection's **Owners** tab, its creator can manage it too.
* A JWT or crypto library. The example on this page uses Node.js 20 or later.

Each connection has its own key, token, and lifetime, so set up each one separately.

## Set up the connection

**1. Generate a key pair**

Use ES256 (an elliptic curve key on the P-256 curve) or RS256 (an RSA key of at least 2,048 bits).

```bash ES256 theme={null}
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out notion-signing-key.pem
openssl pkey -in notion-signing-key.pem -pubout -out notion-signing-key.pub.pem
```

```bash RS256 theme={null}
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out notion-signing-key.pem
openssl pkey -in notion-signing-key.pem -pubout -out notion-signing-key.pub.pem
```

`notion-signing-key.pem` is the private key. Store it in your secret manager next to the connection's API token, then delete the local file. Never commit or share it. `notion-signing-key.pub.pem` is the public key.

The file names are only examples. Notion never sees them, and they don't need to match the key ID. RSA keys must use the standard public exponent, 65537, which is the `openssl` default.

**2. Register the public key**

Open the connection in the [Developer portal](https://app.notion.com/developers/connections). Under **Programmatic token rotation**, select **Add a signing key**, and paste the public key into **Public key or JWK**. It can be a PEM public key or a JWK.

**Key ID (optional)** is the name your requests use to pick this key, up to 256 characters. If you leave it blank, Notion creates one from the key. Select **Add signing key**, then copy the key ID from the **Signing keys** table.

A connection can have up to 5 signing keys that aren't revoked. To replace one later, see [Rotate signing keys](#rotate-signing-keys).

**3. Choose a token lifetime**

On the connection's page, select **New token expiration**, choose an **Expiration**, and select **Save expiration**. With the default, **No expiration**, exchanged tokens never expire.

Pick a lifetime longer than your rotation schedule. If the job runs every 30 days, a 90-day lifetime leaves 60 days to fix a failed run. The setting applies to new tokens. To apply it to the current token too, turn on **Apply expiration to current API token** before you save.

If the token gets close to expiring, the connection's owners get [expiry warnings](https://developers.notion.com/guides/connections-and-tokens/token-rotation.md#expiry-warnings) 7 days and 1 day before.

**4. Note the client ID**

Copy the connection's **Client ID** from the Developer portal. Your requests use it in the `iss` and `sub` claims.

## Build a client assertion

Every token exchange request carries a **client assertion**: a JWT that your job signs with the private key. Notion checks the signature against the connection's signing keys, then checks the claims. Create a new assertion for every request, including retries.

In the JWT header, set `alg` to `ES256` or `RS256` to match your key, and `kid` to the key ID. Without `kid`, Notion tries each of the connection's signing keys.

The payload must have these claims:

| Claim | Value |
| :- | :- |
| `iss` | The connection's client ID. |
| `sub` | The connection's client ID, the same as `iss`. |
| `aud` | `https://api.notion.com/v1/oauth/token` |
| `iat` | When you created the assertion, in seconds since the Unix epoch. It can't be in the future. |
| `exp` | When the assertion expires, in seconds since the Unix epoch. At most 5 minutes after `iat`. One minute is enough. |
| `jti` | A unique ID of up to 256 characters, such as a UUID. Notion rejects a `jti` it has already seen for the connection. |

Notion allows 30 seconds of clock difference when it checks `iat` and `exp`.

This example builds an assertion with Node.js built-in modules:

```javascript Node.js theme={null}
import { createPrivateKey, randomUUID, sign } from "node:crypto";

export function createClientAssertion({ clientId, privateKeyPem, keyId, audience }) {
  const privateKey = createPrivateKey(privateKeyPem);
  const alg = privateKey.asymmetricKeyType === "ec" ? "ES256" : "RS256";
  const header = { alg, typ: "JWT", ...(keyId ? { kid: keyId } : {}) };
  const now = Math.floor(Date.now() / 1000);
  const claims = {
    iss: clientId,
    sub: clientId,
    aud: audience,
    iat: now,
    exp: now + 60,
    jti: randomUUID(),
  };
  const signingInput = `${base64url(header)}.${base64url(claims)}`;
  // A JWT carries an ES256 signature as raw r||s bytes, not DER.
  const signature = sign(
    "sha256",
    Buffer.from(signingInput),
    alg === "ES256" ? { key: privateKey, dsaEncoding: "ieee-p1363" } : privateKey,
  );
  return `${signingInput}.${signature.toString("base64url")}`;
}

function base64url(value) {
  return Buffer.from(JSON.stringify(value)).toString("base64url");
}
```

> [!NOTE]
>
> If you sign with a cloud key management service such as AWS KMS, use an RSA key and RS256. KMS returns ES256 signatures DER-encoded, which Notion rejects.

## Exchange the token

Send a `POST` request to `/v1/oauth/token` with a form-encoded (`application/x-www-form-urlencoded`) or JSON body. Don't send an `Authorization` header. The client assertion authenticates the request.

| Parameter | Value |
| :- | :- |
| `grant_type` | `urn:ietf:params:oauth:grant-type:token-exchange` |
| `subject_token` | The connection's current API token. |
| `subject_token_type` | `urn:ietf:params:oauth:token-type:access_token` |
| `client_assertion_type` | `urn:ietf:params:oauth:client-assertion-type:jwt-bearer` |
| `client_assertion` | The client assertion. |
| `client_id` | Optional. If you send it, it must match the assertion's `iss`. |

```bash cURL theme={null}
curl -X POST https://api.notion.com/v1/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
  --data-urlencode "subject_token=$NOTION_TOKEN" \
  --data-urlencode "subject_token_type=urn:ietf:params:oauth:token-type:access_token" \
  --data-urlencode "client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer" \
  --data-urlencode "client_assertion=$CLIENT_ASSERTION"
```

A successful response looks like this:

```json theme={null}
{
  "access_token": "ntn_...",
  "token_type": "bearer",
  "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
  "expires_in": 7776000,
  "bot_id": "3f8104cd-477e-814b-86f2-00278bbc1c05",
  "workspace_id": "7b9104cd-477e-8130-b489-000349c9fa52",
  "workspace_name": "Acme Engineering",
  "workspace_icon": null,
  "owner": { "type": "workspace", "workspace": true },
  "duplicated_template_id": null,
  "request_id": "b20f6fc9-04c7-4b40-acfa-d58243af516c"
}
```

`access_token` is the new token, and `expires_in` is its lifetime in seconds. `expires_in` is missing when the connection's token expiration is **No expiration**. There's no `refresh_token`.

> [!WARNING]
>
> The response contains the new token. Don't log it. Keep tokens and private keys out of client-side code and repositories.

## Store the new token safely

The old token keeps working until the new token makes its first successful API call. Then Notion revokes the old token. Follow these rules so your applications never hold a revoked token.

### Store the new token before you use it

Write the new token to your secret store, and confirm the write succeeded, before any API call with it. If you call the API first and the write then fails, the old token is revoked and the new one is lost. To recover, select **Refresh** in the Developer portal.

### Retry a failed run with the old token

If the job fails before it stores the new token, run it again with the same old token. Notion revokes the unused token from the failed run and returns another.

### Run one rotation job per connection

A second exchange of the same token revokes the first job's new token. While an exchange for a connection is in progress, another one gets a `400` error, so retry a few seconds later. Each connection can make 10 exchange requests an hour, including ones that fail with `invalid_request`. A job that retries in a tight loop can lock the connection out for up to an hour.

### Reload the token on a `401` error

Once the new token is used, processes that cached the old token get a `401` error. They should read the token from your secret store again and retry once. If the retry also fails, report the error instead of retrying in a loop.

## Use a secret manager

Keep each connection's API token and private key in a secret manager. For each connection, your scheduled job should:

1. Read the current API token, client ID, key ID, and private key.
2. [Exchange the token](#exchange-the-token).
3. Write the new token back, replacing the old one. If the write fails, stop and alert someone.
4. Optionally, call `GET /v1/users/me` with the new token to confirm it works. This revokes the old token.

Only the job and your applications should read these secrets, and only the job should write them. If you rotate many connections, run them one at a time or with low concurrency, and record failures so you can retry them.

## Rotate signing keys

Replace a signing key on a schedule, or right away if its private key may have been exposed. A connection can have more than one live key, so there's no gap:

1. Generate a new key pair, as in [Set up the connection](#set-up-the-connection).
2. In the Developer portal, add the new public key with a key ID the connection hasn't used before. A revoked key can't be added again.
3. In your secret manager, replace the private key and key ID. The job's next exchange uses the new key.
4. After a run succeeds with the new key, revoke the old key in the Developer portal.

## Troubleshoot

### Token exchange errors

Errors from `POST /v1/oauth/token` have an `error` code and, for most errors, an `error_description`.

| Status | `error` | `error_description` | What to do |
| :- | :- | :- | :- |
| 401 | `invalid_client` | None | The client assertion was rejected. See [Fix `invalid_client` errors](#fix-invalid_client-errors). |
| 400 | `invalid_request` | `Invalid subject token` | The `subject_token` is expired, revoked, replaced through **Refresh** in the Developer portal, or from a different connection. If a newer token replaced it, read that token from your secret store. Otherwise, select **Refresh** and store the new token. |
| 400 | `invalid_request` | `Another token exchange for this connection is in progress. Retry shortly.` | Wait a few seconds and retry. If this happens often, check that only one job rotates the connection. |
| 400 | `invalid_request` | Starts with `body failed validation` and names the missing or invalid parameter | Check the request against [Exchange the token](#exchange-the-token). |
| 429 | `rate_limited` | `Too many token exchange requests for this connection. Retry in N seconds.` | The connection made 10 exchange requests in the last hour, including failed ones. Wait the number of seconds in the message. |
| 429 | `rate_limited` | `Too many client assertion attempts. Retry in N seconds.` | Your IP address sent too many client assertions in the last minute. Wait the number of seconds in the message, then retry with a new client assertion. |

### Fix `invalid_client` errors

Notion returns `invalid_client` for every client authentication failure and doesn't say which check failed. Check that:

* The request has no `Authorization` header. Token exchange doesn't accept a client secret or HTTP Basic authentication.
* `client_assertion_type` is exactly `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`.
* `iss` and `sub` are both the client ID of an internal connection that still exists. If you send `client_id`, it matches `iss`.
* `aud` is exactly `https://api.notion.com/v1/oauth/token`, with no trailing slash.
* `alg` is `ES256` or `RS256`, and the assertion is signed with the private key of a live signing key. If you set `kid`, it matches that key's key ID.
* An ES256 signature is in raw `r||s` form, not DER.
* `iat` isn't in the future, `exp` hasn't passed, and `exp` is at most 5 minutes after `iat`. Check your server's clock.
* `jti` is new for every request, including retries, and at most 256 characters.

### Expired tokens

The API rejects an expired token with the same error as a revoked or unknown one: `401`, `unauthorized`, `API token is invalid.` Exchanging it returns `400`, `invalid_request`, `Invalid subject token`. Store each token's expiry from `expires_in` so you can tell these cases apart. If a token expires, select **Refresh** in the Developer portal, store the new token, and find out why the job didn't run in time.
