# Authentication

> Get a short-lived token with your OAuth library and your integration's private key, and call the API with it.

Your backend proves who it is with a key, not a password:

1. **You hold a private key**, and YOU(th) holds only its public half. There is no client secret.
2. **Your code uses the key to prove who it is**, and gets a token that is valid for a few minutes.
3. **You send the token** with each call to the API.
4. **Your OAuth library does the signing.** You give it four values from your credentials file.

This is standard OAuth2: the client-credentials grant, with the client authentication that OAuth2
names `private_key_jwt` (RFC 7523). No person or browser is involved.

## What you need

An integration, which your organization's administrators create in the console: see
[Get API credentials](/docs/credentials). Its credentials file holds four values. Keep them on your
server; the samples on this page read three of them from variables:

| Value           | In the samples      | Is                                                                          |
| --------------- | ------------------- | --------------------------------------------------------------------------- |
| The token URL   | `TOKEN_URL`         | `https://auth.youth-platform.io/realms/youth/protocol/openid-connect/token` |
| The client id   | `YOUTH_CLIENT_ID`   | Your integration's id                                                       |
| The key id      | `YOUTH_KEY_ID`      | The id of the key you sign with                                             |
| The private key | `YOUTH_PRIVATE_KEY` | The key itself, as PEM text (PKCS 8)                                        |

## Get a token

Use your language's OAuth2 library, and set it up with these settings, under the names most
libraries give them:

| Setting               | Value                                                                         |
| --------------------- | ----------------------------------------------------------------------------- |
| Grant type            | `client_credentials`                                                          |
| Client authentication | `private_key_jwt`                                                             |
| Token endpoint        | The token URL                                                                 |
| Client id             | The client id                                                                 |
| Signing key           | The private key, with the key id as its `kid`                                 |
| Signing algorithm     | Your key's: `ES256`, or `RS256`                                               |
| Scope                 | The scopes you want, of those your integration was given, separated by spaces |
| Assertion audience    | The token URL or the issuer: whichever your library sends                     |

**Always send `scope`.** A token asked for without one is refused by every route of the API, with
`401` and `invalid_token`.

A library that supports OpenID Connect discovery needs only the issuer,
`https://auth.youth-platform.io/realms/youth`, and reads the token URL from its metadata. The
issuer is the token URL without `/protocol/openid-connect/token`.

The answer holds the token and how many seconds it lasts:

```json
{ "access_token": "eyJhbGciOiJSUzI1NiIs…", "expires_in": 300, "token_type": "Bearer" }
```

### Node: openid-client

