Service-to-service calls
Give a backend service its own identity, get a token with the scopes of one job, and call another service.
What it shows
- A confidential application stands for the calling service. It may request the scope
reports:readand no other scope. - The service asks the token endpoint for a token with the client credentials grant. No person signs in.
- The service keeps the token until one minute before expiry, then asks again.
- The receiving service verifies the token with the published keys and checks the scope.
- A request for
reports:writeis 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:readandadmin: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.
| 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 for the calling service. The setup script prints it. |
CLIENT_SECRET | The 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.
- Node.js
- Python
- Go
- curl
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
oauth/client-credentials/python/service.py
"""A backend service gets a token of its own, and another service verifies it.
python oauth/client-credentials/python/service.py
"""
import os
import time
from lumoauth import LumoAuth, LumoAuthApiError, verify_access_token
# Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID. The token endpoint takes no API key.
lumo = LumoAuth()
client_id = os.environ["CLIENT_ID"]
client_secret = os.environ["CLIENT_SECRET"]
# The calling service keeps the token until one minute before expiry, then asks again.
cached = {}
def get_token() -> str:
if cached and cached["expires_at"] - 60 > time.time():
return cached["token"]
answer = lumo.auth.client_credentials(client_id, client_secret, scopes=["reports:read"])
cached.update(token=answer["access_token"], expires_at=time.time() + answer["expires_in"])
print(f"token: scope {answer['scope']}, expires in {answer['expires_in']} s")
return cached["token"]
token = get_token()
print(f"second call: {'the cached token' if get_token() == token else '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.
claims = verify_access_token(token, issuer=lumo.issuer, resource=client_id)
if not claims.has_scope("reports:read"):
raise SystemExit("The token lacks reports:read.")
print(f"verified: client {claims.client_id}, scope {claims.scope}")
# The application may not request this scope, so the server refuses.
try:
lumo.auth.client_credentials(client_id, client_secret, scopes=["reports:write"])
print("reports:write -> granted")
except LumoAuthApiError as error:
print(f"reports:write -> refused ({error.code})")
python oauth/client-credentials/python/service.py
oauth/client-credentials/go/main.go
// A backend service gets a token of its own, and another service verifies it.
//
// go run ./oauth/client-credentials/go
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"time"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
var (
clientID = os.Getenv("CLIENT_ID")
clientSecret = os.Getenv("CLIENT_SECRET")
// The calling service keeps the token until one minute before expiry, then asks again.
cachedToken string
expiresAt time.Time
)
func getToken(ctx context.Context, client *lumoauth.Client) string {
if cachedToken != "" && time.Now().Before(expiresAt.Add(-time.Minute)) {
return cachedToken
}
answer, err := client.Auth.ClientCredentials(ctx, clientID, clientSecret, "reports:read")
if err != nil {
log.Fatal(err)
}
cachedToken = answer.AccessToken
expiresAt = time.Now().Add(time.Duration(answer.ExpiresIn) * time.Second)
fmt.Printf("token: scope %s, expires in %d s\n", answer.Scope, answer.ExpiresIn)
return cachedToken
}
func main() {
// Reads LUMOAUTH_URL and LUMOAUTH_ORG_ID.
client, err := lumoauth.New(lumoauth.WithClientCredentials(clientID, clientSecret))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
token := getToken(ctx, client)
if getToken(ctx, client) == token {
fmt.Println("second call: the cached token")
} else {
fmt.Println("second call: 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.
issuer, err := client.Issuer()
if err != nil {
log.Fatal(err)
}
claims, err := lumoauth.VerifyAccessToken(ctx, token, lumoauth.AccessTokenVerifyOptions{Issuer: issuer, Resource: clientID})
if err != nil {
log.Fatal(err)
}
if !claims.HasScope("reports:read") {
log.Fatal("The token lacks reports:read.")
}
fmt.Printf("verified: client %s, scope %s\n", claims.ClientID, claims.Scope)
// The application may not request this scope, so the server refuses.
_, err = client.Auth.ClientCredentials(ctx, clientID, clientSecret, "reports:write")
var apiError *lumoauth.APIError
if errors.As(err, &apiError) {
fmt.Printf("reports:write -> refused (%s)\n", apiError.Code)
} else if err != nil {
log.Fatal(err)
} else {
fmt.Println("reports:write -> granted")
}
}
go run ./oauth/client-credentials/go
oauth/client-credentials/http/service.sh
#!/bin/sh
# A backend service gets a token of its own, with curl.
#
# sh oauth/client-credentials/http/service.sh
set -eu
TOKEN_URL="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1/oauth/token"
# The service sends its own credentials and the scope of the job.
# The answer holds access_token, token_type, expires_in and scope.
curl --silent --show-error "$TOKEN_URL" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "grant_type=client_credentials" \
--data "scope=reports:read" |
sed 's/"access_token":"[^"]*"/"access_token":"..."/'
echo
# The application may not request this scope, so the server refuses.
curl --silent --show-error "$TOKEN_URL" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "grant_type=client_credentials" \
--data "scope=reports:write"
echo
sh oauth/client-credentials/http/service.sh
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
subclaim isclient_followed by the client ID, and itsgtyclaim isclient_credentials. - Leave out
scopein 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
resourcein 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.