Call the API with a scoped key
Create an API key that may do one job, use it from a script, and rotate it.
What it shows
- You create an API key for one job: a nightly report that lists the users. The key gets one scope,
admin:users:read. - The script lists the users with the key. LumoAuth allows the call.
- The script asks for the roles. LumoAuth refuses, and the answer names the missing scope.
- You rotate the key in the portal. The old key stops working at once.
Before you start
You create the key in the portal. Your account needs the permission settings.manage.
- In the sidebar, under Applications & developer tools, open API keys, and click Create API key.
- Enter the Name
Nightly user report, and choose an Expiration, for example 30 days. - Under Permissions, tick
admin:users:readand nothing else. - Click Create API key. The portal can ask you to confirm your sign-in first.
- Copy the key from the page API key created successfully. LumoAuth shows it only once.
The Python version uses the package requests. The CLI version needs the lumo CLI.
| 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. |
REPORT_API_KEY | The API key of this recipe, with the one scope admin:users:read. |
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.
- lumo CLI
- curl
- Python
- Node.js
authorization/api-keys/cli/report.sh
#!/bin/sh
# Call the Admin API with a key that has one scope, and read the refusal for
# a call outside that scope, with the lumo CLI.
#
# sh authorization/api-keys/cli/report.sh
set -eu
# The CLI reads its own three variables. With a key it needs no `lumo login`.
export LUMO_BASE_URL="$LUMOAUTH_URL" LUMO_ORG="$LUMOAUTH_ORG_ID" LUMO_API_KEY="$REPORT_API_KEY"
get() {
# In JSON mode an error is printed as JSON, with the status and the details.
if answer=$(lumo api GET "$2" --query limit=1 --output json); then
echo "$1 -> ok"
return
fi
answer=$(printf '%s\n' "$answer" | tr -d ' \n')
case "$answer" in
# A refusal for a missing scope names the scope.
*'"status":403'*) echo "$1 -> refused, missing scope: $(printf '%s\n' "$answer" | sed -n 's/.*"required_scopes":\["\([^"]*\)".*/\1/p')" ;;
*'"status":401'*) echo "$1 -> refused, the key is not valid" ;;
*) echo "$answer"; exit 1 ;;
esac
}
# The key has the scope admin:users:read.
get "list users" /users
# Roles need admin:roles:read, which the key does not have.
get "list roles" /roles
sh authorization/api-keys/cli/report.sh
authorization/api-keys/http/report.sh
#!/bin/sh
# Call the Admin API with a key that has one scope, and read the refusal for
# a call outside that scope, with curl.
#
# sh authorization/api-keys/http/report.sh
set -eu
ADMIN="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1/admin"
get() {
# The key goes in the header X-API-Key, alone: no access token with it.
# The last line of the answer is the HTTP status.
answer=$(curl --silent --show-error --write-out '\n%{http_code}' "$ADMIN$2" --header "X-API-Key: $REPORT_API_KEY")
case "$(printf '%s\n' "$answer" | tail -n 1)" in
200) echo "$1 -> ok" ;;
# A refusal for a missing scope names the scope.
403) echo "$1 -> refused, missing scope: $(printf '%s\n' "$answer" | sed -n 's/.*"required_scopes":\["\([^"]*\)".*/\1/p')" ;;
401) echo "$1 -> refused, the key is not valid" ;;
*) echo "$answer"; exit 1 ;;
esac
}
# The key has the scope admin:users:read.
get "list users" "/users?limit=1"
# Roles need admin:roles:read, which the key does not have.
get "list roles" "/roles?limit=1"
sh authorization/api-keys/http/report.sh
authorization/api-keys/python/report.py
"""Call the Admin API with a key that has one scope, and read the refusal for
a call outside that scope.
python authorization/api-keys/python/report.py
"""
import os
import requests
admin = f"{os.environ['LUMOAUTH_URL']}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1/admin"
def get(what, path):
# The key goes in the header X-API-Key, alone: no access token with it.
response = requests.get(admin + path, headers={"X-API-Key": os.environ["REPORT_API_KEY"]}, timeout=30)
body = response.json()
if response.status_code == 200:
print(f"{what} -> ok")
elif response.status_code == 403 and body.get("details", {}).get("required_scopes"):
# A refusal for a missing scope names the scope.
print(f"{what} -> refused, missing scope: {', '.join(body['details']['required_scopes'])}")
elif response.status_code == 401:
print(f"{what} -> refused, the key is not valid")
else:
raise SystemExit(f"{what} answered {response.status_code}: {body}")
# The key has the scope admin:users:read.
get("list users", "/users?limit=1")
# Roles need admin:roles:read, which the key does not have.
get("list roles", "/roles?limit=1")
python authorization/api-keys/python/report.py
authorization/api-keys/js/report.mjs
// Call the Admin API with a key that has one scope, and read the refusal for
// a call outside that scope.
//
// node authorization/api-keys/js/report.mjs
const admin = `${process.env.LUMOAUTH_URL}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1/admin`;
async function get(what, path) {
// The key goes in the header X-API-Key, alone: no access token with it.
const response = await fetch(admin + path, { headers: { 'X-API-Key': process.env.REPORT_API_KEY } });
const body = await response.json();
if (response.status === 200) {
console.log(`${what} -> ok`);
} else if (response.status === 403 && body.details?.required_scopes) {
// A refusal for a missing scope names the scope.
console.log(`${what} -> refused, missing scope: ${body.details.required_scopes.join(', ')}`);
} else if (response.status === 401) {
console.log(`${what} -> refused, the key is not valid`);
} else {
throw new Error(`${what} answered ${response.status}: ${JSON.stringify(body)}`);
}
}
// The key has the scope admin:users:read.
await get('list users', '/users?limit=1');
// Roles need admin:roles:read, which the key does not have.
await get('list roles', '/roles?limit=1');
node authorization/api-keys/js/report.mjs
Check the result
Output
list users -> ok
list roles -> refused, missing scope: admin:roles:read
Then rotate the key:
- On the API keys page, click Rotate in the row of the key, and confirm.
- Run the script again with the old key. Both lines now say "refused, the key is not valid": LumoAuth answers 401.
- Copy the new key from the page API key rotated successfully, set
REPORT_API_KEYto it, and run the script again. The output is the same as before the rotation.
The API keys page shows when each key was last used, and from which address.
Limits
- You create, rotate and revoke a key in the portal. The Admin API has no endpoint for that.
- A write scope does not include the read scope. A job that lists and changes users needs
admin:users:readandadmin:users:write. - A key acts for the person who created it. LumoAuth refuses a call when that person no longer holds the permission that the endpoint needs, whatever scopes the key has.
- Send the key in
X-API-Key, or asAuthorization: ApiKey …. A key inAuthorization: Bearergets the answer 401. - A key works only in its own organization, and an organization has at most 25 active keys.