# Get an access token

> The integration signs a short client assertion with its private key and exchanges it for a 15-minute access token. Recipes for curl, Python, Frends and Azure Logic Apps.

An integration has no password or client secret. To get an access token it signs a short JSON Web Token, the **client assertion**, with its private key, and sends it to the token endpoint (OAuth 2 client credentials with `private_key_jwt`, RFC 7523). The token lasts 15 minutes. There is no refresh token: when it expires, sign a new assertion and ask again.

You need the `client_id`, the key id (`kid`), the token endpoint and the private key from [Create an integration](/en/integrations/create-an-integration/).

| Environment | Token endpoint | API address |
|:------------|:---------------|:------------|
| Production | `https://api.whatsbuilt.fi/oauth/token` | `https://api.whatsbuilt.fi/v1` |
| Test | `https://api.test.whatsbuilt.fi/oauth/token` | `https://api.test.whatsbuilt.fi/v1` |
| Development | `https://api.dev.whatsbuilt.fi/oauth/token` | `https://api.dev.whatsbuilt.fi/v1` |

## The client assertion

Header:

```json
{ "alg": "ES256", "kid": "<kid>", "typ": "JWT" }
```

Claims:

```json
{
  "iss": "<client_id>",
  "sub": "<client_id>",
  "aud": "https://api.whatsbuilt.fi/oauth/token",
  "iat": 1763452800,
  "exp": 1763453100,
  "jti": "a new random value for every assertion"
}
```

| Field | Rule |
|:------|:-----|
| `alg` | `ES256` for a key generated in the browser; the key's own algorithm (`ES256` or `RS256`) for a pasted key |
| `kid` | The key id shown on the integration's page |
| `iss`, `sub` | Both the `client_id` |
| `aud` | The token endpoint URL, or the issuer (`https://api.whatsbuilt.fi`) |
| `iat`, `exp` | Seconds since 1970. `exp` at most 300 seconds after `iat`. Clocks may differ by up to 60 seconds |
| `jti` | Unique. An assertion can be used only once |

## Ask for the token

`POST` a form to the token endpoint:

| Field | Value |
|:------|:------|
| `grant_type` | `client_credentials` |
| `client_assertion_type` | `urn:ietf:params:oauth:client-assertion-type:jwt-bearer` |
| `client_assertion` | The signed assertion |
| `scope` | Optional. A space-separated subset of the integration's permissions; all of them by default |

The answer:

```json
{ "access_token": "wbi_at_…", "token_type": "Bearer", "expires_in": 900, "scope": "read" }
```

Send the token on every call as `Authorization: Bearer wbi_at_…`. It works only on `/v1`.

## A worked example with curl

This example makes the assertion with the Python recipe below, saved as `assertion.py`.

```sh
export WB_CLIENT_ID=<client_id>
export WB_KID=<kid>
export WB_KEY_FILE=whatsbuilt-production-planning-1a2b3c4d.pem
export WB_TOKEN_URL=https://api.dev.whatsbuilt.fi/oauth/token

TOKEN=$(curl -s "$WB_TOKEN_URL" \
  -d grant_type=client_credentials \
  -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
  -d client_assertion="$(python3 assertion.py)" | python3 -c 'import json,sys; print(json.load(sys.stdin)["access_token"])')

curl -s https://api.dev.whatsbuilt.fi/v1/me -H "Authorization: Bearer $TOKEN"
```

`GET /v1/me` answers with the integration, its organisation and the token's permissions. Any valid token may call it.

## Python

Needs `pip install "pyjwt[crypto]" requests` (`requests` only for the token fetch below).

```python
import os, time, uuid
import jwt

def client_assertion() -> str:
    now = int(time.time())
    with open(os.environ["WB_KEY_FILE"], "rb") as f:
        private_key = f.read()
    return jwt.encode(
        {
            "iss": os.environ["WB_CLIENT_ID"],
            "sub": os.environ["WB_CLIENT_ID"],
            "aud": os.environ["WB_TOKEN_URL"],
            "iat": now,
            "exp": now + 120,
            "jti": str(uuid.uuid4()),
        },
        private_key,
        algorithm="ES256",
        headers={"kid": os.environ["WB_KID"]},
    )

if __name__ == "__main__":
    print(client_assertion())
```

For an RSA key, use `algorithm="RS256"`. To fetch the token in Python:

