Check a permission
Ask LumoAuth whether a person may do something, from each server SDK and from plain HTTP.
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
What it shows
- A role holds the permission
documents.edit, and one of two users holds the role. - Your backend asks LumoAuth about each user: may this person edit documents?
- LumoAuth answers yes for the editor and no for the reader.
Your backend holds an API key and asks about another person, so each request names that person as the subject. A browser never makes this call: it has no API key.
Before you start
- An API key with the scope
authz:check. Create it in the portal under Applications & developer tools, API keys. - A permission, a role that holds it, and two users. The setup script creates them. Its API key also needs
admin:permissions:write,admin:roles:writeandadmin:users:write.
| 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. |
LUMOAUTH_API_KEY | An API key with the scope authz:check. |
EDITOR_USER_ID | The ID of a user who holds the permission. The setup script prints it. |
READER_USER_ID | The ID of a user who does not hold it. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node authorization/check-a-permission/setup.mjs
setup.mjs
// Creates what the recipe needs: a permission, a role that holds it, and two
// test users. One user gets the role. Run it again at any time.
//
// node authorization/check-a-permission/setup.mjs
//
// The API key needs the scopes admin:permissions:write, admin:roles:write
// and admin:users:write.
import { randomBytes } from 'node:crypto';
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
const permission = await ensure('/admin/permissions', (p) => p.slug === 'documents.edit', {
name: 'Edit documents',
slug: 'documents.edit',
description: 'Change the text of a document.',
});
const role = await ensure('/admin/roles', (r) => r.slug === 'editor', {
name: 'Editor',
slug: 'editor',
description: 'May read and edit documents.',
});
await call('PUT', `/admin/roles/${role.id}/permissions`, { permissions: [permission.slug] });
const user = (email, name) =>
ensure('/admin/users', (u) => u.email === email, {
email,
name,
// The recipe never signs in as these users, so nobody needs the password.
password: `${randomBytes(18).toString('base64url')}#Aa1`,
emailVerified: true,
});
const editor = await user('editor@example.com', 'Erin Editor');
const reader = await user('reader@example.com', 'Riley Reader');
await call('PUT', `/admin/users/${editor.id}/roles`, { roles: [role.slug] });
console.log(`Permission ${permission.slug}, role ${role.slug}, and two users are ready.`);
printEnv({ EDITOR_USER_ID: editor.id, READER_USER_ID: reader.id });
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 programs were run with a built-in permission. On a new organization the setup script stops at the step that adds the new permission to the role.
- Node.js
- Python
- Go
- PHP
- Java
- C#
- curl
authorization/check-a-permission/js/check.mjs
// Ask LumoAuth whether a person holds a permission.
//
// node authorization/check-a-permission/js/check.mjs
import { LumoAuthBackend } from '@lumoauth/backend';
const lumo = new LumoAuthBackend({
baseUrl: process.env.LUMOAUTH_URL,
orgId: process.env.LUMOAUTH_ORG_ID,
secretKey: process.env.LUMOAUTH_API_KEY,
});
const permission = process.env.PERMISSION ?? 'documents.edit';
for (const [who, userId] of [
['editor', process.env.EDITOR_USER_ID],
['reader', process.env.READER_USER_ID],
]) {
// The key asks about another person, so it names that person as the subject.
const allowed = await lumo.permissions.check(permission, undefined, { userId });
console.log(`${who}: ${permission} -> ${allowed ? 'allowed' : 'denied'}`);
}
node authorization/check-a-permission/js/check.mjs
authorization/check-a-permission/python/check.py
"""Ask LumoAuth whether a person holds a permission.
python authorization/check-a-permission/python/check.py
"""
import os
from lumoauth import LumoAuth
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
lumo = LumoAuth()
permission = os.environ.get("PERMISSION", "documents.edit")
for who, user_id in (("editor", os.environ["EDITOR_USER_ID"]), ("reader", os.environ["READER_USER_ID"])):
# The key asks about another person, so it names that person as the subject.
allowed = lumo.permissions.check(permission, user_id=user_id)
print(f"{who}: {permission} -> {'allowed' if allowed else 'denied'}")
python authorization/check-a-permission/python/check.py
authorization/check-a-permission/go/main.go
// Ask LumoAuth whether a person holds a permission.
//
// go run ./authorization/check-a-permission/go
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
client, err := lumoauth.New()
if err != nil {
log.Fatal(err)
}
permission := os.Getenv("PERMISSION")
if permission == "" {
permission = "documents.edit"
}
ctx := context.Background()
for _, who := range []string{"EDITOR", "READER"} {
// The key asks about another person, so it names that person as the subject.
allowed, err := client.Permissions.Check(ctx, permission, &lumoauth.CheckOptions{UserID: os.Getenv(who + "_USER_ID")})
if err != nil {
log.Fatal(err)
}
answer := "denied"
if allowed {
answer = "allowed"
}
fmt.Printf("%s: %s -> %s\n", strings.ToLower(who), permission, answer)
}
}
go run ./authorization/check-a-permission/go
authorization/check-a-permission/php/check.php
<?php
// Ask LumoAuth whether a person holds a permission.
//
// php authorization/check-a-permission/php/check.php
require __DIR__ . '/../../../php/vendor/autoload.php';
use LumoAuth\LumoAuth;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
$lumo = new LumoAuth();
$permission = getenv('PERMISSION') ?: 'documents.edit';
foreach (['editor' => getenv('EDITOR_USER_ID'), 'reader' => getenv('READER_USER_ID')] as $who => $userId) {
// The key asks about another person, so it names that person as the subject.
$allowed = $lumo->permissions->check($permission, userId: $userId);
printf("%s: %s -> %s\n", $who, $permission, $allowed ? 'allowed' : 'denied');
}
php authorization/check-a-permission/php/check.php
authorization/check-a-permission/java/CheckPermission.java
// Ask LumoAuth whether a person holds a permission.
//
// java -cp "java/lib/*" authorization/check-a-permission/java/CheckPermission.java
import io.lumoauth.LumoAuth;
import io.lumoauth.model.CheckOptions;
public class CheckPermission {
public static void main(String[] args) {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
LumoAuth lumo = LumoAuth.fromEnvironment();
String permission = System.getenv().getOrDefault("PERMISSION", "documents.edit");
for (String who : new String[] {"EDITOR", "READER"}) {
// The key asks about another person, so it names that person as the subject.
boolean allowed = lumo.permissions().check(permission, CheckOptions.forUser(System.getenv(who + "_USER_ID")));
System.out.printf("%s: %s -> %s%n", who.toLowerCase(), permission, allowed ? "allowed" : "denied");
}
}
}
java -cp "java/lib/*" authorization/check-a-permission/java/CheckPermission.java
authorization/check-a-permission/csharp/CheckPermission.cs
#:package LumoAuth@1.7.0
#:property PublishAot=false
// Ask LumoAuth whether a person holds a permission.
//
// dotnet run authorization/check-a-permission/csharp/CheckPermission.cs
using LumoAuth;
using LumoAuth.Models;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
var lumo = LumoAuthClient.FromEnvironment();
var permission = Environment.GetEnvironmentVariable("PERMISSION") ?? "documents.edit";
foreach (var who in new[] { "EDITOR", "READER" })
{
// The key asks about another person, so it names that person as the subject.
var userId = Environment.GetEnvironmentVariable($"{who}_USER_ID")!;
var allowed = await lumo.Permissions.CheckAsync(permission, CheckOptions.ForUser(userId));
Console.WriteLine($"{who.ToLowerInvariant()}: {permission} -> {(allowed ? "allowed" : "denied")}");
}
dotnet run authorization/check-a-permission/csharp/CheckPermission.cs
authorization/check-a-permission/http/check.sh
#!/bin/sh
# Ask LumoAuth whether a person holds a permission, with curl.
#
# sh authorization/check-a-permission/http/check.sh
set -eu
PERMISSION="${PERMISSION:-documents.edit}"
for USER_ID in "$EDITOR_USER_ID" "$READER_USER_ID"; do
# The check endpoint is not under /orgs/{org}: the API key names the organization.
curl --silent --show-error "$LUMOAUTH_URL/api/v1/authz/check" \
--header "X-API-Key: $LUMOAUTH_API_KEY" \
--header "Content-Type: application/json" \
--data "{\"permission\": \"$PERMISSION\", \"subject\": {\"type\": \"user\", \"id\": \"$USER_ID\"}}"
echo
done
sh authorization/check-a-permission/http/check.sh
Check the result
Output
editor: documents.edit -> allowed
reader: documents.edit -> denied
- Remove the role from the editor in the portal, and run the program again: both answers are now "denied".
- To see which role gives a person a permission, use the Test access page of the portal, under Access control.
Limits
- The subject is the ID of a user (a UUID), not an email address.
- To protect the routes of your own API in the same way, see Protect routes in each framework. It also asks with an API key and names the person who calls.
- A person can also hold a permission through a group. The answer is the same: see Give roles through groups.