Skip to content

M5-S2 — OAuth: sign-in for programs, anonymous visitors, and the life of a token

Section titled “M5-S2 — OAuth: sign-in for programs, anonymous visitors, and the life of a token”
ModuleM5 — The API and an external client
After this session you canGive every caller the right credential, sign a person in from your own program, and keep a session alive without surprises.
TimeFacilitated: 51 min · On your own: 51 min
Before you startM5-S1: BASE set in your terminal. From your enrolment message: the course’s test client id and its redirect address http://127.0.0.1:8765/callback, and the id of the public view Available jobs. Hala Mansour’s sign-in details.
Go deeperAuthentication & OAuth · Choosing a credential · Token lifecycle

◆ Orientation (1 min) — Not every caller is a machine

Section titled “◆ Orientation (1 min) — Not every caller is a machine”

The careers site’s server reads jobs with the API token you issued. But its visitors are anonymous people, HR’s wall screen (R-12) belongs to a signed-in person, and the agency may one day build a recruiter app that people sign into. Each is a different kind of caller, and each needs a different credential. This session gives you the second credential, OAuth, and the decision that says which to use.

▤ Concept (6 min) — The credential decision and the OAuth flows

Section titled “▤ Concept (6 min) — The credential decision and the OAuth flows”
The callerCredentialBecause
A person in your web or mobile appAuthorization code with PKCEThe platform’s sign-in page handles passwords, second factors and external providers; the person’s own access applies
A program of yours acting as itself, no person presentAPI token of its own application userNo exchange and no refresh; one identity, narrowed on the user
Another company’s product acting for your usersAuthorization code with each user’s consentEach person authorizes it; one person revoking does not affect others
A visitor who is not signed in, on a public pageAnonymous tokenNo secret in the browser; reaches only what is open to visitors
A trusted first-party script that must hold a person’s passwordPassword grant, reluctantlyIt bypasses second factors and ties the job to a person’s account

Why not client credentials? The machine-to-machine grant exists, but its token identifies a client, not a user. The platform authorizes users, so such a token authenticates and then reaches almost nothing. For a program acting as itself, use an API token.

Every tenant has its own OpenID provider. Its public configuration is at /api/identity/v1/tenant-config on the tenant’s host, and names the authority; the authority’s /.well-known/openid-configuration lists every endpoint. Take endpoints from there, never hard-code them. There is no self-service client registration: an operator registers your client with its exact redirect addresses (one wildcard subdomain at most). Your course sandbox has a public test client registered for http://127.0.0.1:8765/callback.

sequenceDiagram
  participant P as Your program
  participant B as Browser
  participant A as Sign-in provider
  P->>P: make a secret verifier and its SHA-256 challenge
  P->>B: open the authorization address (client id, redirect, scopes, state, challenge)
  B->>A: the person signs in
  A-->>B: redirect to your address with ?code and ?state
  B-->>P: code, state
  P->>A: exchange code + verifier at the token endpoint
  A-->>P: access token (1 h), refresh token, id token

What to notice: the code is useless without the verifier, which never left your program; that is what makes the flow safe for a public client that cannot keep a secret.

Check that state matches what you sent. The code is valid for 10 minutes. If the person selects Cancel, your address receives error=access_denied: treat it as “declined”, not as a failure.

Scopes release claims, permissions decide data

Section titled “Scopes release claims, permissions decide data”

openid releases the user’s id (sub), email and profile their email and user name, and offline_access a refresh token. Scopes do not narrow what the person can reach: the person’s own permissions decide that, exactly as in the portal. The one scope that does limit data is the anonymous token’s anonymous scope, which reaches only what the tenant opens to visitors.

TokenLivesWhen it ends early
Access token1 hourRefresh it; on 401, refresh once and retry once
Refresh token14 days, renewable up to a yearIt rotates: always keep the newest one you received
Anonymous token10 minutesFetch another
API tokenUntil its expiry date, or for everDeactivating or archiving its application user stops it

