Introspect and revoke tokens
Ask LumoAuth whether a token is still active, and end a token before it expires.
What it shows
- The backend of an application asks LumoAuth whether a token is active. The answer of an active token holds its scope, its subject and its expiry.
- The backend caches the answer for 30 seconds, so that it does not ask for each request.
- The application revokes the token, for example at sign-out.
- The next introspection says that the token is not active.
Introspection is the only way to check an opaque token. For a JWT, it adds what a check of the signature cannot see: that the token was revoked.
Before you start
- An API key for the setup script, with the scopes
admin:permissions:read,admin:permissions:write,admin:clients:readandadmin:clients:write. - A confidential application. The setup script creates the application "Reports backend", which may request
reports:read.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
CLIENT_ID | The client ID of the application. The setup script prints it. |
CLIENT_SECRET | The secret of the application. The setup script prints it once, when it creates the application. |
LUMOAUTH_API_KEY | Only for the setup script and the lumo CLI version. The CLI version needs the scopes admin:sessions:read and admin:sessions:write. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node oauth/introspection-and-revocation/setup.mjs
setup.mjs
// Creates what the recipe needs: a scope, and a confidential application that
// gets tokens and asks about them. Run it again at any time. The client secret
// is shown once, when the application is created: add --new-secret to replace
// a secret that you lost.
//
// node oauth/introspection-and-revocation/setup.mjs
//
// The API key needs the scopes admin:permissions:read, admin:permissions:write,
// admin:clients:read and admin:clients:write.
import { call, ensure, list, printEnv } from '../../_lib/admin.mjs';
await ensure('/admin/scopes', (s) => s.name === 'reports:read', { name: 'reports:read', description: 'Read the reports.' });
const name = 'Reports backend';
let client = (await list('/admin/clients')).find((c) => c.name === name);
let secret;
if (!client) {
const created = await call('POST', '/admin/clients', {
name,
isConfidential: true,
grantTypes: ['client_credentials'],
scopes: ['reports:read'],
});
client = created.data;
secret = client.secret;
} else if (process.argv.includes('--new-secret')) {
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
}
console.log(`The application "${name}" is ready. It may request reports:read.`);
printEnv({ CLIENT_ID: client.clientId, ...(secret ? { CLIENT_SECRET: secret } : {}) });
if (!secret) console.log('# CLIENT_SECRET was printed when the application was created. Add --new-secret to get a new one.');
The Node.js version and the curl version work with JWT access tokens and with opaque ones. The lumo CLI version lists opaque access tokens, so give the application that format first:
- In the portal, open Applications and the application "Reports backend".
- Open the Security tab.
- Under Token settings, Access token format, choose Opaque tokens.
- Choose Save token settings.
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. The output is that of the Node.js version. The curl version prints the answers of the server. The lumo CLI version shows the other side: an administrator lists the tokens of the application and revokes one.
- Node.js
- curl
- lumo CLI
// Ask LumoAuth whether a token is active, cache the answer, and revoke the token.
//
// node oauth/introspection-and-revocation/js/tokens.mjs
import { AuthModule } from '@lumoauth/backend';
const baseUrl = process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev';
const orgId = process.env.LUMOAUTH_ORG_ID;
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
const auth = new AuthModule({ baseUrl, orgId, clientId });
// The SDK has no call for the token request of a service and none for
// introspection: both are one POST with the credentials of the application.
async function post(path, form) {
const response = await fetch(`${baseUrl}/orgs/${orgId}/api/v1/oauth/${path}`, {
method: 'POST',
headers: { Authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}` },
body: new URLSearchParams(form),
});
if (!response.ok) throw new Error(`${path} answered ${response.status}: ${await response.text()}`);
return response.json();
}
// Answers are kept for 30 seconds, and never longer than the token is valid.
// A longer time means fewer calls, and a revoked token that works longer.
const cache = new Map();
async function introspect(token) {
const hit = cache.get(token);
if (hit && hit.until > Date.now()) return { ...hit.answer, source: 'from the cache' };
const answer = await post('introspect', { token });
if (answer.active) cache.set(token, { answer, until: Math.min(Date.now() + 30_000, answer.exp * 1000) });
return { ...answer, source: 'asked LumoAuth' };
}
const { access_token: token } = await post('token', { grant_type: 'client_credentials', scope: 'reports:read' });
for (const label of ['first check', 'second check']) {
const answer = await introspect(token);
console.log(`${label}: ${answer.active ? `active, scope ${answer.scope}` : 'not active'} (${answer.source})`);
}
// Revoke the token, for example at sign-out. This process removes its own
// cache entry. Another process holds its entry until the 30 seconds end.
await auth.revokeToken(token, undefined, { clientSecret, tokenTypeHint: 'access_token' });
cache.delete(token);
console.log('revoked');
const after = await introspect(token);
console.log(`after revocation: ${after.active ? 'active' : 'not active'} (${after.source})`);
node oauth/introspection-and-revocation/js/tokens.mjs
#!/bin/sh
# Ask LumoAuth whether a token is active, and revoke the token, with curl.
#
# sh oauth/introspection-and-revocation/http/tokens.sh
set -eu
OAUTH="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1/oauth"
# A token to work with. The application gets one for itself.
TOKEN=$(curl --silent --show-error "$OAUTH/token" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "grant_type=client_credentials" \
--data "scope=reports:read" |
sed 's/.*"access_token":"\([^"]*\)".*/\1/')
# Introspection. The caller authenticates as the application that the token
# was issued to. An active token comes back with its scope, subject and expiry.
curl --silent --show-error "$OAUTH/introspect" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "token=$TOKEN"
echo
# Revocation. The answer is 200 with an empty body, also for an unknown token.
curl --silent --show-error --output /dev/null --write-out "revoke: %{http_code}\n" "$OAUTH/revoke" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "token=$TOKEN" \
--data "token_type_hint=access_token"
# The same question again: the token is not active any more.
curl --silent --show-error "$OAUTH/introspect" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "token=$TOKEN"
echo
sh oauth/introspection-and-revocation/http/tokens.sh
#!/bin/sh
# As an administrator, list the access tokens of an application and revoke
# one, with the lumo CLI. The application must use opaque access tokens.
#
# sh oauth/introspection-and-revocation/cli/tokens.sh
#
# The script needs the lumo CLI, curl and jq.
set -eu
# The CLI reads its own three variables. With them it needs no `lumo login`.
export LUMO_BASE_URL="$LUMOAUTH_URL" LUMO_ORG="$LUMOAUTH_ORG_ID" LUMO_API_KEY="$LUMOAUTH_API_KEY"
OAUTH="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1/oauth"
# A token to work with. The application gets one for itself.
TOKEN=$(curl --silent --show-error "$OAUTH/token" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "grant_type=client_credentials" \
--data "scope=reports:read" | jq -r .access_token)
# The tokens of the application, the newest first.
show() {
lumo tokens list --client "$CLIENT_ID" -o json |
jq -r '.data[:3][] | " \(.id) \(.createdAt) \(.scopes | join(" ")) \(if .revoked then "revoked" else "valid" end)"'
}
echo "tokens:"
show
# Revoke the newest one by its ID.
TOKEN_ID=$(lumo tokens list --client "$CLIENT_ID" -o json | jq -r '.data[0].id')
lumo tokens revoke "$TOKEN_ID" --quiet > /dev/null
echo "revoked token $TOKEN_ID"
show
# The application asks about its token: it is not active any more.
curl --silent --show-error "$OAUTH/introspect" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "token=$TOKEN"
echo
sh oauth/introspection-and-revocation/cli/tokens.sh
Check the result
first check: active, scope reports:read (asked LumoAuth)
second check: active, scope reports:read (from the cache)
revoked
after revocation: not active (asked LumoAuth)
- The curl version ends with
{"active":false}. The answer of the server is the same for a revoked token, an expired token and a token that never existed. - Introspect the token with the credentials of another application: the answer is
{"active":false}too. - The lumo CLI version prints the newest tokens of the application before and after the revocation, with "valid" or "revoked" on each line.
Limits
- Only the application that a token was issued to can introspect it. A public application cannot introspect at all.
- A cached answer stays in use until its entry ends. A revoked token therefore works at your backend for up to 30 seconds more. Choose the time for your risk.
- The revocation endpoint answers 200 for every token, also for one that it does not hold.
revokeToken()of the SDK returns nothing and does not throw. - The Node.js packages have no call for introspection, so the code sends the request with
fetch.