A token for one API
Name the API in the token request, so that the token works at that API and nowhere else.
What it shows
- The application calls two APIs:
https://orders.example.comandhttps://billing.example.com. - It asks for a token and sends
resourcewith the address of the orders API. - The token carries that address as its audience.
- 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
httpsaddress 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:readandadmin:clients:write. - A confidential application. The setup script creates the application "Acme Storefront".
| 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. |
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.
- Node.js
- Python
- Go
- curl
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
oauth/resource-indicators/python/audience.py
"""Ask for a token for one API, then show which API accepts it.
python oauth/resource-indicators/python/audience.py
"""
import os
import requests
from lumoauth import LumoAuth, LumoAuthTokenError, verify_access_token
issuer = LumoAuth().issuer # from LUMOAUTH_URL and LUMOAUTH_ORG_ID
orders = "https://orders.example.com"
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.
response = requests.post(
f"{issuer}/oauth/token",
auth=(os.environ["CLIENT_ID"], os.environ["CLIENT_SECRET"]),
data={"grant_type": "client_credentials", "scope": "orders:read", "resource": orders},
)
response.raise_for_status()
token = response.json()["access_token"]
print(f"requested resource: {orders}")
# Each API verifies the token with its own identifier as the audience.
for name, resource in (("orders API", orders), ("billing API", billing)):
try:
claims = verify_access_token(token, issuer=issuer, resource=resource)
print(f"{name}: accepted, audience {' '.join(claims.aud)}")
except LumoAuthTokenError:
print(f"{name}: refused")
python oauth/resource-indicators/python/audience.py
oauth/resource-indicators/go/main.go
// Ask for a token for one API, then show which API accepts it.
//
// go run ./oauth/resource-indicators/go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
const (
orders = "https://orders.example.com"
billing = "https://billing.example.com"
)
func main() {
issuer := os.Getenv("LUMOAUTH_URL") + "/orgs/" + os.Getenv("LUMOAUTH_ORG_ID") + "/api/v1"
// 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.
form := url.Values{"grant_type": {"client_credentials"}, "scope": {"orders:read"}, "resource": {orders}}
request, _ := http.NewRequest("POST", issuer+"/oauth/token", strings.NewReader(form.Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.SetBasicAuth(os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET"))
response, err := http.DefaultClient.Do(request)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
var answer struct {
AccessToken string `json:"access_token"`
}
if json.NewDecoder(response.Body).Decode(&answer); answer.AccessToken == "" {
log.Fatalf("The token request failed: %s", response.Status)
}
fmt.Printf("requested resource: %s\n", orders)
// Each API verifies the token with its own identifier as the audience.
for _, api := range [][2]string{{"orders API", orders}, {"billing API", billing}} {
claims, err := lumoauth.VerifyAccessToken(context.Background(), answer.AccessToken, lumoauth.AccessTokenVerifyOptions{Issuer: issuer, Resource: api[1]})
if err != nil {
fmt.Printf("%s: refused\n", api[0])
continue
}
fmt.Printf("%s: accepted, audience %s\n", api[0], strings.Join(claims.Audience, " "))
}
}
go run ./oauth/resource-indicators/go
oauth/resource-indicators/http/audience.sh
#!/bin/sh
# Ask for a token for one API, and read its audience, with curl.
#
# sh oauth/resource-indicators/http/audience.sh
#
# The script needs curl and jq.
set -eu
OAUTH="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1/oauth"
# The client names the API in the token request.
TOKEN=$(curl --silent --show-error "$OAUTH/token" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "grant_type=client_credentials" \
--data "scope=orders:read" \
--data-urlencode "resource=https://orders.example.com" | jq -r .access_token)
# The token carries that address as its audience. Introspection shows it.
curl --silent --show-error "$OAUTH/introspect" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "token=$TOKEN" | jq -c '{active, aud, scope}'
# An address that cannot name an API is refused with invalid_target.
curl --silent --show-error "$OAUTH/token" \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data "grant_type=client_credentials" \
--data-urlencode "resource=orders"
echo
sh oauth/resource-indicators/http/audience.sh
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 answersinvalid_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.