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”| Module | M5 — The API and an external client |
| After this session you can | Give every caller the right credential, sign a person in from your own program, and keep a session alive without surprises. |
| Time | Facilitated: 51 min · On your own: 51 min |
| Before you start | M5-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 deeper | Authentication & 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”Which credential for which caller
Section titled “Which credential for which caller”| The caller | Credential | Because |
|---|---|---|
| A person in your web or mobile app | Authorization code with PKCE | The 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 present | API token of its own application user | No exchange and no refresh; one identity, narrowed on the user |
| Another company’s product acting for your users | Authorization code with each user’s consent | Each person authorizes it; one person revoking does not affect others |
| A visitor who is not signed in, on a public page | Anonymous token | No secret in the browser; reaches only what is open to visitors |
| A trusted first-party script that must hold a person’s password | Password grant, reluctantly | It 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.
Finding the tenant’s sign-in provider
Section titled “Finding the tenant’s sign-in provider”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.
The authorization code flow with PKCE
Section titled “The authorization code flow with PKCE”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.
The life of a token
Section titled “The life of a token”| Token | Lives | When it ends early |
|---|---|---|
| Access token | 1 hour | Refresh it; on 401, refresh once and retry once |
| Refresh token | 14 days, renewable up to a year | It rotates: always keep the newest one you received |
| Anonymous token | 10 minutes | Fetch another |
| API token | Until its expiry date, or for ever | Deactivating 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”-
Read the tenant’s public configuration:
curl -s "$BASE/api/identity/v1/tenant-config" | jq. It names theauthorityand the portal’s own client. -
Read the discovery document:
curl -s "<authority>/.well-known/openid-configuration" | jq '{authorization_endpoint, token_endpoint, userinfo_endpoint}'. -
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 theanonymousscope. -
Read the public view Available jobs with it (set
PUBLICto 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]' -
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>".
-
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)); -
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 andrefresh token: true. -
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.
-
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. -
Your part. Write
refresh.mjs, which reads.tokens.json, asks the token endpoint for a new access token withgrant_type=refresh_token, and writes the answer back, keeping the new refresh token if one is returned. Run it and check that.tokens.jsonnow holds a different access token. -
Add
.tokens.jsonto 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.mjsreplaced the access token and kept the newest refresh token. -
.tokens.jsonis 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 see | What to do |
|---|---|
| The sign-in page says the redirect address is invalid | The redirect must match the registered one exactly: http://127.0.0.1:8765/callback, not localhost. |
state mismatch | You opened an address from an earlier run. Start the program again and use the new address. |
The token exchange answers invalid_grant | The code expired (10 minutes) or was used twice, or the verifier is not the one the challenge came from. Run again. |
The API answers 401 | The access token expired: run refresh.mjs, then retry once. |
EADDRINUSE | An 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”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.
Check your answer
The correct answer is B. Open the explanation under each option to see why.
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?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A program refreshes its session daily and saves only the access token. After a few days, refresh fails. Why?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
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?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
A single-page careers site needs to show jobs to visitors and must not ship a secret. What does its browser code use?
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.