Rotating an API token without downtime: an administrator selects Regenerate Token; the new token is emailed to that administrator, and the old and new tokens both work for 24 hours by default, so you deploy the new one within that window. Design programs to read tokens from configuration so a rotation is a configuration change, not a release.

Revocation is not instant: the gateway remembers a successful check for about five minutes, so a revoked token can keep working that long. When a token leaks, revoke first, then watch for calls that still succeed in that window.

▶ Guided demo (8 min) — The provider, and an anonymous visitor’s token

Section titled “▶ Guided demo (8 min) — The provider, and an anonymous visitor’s token”
  1. Read the tenant’s public configuration: curl -s "$BASE/api/identity/v1/tenant-config" | jq. It names the authority and the portal’s own client.

  2. Read the discovery document: curl -s "<authority>/.well-known/openid-configuration" | jq '{authorization_endpoint, token_endpoint, userinfo_endpoint}'.

  3. Get an anonymous token: export ANON=$(curl -s -X POST "$BASE/api/identity/v1/anonymous/token" | jq -r .access_token). It lives 10 minutes and carries only the anonymous scope.

  4. Read the public view Available jobs with it (set PUBLIC to its id):

    Terminal window
    curl -s -G "$BASE/api/v1/v/$PUBLIC/v3/entities/jobs/entries" \
    -H "Authorization: Bearer $ANON" --data-urlencode 'filterCriteria={"limit":10}' \
    | jq '[.entries[].value.job_title.en]'
  5. Try Careers feed with the same token: refused. It is open to Careers Site only.

Screenshot pending A terminal showing the anonymous token request and the two open job titles read through the public Available jobs view What to notice: no secret was needed; a browser can do exactly this, which is why a public page never carries a client secret.

⛏ Lab (27 min) — Sign in from your own program

Section titled “⛏ Lab (27 min) — Sign in from your own program”

Goal. A small program that signs Hala Mansour in through the platform’s sign-in page, receives her tokens, says who she is, calls the API as her, and refreshes the session.

Before you start. BASE and the test client id: export CLIENT_ID="<test client id>".

  1. Create pkce-login.mjs:

    import http from 'node:http';
    import crypto from 'node:crypto';
    import fs from 'node:fs';
    const { BASE, CLIENT_ID } = process.env;
    const REDIRECT_URI = 'http://127.0.0.1:8765/callback';
    const cfg = await (await fetch(`${BASE}/api/identity/v1/tenant-config`)).json();
    const disco = await (await fetch(`${cfg.authority}/.well-known/openid-configuration`)).json();
    const verifier = crypto.randomBytes(32).toString('base64url');
    const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
    const state = crypto.randomBytes(16).toString('hex');
    const auth = new URL(disco.authorization_endpoint);
    auth.search = new URLSearchParams({
    client_id: CLIENT_ID, response_type: 'code', redirect_uri: REDIRECT_URI,
    scope: 'openid email profile offline_access', state,
    code_challenge: challenge, code_challenge_method: 'S256',
    });
    console.log(`Open this address and sign in:\n${auth}\n`);
    const code = await new Promise((resolve, reject) => {
    const server = http.createServer((req, res) => {
    const u = new URL(req.url, REDIRECT_URI);
    if (u.pathname !== '/callback') { res.end(); return; }
    res.end('Signed in. You can close this tab.');
    server.close();
    if (u.searchParams.get('error')) return reject(new Error(u.searchParams.get('error')));
    if (u.searchParams.get('state') !== state) return reject(new Error('state mismatch'));
    resolve(u.searchParams.get('code'));
    }).listen(8765, '127.0.0.1');
    });
    const res = await fetch(disco.token_endpoint, {
    method: 'POST',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
    grant_type: 'authorization_code', code, redirect_uri: REDIRECT_URI,
    client_id: CLIENT_ID, code_verifier: verifier,
    }),
    });
    const tokens = await res.json();
    if (!res.ok) throw new Error(JSON.stringify(tokens));
    fs.writeFileSync('.tokens.json', JSON.stringify({ ...tokens, token_endpoint: disco.token_endpoint }));
    const me = await (await fetch(disco.userinfo_endpoint, {
    headers: { authorization: `Bearer ${tokens.access_token}` },
    })).json();
    console.log('Signed in as', me.preferred_username ?? me.email, '| expires in', tokens.expires_in, 's',
    '| refresh token:', Boolean(tokens.refresh_token));
  2. Run node pkce-login.mjs. Open the printed address in a private browser window and sign in as Hala Mansour. The tab says Signed in; the terminal prints her user name, 3600 seconds and refresh token: true.

  3. Call the API as Hala, through the view she can open, HR worklist:

    Terminal window
    export ACCESS=$(jq -r .access_token .tokens.json)
    export WORKLIST="<HR worklist view id>"
    curl -s -G "$BASE/api/v1/v/$WORKLIST/v3/entities/hr_worklist/entries" \
    -H "Authorization: Bearer $ACCESS" --data-urlencode 'filterCriteria={"limit":20}' \
    | jq '.entries | length'

    It prints the number of worklist items, because Hala is in HR.

  4. Run the flow again and select Cancel on the sign-in page: your program prints access_denied. That is the person declining, not a bug.

  5. Your part. Write refresh.mjs, which reads .tokens.json, asks the token endpoint for a new access token with grant_type=refresh_token, and writes the answer back, keeping the new refresh token if one is returned. Run it and check that .tokens.json now holds a different access token.

  6. Add .tokens.json to your .gitignore. Tokens never go into source control.

