Docs
Contact

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. Its credentials file holds four values. Keep them on your server; the samples on this page read three of them from variables:

ValueIn the samplesIs
The token URLTOKEN_URLhttps://auth.youth-platform.io/realms/youth/protocol/openid-connect/token
The client idYOUTH_CLIENT_IDYour integration's id
The key idYOUTH_KEY_IDThe id of the key you sign with
The private keyYOUTH_PRIVATE_KEYThe 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:

SettingValue
Grant typeclient_credentials
Client authenticationprivate_key_jwt
Token endpointThe token URL
Client idThe client id
Signing keyThe private key, with the key id as its kid
Signing algorithmYour key's: ES256, or RS256
ScopeThe scopes you want, of those your integration was given, separated by spaces
Assertion audienceThe 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:

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

Node: openid-client

With openid-client (npm install openid-client):

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 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:

import osfrom authlib.integrations.requests_client import OAuth2Sessionfrom authlib.oauth2.rfc7523 import PrivateKeyJWTfrom joserfc.jwk import ECKeyTOKEN_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 (com.nimbusds:oauth2-oidc-sdk):

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:

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

GET /v1/organization 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:

HeaderHolds
algThe key's algorithm: ES256, or RS256
kidThe key id
typJWT

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

ClaimHolds
iss, subYour client id, in both
audThe token URL, or the issuer
jtiAn id of its own, such as a UUID: an assertion is accepted once
iatNow, in Unix seconds
expWhen it expires: one minute from now is enough

Send it to the token URL, as a form:

FieldHolds
grant_typeclient_credentials
scopeThe scopes you want, of those your integration was given
client_assertion_typeurn:ietf:params:oauth:client-assertion-type:jwt-bearer
client_assertionThe 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:

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 and Requests (pip install "pyjwt[crypto]" requests):

import osimport timeimport uuidimport jwtimport requestsTOKEN_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:

errorerror_descriptionMeans
invalid_clientInvalid token audienceThe assertion's audience is neither the token URL nor the issuer, exactly as written
invalid_clientToken is not activeThe assertion has expired: check your server's clock
invalid_clientToken reuse detectedThe same assertion came twice: every token request needs a new one
invalid_clientUnable to load public keyThe key id names no key of this integration, or the key was removed
invalid_clientInvalid signature algorithmThe signing algorithm is not that of the key YOU(th) holds
invalid_clientIt names the signatureThe assertion was signed with another private key
invalid_clientIt names client_assertion_typeThe request sent no assertion, or a client secret in its place
invalid_scopeIt names the scopesscope asks for one your integration was not given

When the API refuses a token

AnswercodeMeans
401invalid_tokenNo token, an expired or unknown one, or one asked for without scope
401integration_revokedThe integration was revoked, even if the token has not expired yet
403insufficient_scopeThe 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 describes.

Your integration belongs to one organization, and the API answers only that organization's data: see 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 to the same integration, move your servers to it, then remove the old one. Nothing stops in between.
  • Revoke an integration you no longer use. The API refuses it from the next request.

Last updated