# Backend Services (Client Credentials)

Use this flow when **no user is present**: a backend system, integration engine, or
scheduled job accessing the API on its own authority (SMART Backend Services). Tokens
are minted directly at the token endpoint with the `client_credentials` grant — there
is no browser redirect and no consent screen.

> For flows where a clinician or patient is present, see
> [App Launch (Authorization Code + PKCE)](/guides/app-launch-pkce) instead.

## The four steps

1. **Register** (out of band). Innowell issues you a `client_id`, grants your
   `system/*` scopes, and binds the client to your tenant. Choose a client
   authentication method:
   - **`private_key_jwt`** (recommended, per the SMART
     [client-confidential-asymmetric](https://hl7.org/fhir/smart-app-launch/client-confidential-asymmetric.html)
     spec): register your public keys (JWKS or a `jwks_uri`); no shared secret ever
     crosses the wire.
   - **Client secret** (`client_secret_post` or `client_secret_basic`): Innowell also
     issues a `client_secret`.
2. **Discover.** `GET /.well-known/smart-configuration` publishes the token endpoint
   and supported scopes.
3. **Mint a token.** `POST /oauth/token` with `grant_type=client_credentials`, your
   `system/*` scopes, a `tenant_id`, and `aud` set to the FHIR base URL.
4. **Call the FHIR API** with the resulting bearer token.

## Flow

```mermaid
sequenceDiagram
    participant System as Your backend system
    participant Auth as Innowell Auth Server
    participant FHIR as FHIR API
    System->>Auth: POST /oauth/token (client_credentials + system/* scopes + tenant_id + aud)
    Auth->>System: access_token (RS256 JWT, 300 s)
    System->>FHIR: GET /fhir/R4/Patient (Authorization: Bearer)
    FHIR->>System: Bundle
```

## Token request rules

- **Scopes must all be `system/*`** and granted to your client; anything else is
  rejected with `invalid_scope`. See [Scopes](/guides/scopes).
- **`tenant_id` is required** whenever a `system/*` scope is requested; omitting it
  returns `invalid_request`.
- A tenant-owned client may only request its **owning tenant**; any other `tenant_id`
  returns `invalid_request`.
- Partner clients are approved per tenant. Requesting a tenant your client has not been
  approved for returns `invalid_grant`.
- **Send `aud` set to the FHIR base URL** of the environment you are calling
  (`https://au.fhir.innowell.org/fhir/R4` in production,
  `https://au.fhir-stg.innowell.dev/fhir/R4` in staging). The FHIR API only accepts
  tokens issued for that audience. Without `aud`, the token is issued for your
  `client_id`, and every FHIR request fails with `401` and an empty body. An `aud` that
  is not a recognised FHIR base URL returns `invalid_request`.

## Token request — client secret (curl)

```bash
curl -X POST "$BASE_URL/oauth/token" \
  -d grant_type=client_credentials \
  -d client_id="$CLIENT_ID" \
  -d client_secret="$CLIENT_SECRET" \
  -d scope="system/Patient.rs system/DocumentReference.cru" \
  -d tenant_id="$TENANT_ID" \
  -d aud="$FHIR_BASE"
```

## Using private_key_jwt, step by step

Instead of a shared secret, you sign each token request with a private key that never
leaves your infrastructure. One-time setup (steps 1–3), then per-request (steps 4–5).

### 1. Generate a key pair

Only `RS384` (RSA, 2048-bit minimum) and `ES384` (EC, P-384 curve) are accepted:

```bash
# RSA (RS384)
openssl genrsa -out private.pem 4096

# or EC P-384 (ES384)
openssl ecparam -name secp384r1 -genkey -noout -out private.pem
```

Keep `private.pem` secret (an HSM or secret manager, not source control). Innowell
never sees it.

### 2. Publish the public key as a JWKS

Convert the **public** key to JWK form and wrap it in a JWK Set. Every key needs a
`kid` (key id) of your choosing — the assertion's header must name it. Most JWT
libraries can export this; for example with Node's [`jose`](https://github.com/panva/jose):

```js
import { exportJWK, importSPKI } from "jose";

const publicJwk = await exportJWK(await importSPKI(publicPem, "RS384"));
const jwks = { keys: [{ ...publicJwk, alg: "RS384", kid: "my-key-2026-01" }] };
```

### 3. Register the keys with Innowell

Two options, agreed at client registration:

- **`jwks_uri` (preferred):** host the JWK Set at a stable HTTPS URL you control
  (e.g. `https://yourapp.example.org/.well-known/jwks.json`) and give Innowell that
  URL. Innowell re-fetches it (honouring your `Cache-Control` header, capped at
  4 hours), so **key rotation needs no coordination**: publish the new key alongside
  the old, switch signing, then retire the old key.
- **Inline JWKS (discouraged):** supply the JWK Set document itself if you cannot
  host one. Rotating keys then means contacting Innowell each time.

### 4. Build and sign the assertion (per request)

Each token request carries a fresh, short-lived signed JWT:

```json
// header
{ "alg": "RS384", "typ": "JWT", "kid": "my-key-2026-01" }
// payload
{
  "iss": "<your client_id>",
  "sub": "<your client_id>",
  "aud": "https://au.platform.innowell.org/oauth/token",
  "exp": 1893456180,
  "jti": "8b2f6f9e-…-unique-per-request"
}
```

For example, with Node's `jose`:

```js
import { SignJWT, importPKCS8 } from "jose";
import { randomUUID } from "node:crypto";

const key = await importPKCS8(privatePem, "RS384");
const assertion = await new SignJWT({})
  .setProtectedHeader({ alg: "RS384", typ: "JWT", kid: "my-key-2026-01" })
  .setIssuer(clientId)
  .setSubject(clientId)
  .setAudience(`${baseUrl}/oauth/token`)
  .setExpirationTime("4m")
  .setJti(randomUUID())
  .sign(key);
```

The assertion is verified strictly; it must satisfy **all** of the following or the
request fails with `invalid_client`:

| Assertion field | Requirement |
|---|---|
| `alg` (header) | `RS384` or `ES384` — RS256/ES256 are **not** accepted |
| `kid` (header) | Present, and matching a registered key of the right type |
| `jku` (header, optional) | If present, must equal your registered `jwks_uri` |
| `iss` / `sub` | Both equal your `client_id` |
| `aud` | The token endpoint URL of the environment you are calling — staging and production differ. This is the assertion's own audience, not the `aud` form field you send with the token request (the FHIR base URL) |
| `exp` | In the future, and no more than **5 minutes** ahead |
| `jti` | Unique — each assertion is single-use; replays are rejected |

Because `jti` is single-use and `exp` is capped at 5 minutes, **generate a new
assertion for every token request** — never reuse or pre-mint them.

### 5. Request the token

Send the assertion in place of a secret:

```bash
curl -X POST "$BASE_URL/oauth/token" \
  -d grant_type=client_credentials \
  -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
  -d client_assertion="$SIGNED_JWT" \
  -d scope="system/Patient.rs" \
  -d tenant_id="$TENANT_ID" \
  -d aud="$FHIR_BASE"
```

## What you get back

System tokens are deliberately short-lived and non-refreshable:

```json
{
  "access_token": "<JWT>",
  "token_type": "Bearer",
  "expires_in": 300,
  "scope": "system/Patient.rs system/Practitioner.rs"
}
```

- An RS256 JWT with `expires_in` of **300 seconds**. Reuse it until shortly before it
  expires, then mint a new one; do not mint a token per request.
- **No `refresh_token`** — repeat the client_credentials request when the token
  expires. Refresh tokens stand in for an absent user; with no user in this flow,
  your key or secret already lets you mint a token at any time, and a refresh token
  would only be a second long-lived credential to protect. (Refresh tokens are
  available in [App Launch](/guides/app-launch-pkce) via the `offline_access` scope.)
- Claims: `sub` is `<client_id>:<tenant_id>`, `aud` is the FHIR base URL you sent
  (your `client_id` if you sent none), plus the `tenant_id` claim. No user claims
  (`fhirUser`, `role_type`) are present, since no user is involved.
- All access is confined to the token's tenant — see
  [Scopes → Multi-tenant narrowing](/guides/scopes).

## Try it in Postman

Download the [Backend Services Postman collection](/postman/innowell-backend-services.postman_collection.json)
and the [staging environment](/postman/innowell-staging.postman_environment.json), import
both, and fill in `client_id`, `client_secret` and `tenant_id` in the environment. The
collection fetches a token (with `aud` set) before any request that needs one and reuses it
until shortly before it expires. Run **Search patients** and **Search practitioners** first;
they fill in the sample ids and names the other requests use. The collection covers
Patient and Practitioner reads and searches; add requests for any other resource types your
client is granted.

## Calling the FHIR API

Send the token as a bearer token. Searches return a FHIR `Bundle`; set the page size
with `_count` and follow the `link` whose `relation` is `next` until there is none.

```bash
curl "$FHIR_BASE/Patient?_count=50" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Accept: application/fhir+json"
```

Your scopes are enforced on every request: a resource type you have no scope for, or a
write with read-only (`.rs`) scopes, returns `403`. See the
[FHIR reference](/guides/fhir-reference) for the resources and search parameters.

## Errors

At the token endpoint:

| Error | Cause |
|---|---|
| `invalid_scope` | A non-`system/*` scope, or a scope not granted to your client |
| `invalid_request` | `system/*` scope without `tenant_id`, a `tenant_id` your client does not own, or an `aud` that is not a FHIR base URL |
| `invalid_grant` | Your client is not approved for the requested tenant |
| `invalid_client` | Bad secret, or a client assertion failing any rule above |
| `temporarily_unavailable` (`503`) | Access for your client could not be set up for this tenant just now; retry after a few seconds |
| `429 Too Many Requests` | More than 15 requests/second or 60/minute to `/oauth/token`, `/oauth/introspect`, or `/oauth/revoke` from one IP — slow down and retry |

At the FHIR API:

| Status | Cause |
|---|---|
| `401`, empty body | Token minted without `aud` set to the FHIR base URL, or expired. Mint a new token with `aud` |
| `401`, `OperationOutcome` | No `Authorization` header, or a token this environment does not accept. Mint a new token; contact Innowell if it persists |
| `403` | A resource type outside your scopes, or a write with read-only scopes |
| `404` | No resource with that id in your tenant |