Check.

  • The program printed Hala’s user name, a 3600-second lifetime and a refresh token.
  • Your call through HR worklist with her access token returned her worklist items.
  • Cancelling produced access_denied, handled as a decline.
  • refresh.mjs replaced the access token and kept the newest refresh token.
  • .tokens.json is ignored by source control.

Pass condition. Your own program signs a person in with PKCE, calls the API as that person, and renews the session without asking them to sign in again.

If something goes wrong

What you seeWhat to do
The sign-in page says the redirect address is invalidThe redirect must match the registered one exactly: http://127.0.0.1:8765/callback, not localhost.
state mismatchYou opened an address from an earlier run. Start the program again and use the new address.
The token exchange answers invalid_grantThe code expired (10 minutes) or was used twice, or the verifier is not the one the challenge came from. Run again.
The API answers 401The access token expired: run refresh.mjs, then retry once.
EADDRINUSEAn earlier run still listens on port 8765: stop it.
Model answer

refresh.mjs in full:

import fs from 'node:fs';
const { CLIENT_ID } = process.env;
const saved = JSON.parse(fs.readFileSync('.tokens.json', 'utf8'));
const res = await fetch(saved.token_endpoint, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: saved.refresh_token, client_id: CLIENT_ID }),
});
const fresh = await res.json();
if (!res.ok) throw new Error(JSON.stringify(fresh));
// Refresh tokens rotate: keep the newest one, or the next refresh may fail.
fs.writeFileSync('.tokens.json', JSON.stringify({
...saved, ...fresh, refresh_token: fresh.refresh_token ?? saved.refresh_token,
}));
console.log('new access token, expires in', fresh.expires_in, 's');

The flow is safe without a client secret because the code is bound to the verifier your program generated; state ties the answer to your request. Hala’s call works because she can open HR worklist: the token says who she is, and her permissions say what she may read.

◇ Worked scenario (2 min) — Four callers, four credentials

Section titled “◇ Worked scenario (2 min) — Four callers, four credentials”

Decide each before reading on.