With [openid-client](https://github.com/panva/openid-client) (`npm install openid-client`):

```typescript
import { createPrivateKey } from "node:crypto";
import * as client from "openid-client";

const ISSUER = "https://auth.youth-platform.io/realms/youth";

const key = await crypto.subtle.importKey(
  "pkcs8",
  createPrivateKey(process.env.YOUTH_PRIVATE_KEY ?? "").export({ type: "pkcs8", format: "der" }),
  { name: "ECDSA", namedCurve: "P-256" },
  false,
  ["sign"],
);
// Discovery reads the token URL from the issuer's metadata.
const config = await client.discovery(
  new URL(ISSUER),
  process.env.YOUTH_CLIENT_ID ?? "",
  undefined,
  client.PrivateKeyJwt({ key, kid: process.env.YOUTH_KEY_ID ?? "" }),
);

const tokens = await client.clientCredentialsGrant(config, {
  scope: "access_codes:read access_codes:write",
});
// tokens.access_token, valid for tokens.expires_in seconds
```

### Python: Authlib

With [Authlib](https://docs.authlib.org) and Requests (`pip install authlib requests`). The session
gets a token, sends it with each request, and gets a new one when it has expired:

```python
import os

from authlib.integrations.requests_client import OAuth2Session
from authlib.oauth2.rfc7523 import PrivateKeyJWT
from joserfc.jwk import ECKey

TOKEN_URL = "https://auth.youth-platform.io/realms/youth/protocol/openid-connect/token"

session = OAuth2Session(
    os.environ["YOUTH_CLIENT_ID"],
    ECKey.import_key(os.environ["YOUTH_PRIVATE_KEY"]),
    token_endpoint_auth_method=PrivateKeyJWT(
        TOKEN_URL, headers={"kid": os.environ["YOUTH_KEY_ID"]}, alg="ES256"
    ),
    token_endpoint=TOKEN_URL,
    grant_type="client_credentials",
    scope="access_codes:read access_codes:write",
)
session.fetch_token()

response = session.get("https://api.youth-platform.io/v1/organization")
response.raise_for_status()
```

### Java: Nimbus

With the [Nimbus OAuth 2.0 SDK](https://connect2id.com/products/nimbus-oauth-openid-connect-sdk)
(`com.nimbusds:oauth2-oidc-sdk`):

```java
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.oauth2.sdk.ClientCredentialsGrant;
import com.nimbusds.oauth2.sdk.Scope;
import com.nimbusds.oauth2.sdk.TokenRequest;
import com.nimbusds.oauth2.sdk.TokenResponse;
import com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT;
import com.nimbusds.oauth2.sdk.id.ClientID;
import java.net.URI;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class Token {
  public static void main(String[] args) throws Exception {
    URI tokenUrl =
        URI.create("https://auth.youth-platform.io/realms/youth/protocol/openid-connect/token");
    String pem = System.getenv("YOUTH_PRIVATE_KEY").replaceAll("-----[A-Z ]+-----|\\s", "");
    PrivateKey key = KeyFactory.getInstance("EC")
        .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pem)));

    PrivateKeyJWT assertion = new PrivateKeyJWT(
        new ClientID(System.getenv("YOUTH_CLIENT_ID")), tokenUrl,
        JWSAlgorithm.ES256, key, System.getenv("YOUTH_KEY_ID"), null);
    TokenRequest request = new TokenRequest(
        tokenUrl, assertion, new ClientCredentialsGrant(),
        new Scope("access_codes:read", "access_codes:write"));
    TokenResponse response = TokenResponse.parse(request.toHTTPRequest().send());
    if (!response.indicatesSuccess()) {
      throw new IllegalStateException(response.toErrorResponse().getErrorObject().toString());
    }
    String token = response.toSuccessResponse().getTokens().getAccessToken().getValue();
  }
}
```

## Call the API with it

Send the token in the `Authorization` header of every request:

```bash
curl https://api.youth-platform.io/v1/organization \
  --header "Authorization: Bearer $YOUTH_ACCESS_TOKEN"
```

[`GET /v1/organization`](/docs/credentials#check-your-credentials) answers your organization and
your integration, whatever the token's scopes: call it first, to check new credentials. The `curl`
examples on the other pages send the token the same way, as `$YOUTH_ACCESS_TOKEN`.

A token lasts about five minutes. Reuse it until shortly before it expires, then get a new one; do
not get a token for every request.

## Without a library

If your stack has no library for `private_key_jwt`, this is what one sends. For every token
request, sign a new JWT, the client assertion. Its header names the key:

| Header | Holds                                    |
| ------ | ---------------------------------------- |
| `alg`  | The key's algorithm: `ES256`, or `RS256` |
| `kid`  | The key id                               |
| `typ`  | `JWT`                                    |

Its claims say who asks, whom, and for how long:

| Claim        | Holds                                                           |
| ------------ | --------------------------------------------------------------- |
| `iss`, `sub` | Your client id, in both                                         |
| `aud`        | The token URL, or the issuer                                    |
| `jti`        | An id of its own, such as a UUID: an assertion is accepted once |
| `iat`        | Now, in Unix seconds                                            |
| `exp`        | When it expires: one minute from now is enough                  |

Send it to the token URL, as a form:

| Field                   | Holds                                                    |
| ----------------------- | -------------------------------------------------------- |
| `grant_type`            | `client_credentials`                                     |
| `scope`                 | The scopes you want, of those your integration was given |
| `client_assertion_type` | `urn:ietf:params:oauth:client-assertion-type:jwt-bearer` |
| `client_assertion`      | The assertion you signed                                 |

The two samples sign with an `ES256` key. For an `RS256` key, change the algorithm they name and
sign with.

### In TypeScript

With Node's own `crypto`:

```typescript
import { createPrivateKey, randomUUID, sign } from "node:crypto";

const TOKEN_URL = "https://auth.youth-platform.io/realms/youth/protocol/openid-connect/token";
// The scopes this system needs, of those your integration was given.
const SCOPE = "access_codes:read access_codes:write";

const base64url = (value: object) => Buffer.from(JSON.stringify(value)).toString("base64url");

/** A JWT signed with your private key, which proves one token request is yours. */
function clientAssertion(now: number): string {
  const clientId = process.env.YOUTH_CLIENT_ID ?? "";
  const issuedAt = Math.floor(now / 1000);
  const header = { alg: "ES256", kid: process.env.YOUTH_KEY_ID ?? "", typ: "JWT" };
  const claims = {
    iss: clientId,
    sub: clientId,
    aud: TOKEN_URL,
    jti: randomUUID(),
    iat: issuedAt,
    exp: issuedAt + 60,
  };
  const signed = `${base64url(header)}.${base64url(claims)}`;
  // A JWT's ES256 signature is the two numbers side by side, not the DER that `sign` defaults to.
  const signature = sign("sha256", Buffer.from(signed), {
    key: createPrivateKey(process.env.YOUTH_PRIVATE_KEY ?? ""),
    dsaEncoding: "ieee-p1363",
  });
  return `${signed}.${signature.toString("base64url")}`;
}

let cached: { token: string; expiresAt: number } | undefined;

/** A token for the API, reused until a minute before it expires. */
export async function accessToken(now = Date.now()): Promise<string> {
  if (cached && now < cached.expiresAt) return cached.token;
  const response = await fetch(TOKEN_URL, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "client_credentials",
      scope: SCOPE,
      client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      client_assertion: clientAssertion(now),
    }),
  });
  if (!response.ok) throw new Error(`The token was refused: ${response.status}`);
  const answer: { access_token: string; expires_in: number } = await response.json();
  cached = { token: answer.access_token, expiresAt: now + (answer.expires_in - 60) * 1000 };
  return cached.token;
}
```

### In Python

With [PyJWT](https://pyjwt.readthedocs.io) and [Requests](https://requests.readthedocs.io)
(`pip install "pyjwt[crypto]" requests`):

```python
import os
import time
import uuid

import jwt
import requests

TOKEN_URL = "https://auth.youth-platform.io/realms/youth/protocol/openid-connect/token"


def access_token(scope: str) -> str:
    """A new token for the API. Keep it, and reuse it until shortly before it expires."""
    client_id = os.environ["YOUTH_CLIENT_ID"]
    now = int(time.time())
    assertion = jwt.encode(
        {
            "iss": client_id,
            "sub": client_id,
            "aud": TOKEN_URL,
            "jti": str(uuid.uuid4()),
            "iat": now,
            "exp": now + 60,
        },
        os.environ["YOUTH_PRIVATE_KEY"],
        algorithm="ES256",
        headers={"kid": os.environ["YOUTH_KEY_ID"]},
    )
    response = requests.post(
        TOKEN_URL,
        data={
            "grant_type": "client_credentials",
            "scope": scope,
            "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
            "client_assertion": assertion,
        },
        timeout=10,
    )
    response.raise_for_status()
    return response.json()["access_token"]


token = access_token("access_codes:read access_codes:write")
response = requests.get(
    "https://api.youth-platform.io/v1/organization",
    headers={"Authorization": f"Bearer {token}"},
    timeout=10,
)
response.raise_for_status()
```

## When the token request is refused

The token URL answers `400` or `401` with an OAuth2 error, and says more in `error_description`:

| `error`          | `error_description`              | Means                                                                                |
| ---------------- | -------------------------------- | ------------------------------------------------------------------------------------ |
| `invalid_client` | `Invalid token audience`         | The assertion's audience is neither the token URL nor the issuer, exactly as written |
| `invalid_client` | `Token is not active`            | The assertion has expired: check your server's clock                                 |
| `invalid_client` | `Token reuse detected`           | The same assertion came twice: every token request needs a new one                   |
| `invalid_client` | `Unable to load public key`      | The key id names no key of this integration, or the key was removed                  |
| `invalid_client` | `Invalid signature algorithm`    | The signing algorithm is not that of the key YOU(th) holds                           |
| `invalid_client` | It names the signature           | The assertion was signed with another private key                                    |
| `invalid_client` | It names `client_assertion_type` | The request sent no assertion, or a client secret in its place                       |
| `invalid_scope`  | It names the scopes              | `scope` asks for one your integration was not given                                  |

## When the API refuses a token

| Answer | `code`                | Means                                                                 |
| ------ | --------------------- | --------------------------------------------------------------------- |
| `401`  | `invalid_token`       | No token, an expired or unknown one, or one asked for without `scope` |
| `401`  | `integration_revoked` | The integration was revoked, even if the token has not expired yet    |
| `403`  | `insufficient_scope`  | The token is valid, but lacks the route's scope                       |

A `401` carries a `WWW-Authenticate: Bearer` header: alone when the request had no token, and with
`error="invalid_token"` when its token did not hold. Every refusal has the body
[Errors and rate limits](/docs/errors) describes.

Your integration belongs to one organization, and the API answers only that organization's data:
see [Your organization](/docs/concepts#your-organization). No route takes an organization in its
address or its body.

## Keep the key safe

- Keep the private key on your server, in its secret store: never in an app, a browser or a
  repository.
- Never log the key, an assertion or a token.
- Replace a key that is lost or may have leaked: [add a new key](/docs/credentials#replace-a-key)
  to the same integration, move your servers to it, then remove the old one. Nothing stops in
  between.
- [Revoke an integration](/docs/credentials#revoke-an-integration) you no longer use. The API
  refuses it from the next request.