```python
import requests

def access_token() -> str:
    answer = requests.post(os.environ["WB_TOKEN_URL"], data={
        "grant_type": "client_credentials",
        "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
        "client_assertion": client_assertion(),
    }, timeout=30)
    answer.raise_for_status()
    return answer.json()["access_token"]
```

## Frends

Frends runs C#, and .NET 6 or later signs ES256 without extra packages. Put the private key in an environment variable of type secret, for example `#env.WhatsBuilt.PrivateKey`, and the `client_id`, `kid` and token endpoint in plain environment variables. In the code below, `PrivateKeyPem`, `ClientId`, `Kid` and `TokenUrl` stand for those variables.

1. A **Code** step (C#) makes the assertion:

   ```csharp
   using System.Security.Cryptography;
   using System.Text;
   using System.Text.Json;

   static string B64(byte[] b) => Convert.ToBase64String(b).TrimEnd('=').Replace('+', '-').Replace('/', '_');

   var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
   var header = JsonSerializer.Serialize(new { alg = "ES256", kid = Kid, typ = "JWT" });
   var claims = JsonSerializer.Serialize(new {
       iss = ClientId, sub = ClientId, aud = TokenUrl,
       iat = now, exp = now + 120, jti = Guid.NewGuid().ToString(),
   });
   var signingInput = B64(Encoding.UTF8.GetBytes(header)) + "." + B64(Encoding.UTF8.GetBytes(claims));
   using var key = ECDsa.Create();
   key.ImportFromPem(PrivateKeyPem);
   var signature = key.SignData(Encoding.ASCII.GetBytes(signingInput), HashAlgorithmName.SHA256);
   return signingInput + "." + B64(signature);
   ```

   `ECDsa.SignData` returns the signature as `r‖s`, the form JWS needs. For an RSA key use `RSA.Create()`, `RSASignaturePadding.Pkcs1` and `alg = "RS256"`.
2. An **HTTP Request** step posts the form of *Ask for the token* to the token endpoint, with `Content-Type: application/x-www-form-urlencoded` and the assertion from step 1.
3. Read `access_token` from the answer and pass it as `Authorization: Bearer …` to the HTTP steps that call `/v1`. Fetch a new token when 15 minutes have passed or a call answers `401`.

## Azure Logic Apps

Logic Apps cannot sign a JWT with a private key on its own, so a small Azure Function signs the assertion and the Logic App does the rest.

1. Store the private key in **Azure Key Vault** as a secret, and give the Function App a managed identity that may read it. Refer to it from an app setting, for example `WB_PRIVATE_KEY=@Microsoft.KeyVault(SecretUri=…)`, beside `WB_CLIENT_ID`, `WB_KID` and `WB_TOKEN_URL`.
2. Create an HTTP-triggered **Azure Function** in Python that returns the assertion. Its body is the `client_assertion()` function of the Python recipe, reading the key from `WB_PRIVATE_KEY` instead of a file. Keep the function's authorization level at *Function*.
3. In the **Logic App**:
   1. An *Azure Functions* action calls the function and gets the assertion.
   2. An *HTTP* action posts to the token endpoint with `Content-Type: application/x-www-form-urlencoded` and the body `grant_type=client_credentials&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&client_assertion=@{body('Get_assertion')}`.
   3. *Parse JSON* reads `access_token`.
   4. The *HTTP* actions that call `/v1` send the header `Authorization: Bearer @{body('Parse_token')?['access_token']}`.

Fetch a new token in each run, or when 15 minutes have passed.

## When the token endpoint refuses

The token endpoint answers OAuth errors, `{ "error": "…", "error_description": "…" }`, with status `400` unless stated otherwise:

| `error` | Common reasons |
|:--------|:---------------|
| `invalid_request` | The body is not a form, or `grant_type` is missing |
| `unsupported_grant_type` | `grant_type` is not `client_credentials` |
| `invalid_client` | The assertion is malformed, signed with another key or algorithm, expired, issued in the future, valid for more than 300 seconds, or already used; `iss` and `sub` are not the `client_id`; the `kid` is unknown or removed; the integration is disabled or revoked; or the API is off for the organisation. `error_description` says which |
| `invalid_scope` | `scope` names a permission the integration does not hold |
| `temporarily_unavailable` | `429`: more than 30 token requests a minute for the integration, or 60 from one address. `503`: the service is starting. Wait for `Retry-After` |

More on [Errors and limits](/en/integrations/errors-and-limits/).