1. HR’s wall screen shows applications moving, live (R-12). It must open a live connection, which an API token cannot do (M6). Decision: a dedicated kiosk account with HR’s view access, signed in once with the authorization code flow; the screen’s program refreshes its session, which lasts at most a year before someone signs in again.

2. The careers site’s public pages list jobs to visitors. Decision: in the visitor’s browser, an anonymous token, fetched fresh every ten minutes; no secret ships to the browser. The site’s server, which submits applications, keeps its API token.

3. A business-intelligence tool shows recruitment figures to each manager. Two managers must see only their own departments’ data. Decision: each manager’s own OAuth token, passed through by the tool, so each request runs as the person looking; a shared token would show everyone the same data.

4. The payroll system’s nightly job reads new hires. Decision: an API token for a Payroll application user, one per environment, with access to one view. Not client credentials: its token would name no user and reach nothing.

✓ Practice (6 min) — Check your credentials

Section titled “✓ Practice (6 min) — Check your credentials”
PracticeChoose one answer.

A partner’s server fetches a client-credentials token, calls the entries list, and always gets nothing back. Its developer asks what is wrong with the platform.

  1. Explanation for A

    ✗ Incorrect

    Not this one: a bearer token travels in the Authorization header; the header is not the problem. See the credential decision.

  2. Explanation for B

    ✓ Correct

    Correct: the platform authorizes users, so a client-credentials token authenticates and then sees nothing. Use an API token. See the credential decision.

  3. Explanation for C

    ✗ Incorrect

    Not this one: they live ten minutes; the empty answer comes from having no user behind them. See the life of a token.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A recruiter app asks for the scopes openid email profile offline_access. A product manager asks whether that limits the app to profile data. What is the answer?

  1. Explanation for A

    ✗ Incorrect

    Not this one: scopes release claims about the person; they do not narrow what data the person can reach. See scopes release claims.

  2. Explanation for B

    ✓ Correct

    Correct: the token acts as the person, with their access, as in the portal. See scopes release claims.

  3. Explanation for C

    ✗ Incorrect

    Not this one: offline_access only adds a refresh token. See scopes release claims.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A program refreshes its session daily and saves only the access token. After a few days, refresh fails. Why?

  1. Explanation for A

    ✓ Correct

    Correct: a refresh can return a new refresh token, and the old one may stop working. See the life of a token.

  2. Explanation for B

    ✗ Incorrect

    Not this one: there is no such limit; the program must keep the newest refresh token. See the life of a token.

  3. Explanation for C

    ✗ Incorrect

    Not this one: a refresh sends the refresh token, not the access token. See the life of a token.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

An API token leaked on a public site at 10:00. At 10:01 the administrator archives its application user. Calls with the token still succeed at 10:03. What is happening?

  1. Explanation for A

    ✗ Incorrect

    Not this one: archiving the application user does stop it. See the life of a token.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the 24-hour overlap is for a regenerated token, not a revoked one. See the life of a token.

  3. Explanation for C

    ✓ Correct

    Correct: revocation reaches every request within that short window, so watch for calls until it passes. See the life of a token.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

A single-page careers site needs to show jobs to visitors and must not ship a secret. What does its browser code use?

  1. Explanation for A

    ✗ Incorrect

    Not this one: anything in a page is public, so the token would leak at once. See the credential decision.

  2. Explanation for B

    ✓ Correct

    Correct: it needs no secret, lives ten minutes and reaches only what visitors may see. See the guided demo.

  3. Explanation for C

    ✗ Incorrect

    Not this one: it puts a password in public code and bypasses second factors. See the credential decision.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

↺ Recap (1 min) — The right key for every caller

Section titled “↺ Recap (1 min) — The right key for every caller”

You can choose a credential for every kind of caller, sign a person in from your own program with PKCE, read public data with an anonymous token, and plan for expiry, rotation, revocation and refresh.

Next. In M5-S3 you put it together: the careers client that reads, writes an application with its CV, survives errors and moves between environments.