Verify access tokens in your API
Check a token inside your service with the published keys: signature, issuer, audience, expiry and scopes.
What it shows
- The API reads the discovery document of the organization once and caches the key set.
- For each request, it verifies the token: the signature, the issuer, the expiry, and that the audience is this API.
- Each route checks its scope. A token without the scope gets 403.
- The API reads the subject, the scopes, the agent flag and the actor chain from the claims.
- A token for another API gets 401, and so does a request with no token.
The API makes no call to LumoAuth for a request. After a key rotation, the cache fetches the key set again when a token names a key ID that the cache does not hold. The API needs no restart.
Before you start
- The identifier of your API: an
httpsaddress such ashttps://reports.example.com. A client names it asresourcein the token request, and the token carries it as the audience. The address does not have to answer requests. - An API key for the setup script, with the scopes
admin:permissions:read,admin:permissions:write,admin:clients:readandadmin:clients:write. - An application that calls the API. The setup script creates the application "Reports dashboard", 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 that calls the API. The setup script prints it. |
CLIENT_SECRET | The secret of that application. The setup script prints it once, when it creates the application. |
API_RESOURCE | Optional. The identifier of your API, which tokens carry as the audience. The default is https://reports.example.com. |
PORT | Optional. The local port of the API. The default is 4000. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node oauth/verify-access-tokens/setup.mjs
setup.mjs
// Creates what the recipe needs: the scopes of the API, and a confidential
// application that calls the API. 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/verify-access-tokens/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';
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 = 'Reports dashboard';
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.');
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. In each language the first file is the API. The second file starts it, asks LumoAuth for two tokens, and sends four requests.
- Node.js
- Python
- Go
oauth/verify-access-tokens/js/api.mjs
// The Reports API. It verifies the access token of each request with the
// published keys of the organization: no call to LumoAuth for each request.
import express from 'express';
import { AccessTokenError, accessTokenScopes, createAccessTokenVerifier, issuerFor } from '@lumoauth/agent';
// The verifier reads the discovery document once and caches the key set.
// A token with a key ID that it has not seen makes it fetch the keys again.
const verifier = createAccessTokenVerifier({
issuer: issuerFor(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev', process.env.LUMOAUTH_ORG_ID),
// The identifier of this API. The token must name it as its audience.
resource: process.env.API_RESOURCE ?? 'https://reports.example.com',
});
// Verifies the token of the request, then checks the scope of the route.
const requireToken = (scope) => async (req, res, next) => {
try {
const url = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
req.token = await verifier.verifyRequest({ method: req.method, url, headers: req.headers });
} catch (error) {
if (!(error instanceof AccessTokenError)) return next(error);
return res.status(401).set('WWW-Authenticate', 'Bearer error="invalid_token"').json({ error: error.code, error_description: error.message });
}
if (!accessTokenScopes(req.token).includes(scope)) {
return res.status(403).json({ error: 'insufficient_scope', error_description: `Missing: ${scope}` });
}
next();
};
// What the API learned from the token: who calls, with which scopes, whether
// the caller is an agent, and who acts for the subject (the `act` claim).
const caller = (claims) => {
const actors = [];
for (let actor = claims.act; actor; actor = actor.act) actors.push(actor.sub);
return { subject: claims.sub, scopes: accessTokenScopes(claims), agent: claims.is_agent === true, actors };
};
export const app = express();
app.get('/reports', requireToken('reports:read'), (req, res) => res.json(caller(req.token)));
app.post('/reports', requireToken('reports:write'), (req, res) => res.status(201).json(caller(req.token)));
oauth/verify-access-tokens/js/try.mjs
// Starts the Reports API, then calls it with a token for this API, with a
// token for another API, and with no token.
//
// node oauth/verify-access-tokens/js/try.mjs
import { app } from './api.mjs';
const port = process.env.PORT ?? 4000;
const server = app.listen(port);
// A client asks for a token for one API: `resource` becomes the audience.
async function tokenFor(resource) {
const response = await fetch(`${process.env.LUMOAUTH_URL}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1/oauth/token`, {
method: 'POST',
headers: { Authorization: `Basic ${btoa(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`)}` },
body: new URLSearchParams({ grant_type: 'client_credentials', scope: 'reports:read', resource }),
});
if (!response.ok) throw new Error(await response.text());
return (await response.json()).access_token;
}
async function request(label, method, token) {
const response = await fetch(`http://localhost:${port}/reports`, { method, headers: token ? { Authorization: `Bearer ${token}` } : {} });
// A refused request has `error` and `error_description` in its body.
console.log(`${label} -> ${response.status} ${response.ok ? await response.text() : ''}`.trimEnd());
}
const mine = await tokenFor(process.env.API_RESOURCE ?? 'https://reports.example.com');
const other = await tokenFor('https://billing.example.com');
await request('GET /reports, token for this API', 'GET', mine);
await request('POST /reports, the same token', 'POST', mine);
await request('GET /reports, token for another API', 'GET', other);
await request('GET /reports, no token', 'GET');
server.close();
node oauth/verify-access-tokens/js/try.mjs
oauth/verify-access-tokens/python/api.py
"""The Reports API. It verifies the access token of each request with the
published keys of the organization: no call to LumoAuth for each request.
"""
import os
from fastapi import Depends, FastAPI
from lumoauth import AccessTokenClaims, AccessTokenVerifier, LumoAuth
from lumoauth.fastapi import require_access_token
# The verifier reads the discovery document once and caches the key set.
# A token with a key ID that it has not seen makes it fetch the keys again.
verifier = AccessTokenVerifier(
LumoAuth().issuer, # from LUMOAUTH_URL and LUMOAUTH_ORG_ID
# The identifier of this API. The token must name it as its audience.
os.environ.get("API_RESOURCE", "https://reports.example.com"),
)
def require_token(scope: str):
"""Verifies the token of the request, then checks the scope of the route."""
return Depends(require_access_token(resource=verifier.resource, verifier=verifier, scopes=[scope]))
def caller(claims: AccessTokenClaims) -> dict:
"""What the API learned from the token: who calls, with which scopes, whether
the caller is an agent, and who acts for the subject (the `act` claim)."""
return {
"subject": claims.sub,
"scopes": list(claims.scopes),
"agent": claims.is_agent,
"actors": [actor["sub"] for actor in claims.act_chain],
}
app = FastAPI()
@app.get("/reports")
def read_reports(claims: AccessTokenClaims = require_token("reports:read")):
return caller(claims)
@app.post("/reports", status_code=201)
def write_report(claims: AccessTokenClaims = require_token("reports:write")):
return caller(claims)
oauth/verify-access-tokens/python/try.py
"""Starts the Reports API, then calls it with a token for this API, with a
token for another API, and with no token.
python oauth/verify-access-tokens/python/try.py
"""
import os
import threading
import time
import requests
import uvicorn
from api import app
port = int(os.environ.get("PORT", "4000"))
server = uvicorn.Server(uvicorn.Config(app, port=port, log_level="warning"))
threading.Thread(target=server.run, daemon=True).start()
while not server.started:
time.sleep(0.05)
def token_for(resource: str) -> str:
"""A client asks for a token for one API: `resource` becomes the audience."""
response = requests.post(
f"{os.environ['LUMOAUTH_URL']}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1/oauth/token",
auth=(os.environ["CLIENT_ID"], os.environ["CLIENT_SECRET"]),
data={"grant_type": "client_credentials", "scope": "reports:read", "resource": resource},
)
response.raise_for_status()
return response.json()["access_token"]
def request(label: str, method: str, token: str | None = None) -> None:
headers = {"Authorization": f"Bearer {token}"} if token else {}
response = requests.request(method, f"http://localhost:{port}/reports", headers=headers)
# A refused request has `error` and `error_description` in its body, under "detail".
print(f"{label} -> {response.status_code} {response.text if response.ok else ''}".rstrip())
mine = token_for(os.environ.get("API_RESOURCE", "https://reports.example.com"))
other = token_for("https://billing.example.com")
request("GET /reports, token for this API", "GET", mine)
request("POST /reports, the same token", "POST", mine)
request("GET /reports, token for another API", "GET", other)
request("GET /reports, no token", "GET")
server.should_exit = True
python oauth/verify-access-tokens/python/try.py
oauth/verify-access-tokens/go/api.go
// The Reports API. It verifies the access token of each request with the
// published keys of the organization: no call to LumoAuth for each request.
package main
import (
"encoding/json"
"net/http"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
// The identifier of this API. The token must name it as its audience.
func apiResource() string {
if resource := os.Getenv("API_RESOURCE"); resource != "" {
return resource
}
return "https://reports.example.com"
}
// What the API learned from the token: who calls, with which scopes, whether
// the caller is an agent, and who acts for the subject (the `act` claim).
type caller struct {
Subject string `json:"subject"`
Scopes []string `json:"scopes"`
Agent bool `json:"agent"`
Actors []string `json:"actors"`
}
// The handler of a route. The middleware has verified the token: the
// handler checks the scope of the route and reads the claims.
func reports(scope string, status int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, _ := lumoauth.AccessTokenFromContext(r.Context())
w.Header().Set("Content-Type", "application/json")
if !claims.HasScope(scope) {
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]string{"error": "insufficient_scope", "error_description": "Missing: " + scope})
return
}
actors := claims.ActorChain()
if actors == nil {
actors = []string{}
}
w.WriteHeader(status)
json.NewEncoder(w).Encode(caller{Subject: claims.Subject, Scopes: claims.Scopes(), Agent: claims.IsAgent, Actors: actors})
})
}
func newAPI(issuer string) http.Handler {
// The middleware reads the discovery document once and caches the key
// set. A token with a key ID that it has not seen makes it fetch the
// keys again.
protect := lumoauth.RequireAccessToken(lumoauth.AccessTokenVerifyOptions{Issuer: issuer, Resource: apiResource()})
mux := http.NewServeMux()
mux.Handle("GET /reports", protect(reports("reports:read", http.StatusOK)))
mux.Handle("POST /reports", protect(reports("reports:write", http.StatusCreated)))
return mux
}
oauth/verify-access-tokens/go/main.go
// Starts the Reports API, then calls it with a token for this API, with a
// token for another API, and with no token.
//
// go run ./oauth/verify-access-tokens/go
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
)
var issuer = os.Getenv("LUMOAUTH_URL") + "/orgs/" + os.Getenv("LUMOAUTH_ORG_ID") + "/api/v1"
// A client asks for a token for one API: `resource` becomes the audience.
func tokenFor(resource string) string {
form := url.Values{"grant_type": {"client_credentials"}, "scope": {"reports:read"}, "resource": {resource}}
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)
}
return answer.AccessToken
}
func request(label, method, address, token string) {
request, _ := http.NewRequest(method, address, nil)
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
// A refused request has `error` and `error_description` in its body.
text := ""
if response.StatusCode < 400 {
body, _ := io.ReadAll(response.Body)
text = string(body)
}
fmt.Println(strings.TrimSpace(fmt.Sprintf("%s -> %d %s", label, response.StatusCode, text)))
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "4000"
}
listener, err := net.Listen("tcp", "localhost:"+port)
if err != nil {
log.Fatal(err)
}
go http.Serve(listener, newAPI(issuer))
address := "http://localhost:" + port + "/reports"
mine := tokenFor(apiResource())
other := tokenFor("https://billing.example.com")
request("GET /reports, token for this API", "GET", address, mine)
request("POST /reports, the same token", "POST", address, mine)
request("GET /reports, token for another API", "GET", address, other)
request("GET /reports, no token", "GET", address, "")
}
go run ./oauth/verify-access-tokens/go
Check the result
Output
GET /reports, token for this API -> 200 {"subject":"client_client_944fb2b5a6632680cf757a3053ba6e07","scopes":["reports:read"],"agent":false,"actors":[]}
POST /reports, the same token -> 403
GET /reports, token for another API -> 401
GET /reports, no token -> 401
- The body of each refused answer has an
error_descriptionthat says why. For the third request, it says that the audience is wrong. - The subject of this token is an application, so
agentisfalseandactorsis empty. The token of an agent hasagent: true. A token from a token exchange lists the service that acts for the person inactors.
Limits
- This check works for JWT access tokens. An application with opaque tokens needs introspection.
- A verified token can be revoked before it expires, and this check does not see that. Keep the lifetime of access tokens short, or introspect the token for a sensitive action.
- For a token that is bound to a key, the verifier also needs the DPoP proof of the request. See Bind tokens to a key with DPoP.