Skip to main content

A token for one API

Name the API in the token request, so that the token works at that API and nowhere else.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoPlain HTTP
Standards
RFC 8707

What it shows​

  1. The application calls two APIs: https://orders.example.com and https://billing.example.com.
  2. It asks for a token and sends resource with the address of the orders API.
  3. The token carries that address as its audience.
  4. The orders API accepts the token. The billing API refuses it, because the audience is not its own address.

A token that is taken from one API is therefore of no use at the other one.

Before you start​

  • An identifier for each API: an absolute https address without a fragment. The address does not have to answer requests, and you do not register it.
  • An API key for the setup script, with the scopes admin:permissions:read, admin:permissions:write, admin:clients:read and admin:clients:write.
  • A confidential application. The setup script creates the application "Acme Storefront".
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
CLIENT_IDThe client ID of the application. The setup script prints it.
CLIENT_SECRETThe secret of the application. The setup script prints it once, when it creates the application.

The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.

node oauth/resource-indicators/setup.mjs
setup.mjs
// Creates what the recipe needs: a scope, and a confidential application that
// calls two APIs. 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/resource-indicators/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 === 'orders:read', { name: 'orders:read', description: 'Read the orders.' });

const name = 'Acme Storefront';
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: ['orders: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.`);
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.');

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 curl version reads the audience with introspection, and shows the answer to a resource that is not an address.

oauth/resource-indicators/js/audience.mjs
// Ask for a token for one API, then show which API accepts it.
//
// node oauth/resource-indicators/js/audience.mjs
import { issuerFor, verifyAccessToken } from '@lumoauth/agent';

const issuer = issuerFor(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev', process.env.LUMOAUTH_ORG_ID);
const orders = 'https://orders.example.com';
const billing = 'https://billing.example.com';

// The client names the API in the token request. The SDK has no parameter
// for `resource` in this grant, so the request is a plain POST.
const response = await fetch(`${issuer}/oauth/token`, {
method: 'POST',
headers: { Authorization: `Basic ${btoa(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`)}` },
body: new URLSearchParams({ grant_type: 'client_credentials', scope: 'orders:read', resource: orders }),
});
if (!response.ok) throw new Error(await response.text());
const { access_token: token } = await response.json();
console.log(`requested resource: ${orders}`);

// Each API verifies the token with its own identifier as the audience.
for (const [name, resource] of [['orders API', orders], ['billing API', billing]]) {
try {
const claims = await verifyAccessToken(token, { issuer, resource });
console.log(`${name}: accepted, audience ${[claims.aud].flat().join(' ')}`);
} catch (error) {
console.log(`${name}: refused`);
}
}
node oauth/resource-indicators/js/audience.mjs

Check the result​

Output
requested resource: https://orders.example.com
orders API: accepted, audience https://orders.example.com
billing API: refused
  • Leave out resource: the audience of the token is then the client ID of the application, and both APIs refuse the token.
  • Send resource=orders: the server answers invalid_target, because the value is not an absolute address.
  • Limit the application to your APIs. In the portal, open the application, the Configuration tab, and add the address under Resource indicators. A request for another resource then answers invalid_target.

Limits​

  • An application with an empty list under Resource indicators may name any valid address. Fill the list for an application that you do not control.
  • The parameter also works at the authorization endpoint, for a token of a signed-in person. The token request can then name the same resource or leave it out.
  • The Python and Go calls for the client credentials grant have no parameter for resource. The programs send the token request as a plain POST and verify the token with the SDK.
  • The Configuration tab of the portal asks for a redirect URI before it saves. An application that only uses client credentials has none, so enter one that you own.