Skip to main content

Service-to-service calls

Give a backend service its own identity, get a token with the scopes of one job, and call another service.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoPlain HTTP

What it shows​

  1. A confidential application stands for the calling service. It may request the scope reports:read and no other scope.
  2. The service asks the token endpoint for a token with the client credentials grant. No person signs in.
  3. The service keeps the token until one minute before expiry, then asks again.
  4. The receiving service verifies the token with the published keys and checks the scope.
  5. A request for reports:write is refused, because the application may not request that scope.

Before you start​

  • An API key for the setup script, with the scopes admin:permissions:read, admin:permissions:write, admin:clients:read and admin:clients:write. Create it in the portal under Applications & developer tools, API keys.
  • Two scopes and the application "Report worker". The setup script creates them.

The client secret is shown once, when the application is created. Store it in the secret store of the service.

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 for the calling service. The setup script prints it.
CLIENT_SECRETThe secret of that 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/client-credentials/setup.mjs
setup.mjs
// Creates what the recipe needs: two scopes, and a confidential application
// for the calling service that may request one of 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/client-credentials/setup.mjs
//
// The API key needs the scopes admin:permissions:write and admin:clients:write.
import { call, ensure, list, printEnv } from '../../_lib/admin.mjs';

for (const [name, description] of [
['reports:read', 'Read the reports.'],
['reports:write', 'Create and change reports.'],
]) {
await ensure('/admin/scopes', (s) => s.name === name, { name, description });
}

const name = 'Report worker';
let client = (await list('/admin/clients')).find((c) => c.name === name);
let secret;
if (!client) {
// The service has no user and no browser: it needs one grant type only.
// It may read reports. It may not write them.
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.');

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 makes the two token requests and prints the answers of the server. It does not verify the token.

oauth/client-credentials/js/service.mjs
// A backend service gets a token of its own, and another service verifies it.
//
// node oauth/client-credentials/js/service.mjs
import { accessTokenScopes, issuerFor, verifyAccessToken } from '@lumoauth/agent';

const issuer = issuerFor(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev', process.env.LUMOAUTH_ORG_ID);
const clientId = process.env.CLIENT_ID;

// The calling service: one request to the token endpoint, with its own credentials.
async function requestToken(scope) {
const response = await fetch(`${issuer}/oauth/token`, {
method: 'POST',
headers: { Authorization: `Basic ${btoa(`${clientId}:${process.env.CLIENT_SECRET}`)}` },
body: new URLSearchParams({ grant_type: 'client_credentials', scope }),
});
const answer = await response.json();
if (!response.ok) throw new Error(answer.error);
return answer;
}

// It keeps the token until one minute before expiry, then asks again.
let cached;
async function getToken() {
if (cached && cached.expiresAt - 60_000 > Date.now()) return cached.token;
const answer = await requestToken('reports:read');
cached = { token: answer.access_token, expiresAt: Date.now() + answer.expires_in * 1000 };
console.log(`token: scope ${answer.scope}, expires in ${answer.expires_in} s`);
return cached.token;
}

const token = await getToken();
console.log(`second call: ${(await getToken()) === token ? 'the cached token' : 'a new token'}`);

// The receiving service: it checks the signature, the issuer, the expiry and
// the audience with the published keys. Without a `resource` in the token
// request, the audience is the client ID of the caller.
const claims = await verifyAccessToken(token, { issuer, resource: clientId });
if (!accessTokenScopes(claims).includes('reports:read')) throw new Error('The token lacks reports:read.');
console.log(`verified: client ${claims.client_id}, scope ${claims.scope}`);

// The application may not request this scope, so the server refuses.
try {
await requestToken('reports:write');
console.log('reports:write -> granted');
} catch (error) {
console.log(`reports:write -> refused (${error.message})`);
}
node oauth/client-credentials/js/service.mjs

Check the result​

Output
token: scope reports:read, expires in 3600 s
second call: the cached token
verified: client client_1268c348467d6d30e21f80345a19f6d0, scope reports:read
reports:write -> refused (invalid_scope)
  • The token is a JWT. Its sub claim is client_ followed by the client ID, and its gty claim is client_credentials.
  • Leave out scope in the request: the token then carries every scope that the application may request.
  • In the portal, open Applications and the application "Report worker". The Configuration tab lists the allowed scopes.

Limits​

  • The token has no refresh token. The service asks for a new access token with its credentials.
  • Without a resource in the request, the audience of the token is the client ID of the caller. To get a token that works at one API only, see A token for one API.
  • The Node.js packages have no call for this grant outside the agent client, so the Node.js version sends the request with fetch.
  • To use a key in place of the client secret, see Authenticate a client with a key.