Decide by attributes
Allow an action by the attributes of the person and of the resource: department, clearance, working hours, network.
What it shows
- The setup script defines three attributes: the department of a person, the department of a record, and a legal hold on a record.
- It writes two policies. A person of cardiology may read a record of cardiology. Nobody may read a record on legal hold.
- The program stores the values: the department of the caller, and the attributes of three records.
- It asks about each record. The request names only the resource and the action, and LumoAuth reads the stored values.
- The record on legal hold is refused, because a deny policy wins over every allow policy.
LumoAuth also adds the time and the address of the request itself. A policy can read them, for example as environment.hour and environment.ip.
Before you start
- Check that your plan includes fine-grained authorization in the plans matrix.
- An API key with the scope
admin:abac:write, for the setup script. Create it in the portal: open API keys, under Applications & developer tools. - An application that may ask for the scopes
abac:readandabac:write. In the portal, open Applications, your application, Configuration, and add both to Allowed scopes. - The access token of an administrator who signed in through that application with both scopes. The Express sign-in recipe has an application that you can use for this.
The checks answer for the person who holds the token, and an API key cannot make them. Storing a value needs the permission abac.manage. So in this recipe one administrator stores the values and asks the questions. In your app, an administrator stores the values, and each person asks with their own token and the scope abac: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. |
LUMOAUTH_API_KEY | An API key with the scope admin:abac:write. Only the setup script uses it. |
USER_ACCESS_TOKEN | The access token of a signed-in administrator, with the scopes abac:read and abac:write. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node authorization/attribute-policies/setup.mjs
setup.mjs
// Creates what the recipe needs: three attribute definitions and two
// policies. Run it again at any time.
//
// node authorization/attribute-policies/setup.mjs
//
// The API key needs the scope admin:abac:write. The person who created the
// key must be an administrator of the organization.
import { ensure } from '../../_lib/admin.mjs';
const attribute = (attributeType, slug, name, dataType, extra = {}) =>
ensure('/abac/attributes', (a) => a.slug === slug && a.attributeType === attributeType, {
name,
slug,
attributeType,
dataType,
...extra,
});
await attribute('user', 'department', 'Department', 'string', {
description: 'The department that the person works in.',
});
await attribute('resource', 'record_department', 'Department of the record', 'string', {
description: 'The department that the record belongs to.',
});
// A record with no stored value is not on legal hold.
await attribute('resource', 'legal_hold', 'Legal hold', 'boolean', {
description: 'Nobody may read a record on legal hold.',
defaultValue: false,
});
// A condition compares one attribute with a fixed value, so each department
// gets its own policy.
await ensure('/abac/policies', (p) => p.name === 'Cardiology reads its records', {
name: 'Cardiology reads its records',
description: 'A person of cardiology may read a record of cardiology.',
resourceType: 'record',
action: 'read',
effect: 'allow',
priority: 100,
conditions: {
operator: 'AND',
conditions: [
{ subject: 'user.department', operator: 'equals', value: 'cardiology' },
{ subject: 'resource.record_department', operator: 'equals', value: 'cardiology' },
],
},
});
// A deny policy wins over every allow policy.
await ensure('/abac/policies', (p) => p.name === 'No reading on legal hold', {
name: 'No reading on legal hold',
description: 'Nobody may read a record on legal hold.',
resourceType: 'record',
action: 'read',
effect: 'deny',
priority: 200,
conditions: {
operator: 'AND',
conditions: [{ subject: 'resource.legal_hold', operator: 'equals', value: true }],
},
});
console.log('Three attribute definitions and two policies are ready.');
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. The curl version prints the JSON answers of the three checks and of the bulk check.
- Node.js
- Python
- Go
- PHP
- Java
- C#
- curl
// Set attributes on a person and on three records, then ask LumoAuth which
// records the person may read.
//
// node authorization/attribute-policies/js/records.mjs
import { LumoAuthBackend } from '@lumoauth/backend';
// These calls take the access token of a signed-in person, not an API key.
const lumo = new LumoAuthBackend({
baseUrl: process.env.LUMOAUTH_URL,
orgId: process.env.LUMOAUTH_ORG_ID,
secretKey: process.env.USER_ACCESS_TOKEN,
});
const department = process.env.DEPARTMENT ?? 'cardiology';
// The policies read stored values. An administrator sets them.
const me = await lumo.abac.getMyAttributes();
await lumo.abac.setUserAttribute(me.user_id, 'department', department);
await lumo.abac.setResourceAttribute('record', 'rec-1001', 'record_department', 'cardiology');
await lumo.abac.setResourceAttribute('record', 'rec-2001', 'record_department', 'oncology');
await lumo.abac.setResourceAttribute('record', 'rec-1002', 'record_department', 'cardiology');
await lumo.abac.setResourceAttribute('record', 'rec-1002', 'legal_hold', true);
console.log(`department of the caller: ${department}`);
const records = ['rec-1001', 'rec-2001', 'rec-1002'];
// The request names the resource and the action. The answer is about the caller.
for (const resourceId of records) {
const decision = await lumo.abac.check({ resourceType: 'record', resourceId, action: 'read' });
console.log(`read ${resourceId} -> ${decision.allowed ? 'allowed' : 'denied'} (${decision.reason})`);
}
// One request for the three records.
const bulk = await lumo.abac.checkBulk({
checks: records.map((resourceId) => ({ resourceType: 'record', resourceId, action: 'read' })),
});
console.log(`bulk: ${bulk.results.map((r) => `${r.resourceId} ${r.allowed ? 'allowed' : 'denied'}`).join(', ')}`);
node authorization/attribute-policies/js/records.mjs
Run against a LumoAuth organization.
"""Set attributes on a person and on three records, then ask LumoAuth which
records the person may read.
python authorization/attribute-policies/python/records.py
"""
import os
from lumoauth import LumoAuth
# These calls take the access token of a signed-in person, not an API key.
lumo = LumoAuth(token_provider=lambda: os.environ["USER_ACCESS_TOKEN"])
department = os.environ.get("DEPARTMENT", "cardiology")
# The policies read stored values. An administrator sets them.
me = lumo.abac.get_my_attributes()
lumo.abac.set_user_attribute(me["user_id"], "department", department)
lumo.abac.set_resource_attribute("record", "rec-1001", "record_department", "cardiology")
lumo.abac.set_resource_attribute("record", "rec-2001", "record_department", "oncology")
lumo.abac.set_resource_attribute("record", "rec-1002", "record_department", "cardiology")
lumo.abac.set_resource_attribute("record", "rec-1002", "legal_hold", True)
print(f"department of the caller: {department}")
records = ["rec-1001", "rec-2001", "rec-1002"]
# The request names the resource and the action. The answer is about the caller.
for resource_id in records:
decision = lumo.abac.check("record", "read", resource_id=resource_id)
print(f"read {resource_id} -> {'allowed' if decision['allowed'] else 'denied'} ({decision['reason']})")
# One request for the three records.
bulk = lumo.abac.check_bulk([{"resource_type": "record", "resource_id": r, "action": "read"} for r in records])
print("bulk: " + ", ".join(f"{r['resourceId']} {'allowed' if r['allowed'] else 'denied'}" for r in bulk["results"]))
python authorization/attribute-policies/python/records.py
Run against a LumoAuth organization.
// Set attributes on a person and on three records, then ask LumoAuth which
// records the person may read.
//
// go run ./authorization/attribute-policies/go
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func answer(allowed bool) string {
if allowed {
return "allowed"
}
return "denied"
}
func must(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
// These calls take the access token of a signed-in person, not an API key.
client, err := lumoauth.New(lumoauth.WithAccessToken(os.Getenv("USER_ACCESS_TOKEN")))
must(err)
ctx := context.Background()
department := os.Getenv("DEPARTMENT")
if department == "" {
department = "cardiology"
}
// The policies read stored values. An administrator sets them.
me, err := client.Abac.MyAttributes(ctx)
must(err)
must(client.Abac.SetUserAttribute(ctx, me["user_id"].(string), "department", department))
must(client.Abac.SetResourceAttribute(ctx, "record", "rec-1001", "record_department", "cardiology"))
must(client.Abac.SetResourceAttribute(ctx, "record", "rec-2001", "record_department", "oncology"))
must(client.Abac.SetResourceAttribute(ctx, "record", "rec-1002", "record_department", "cardiology"))
must(client.Abac.SetResourceAttribute(ctx, "record", "rec-1002", "legal_hold", true))
fmt.Printf("department of the caller: %s\n", department)
records := []string{"rec-1001", "rec-2001", "rec-1002"}
// The request names the resource and the action. The answer is about the caller.
checks := []lumoauth.AbacCheckParams{}
for _, resourceID := range records {
check := lumoauth.AbacCheckParams{ResourceType: "record", ResourceID: resourceID, Action: "read"}
decision, err := client.Abac.Check(ctx, check)
must(err)
fmt.Printf("read %s -> %s (%s)\n", resourceID, answer(decision.Allowed), decision.Reason)
checks = append(checks, check)
}
// One request for the three records.
decisions, err := client.Abac.CheckBulk(ctx, checks)
must(err)
answers := []string{}
for _, decision := range decisions {
answers = append(answers, decision.ResourceID+" "+answer(decision.Allowed))
}
fmt.Printf("bulk: %s\n", strings.Join(answers, ", "))
}
go run ./authorization/attribute-policies/go
Compiles. Not run against an organization. The program stops at the first check with a matched policy: this version of the Go SDK expects the ID of a policy as text, and LumoAuth sends a number.
<?php
// Set attributes on a person and on three records, then ask LumoAuth which
// records the person may read.
//
// php authorization/attribute-policies/php/records.php
require __DIR__ . '/../../../php/vendor/autoload.php';
use LumoAuth\LumoAuth;
// These calls take the access token of a signed-in person, not an API key.
$lumo = new LumoAuth(tokenProvider: fn () => getenv('USER_ACCESS_TOKEN'));
$department = getenv('DEPARTMENT') ?: 'cardiology';
// The policies read stored values. An administrator sets them.
$me = $lumo->abac->myAttributes();
$lumo->abac->setUserAttribute($me['user_id'], 'department', $department);
$lumo->abac->setResourceAttribute('record', 'rec-1001', 'record_department', 'cardiology');
$lumo->abac->setResourceAttribute('record', 'rec-2001', 'record_department', 'oncology');
$lumo->abac->setResourceAttribute('record', 'rec-1002', 'record_department', 'cardiology');
$lumo->abac->setResourceAttribute('record', 'rec-1002', 'legal_hold', true);
printf("department of the caller: %s\n", $department);
$records = ['rec-1001', 'rec-2001', 'rec-1002'];
// The request names the resource and the action. The answer is about the caller.
foreach ($records as $resourceId) {
$decision = $lumo->abac->check('record', 'read', $resourceId);
printf("read %s -> %s (%s)\n", $resourceId, $decision['allowed'] ? 'allowed' : 'denied', $decision['reason']);
}
// One request for the three records.
$bulk = $lumo->abac->checkBulk(array_map(
fn ($resourceId) => ['resourceType' => 'record', 'resourceId' => $resourceId, 'action' => 'read'],
$records,
));
$answers = array_map(fn ($r) => $r['resourceId'] . ' ' . ($r['allowed'] ? 'allowed' : 'denied'), $bulk['results']);
printf("bulk: %s\n", implode(', ', $answers));
php authorization/attribute-policies/php/records.php
Run against a LumoAuth organization.
// Set attributes on a person and on three records, then ask LumoAuth which
// records the person may read.
//
// java -cp "java/lib/*" authorization/attribute-policies/java/ReadRecords.java
import io.lumoauth.LumoAuth;
import io.lumoauth.model.AbacCheck;
import io.lumoauth.model.AbacDecision;
import java.util.ArrayList;
import java.util.List;
public class ReadRecords {
public static void main(String[] args) {
// These calls take the access token of a signed-in person, not an API key.
LumoAuth lumo = LumoAuth.builder().accessToken(System.getenv("USER_ACCESS_TOKEN")).build();
String department = System.getenv().getOrDefault("DEPARTMENT", "cardiology");
// The policies read stored values. An administrator sets them.
String userId = (String) lumo.abac().myAttributes().get("user_id");
lumo.abac().setUserAttribute(userId, "department", department);
lumo.abac().setResourceAttribute("record", "rec-1001", "record_department", "cardiology");
lumo.abac().setResourceAttribute("record", "rec-2001", "record_department", "oncology");
lumo.abac().setResourceAttribute("record", "rec-1002", "record_department", "cardiology");
lumo.abac().setResourceAttribute("record", "rec-1002", "legal_hold", true);
System.out.printf("department of the caller: %s%n", department);
List<AbacCheck> checks = List.of(
AbacCheck.of("record", "read", "rec-1001"),
AbacCheck.of("record", "read", "rec-2001"),
AbacCheck.of("record", "read", "rec-1002"));
// The request names the resource and the action. The answer is about the caller.
for (AbacCheck check : checks) {
AbacDecision decision = lumo.abac().check(check);
System.out.printf("read %s -> %s (%s)%n", check.resourceId(), decision.allowed() ? "allowed" : "denied", decision.reason());
}
// One request for the three records. The answers come in the order of the questions.
List<AbacDecision> decisions = lumo.abac().checkBulk(checks);
List<String> answers = new ArrayList<>();
for (int i = 0; i < checks.size(); i++) {
answers.add(checks.get(i).resourceId() + " " + (decisions.get(i).allowed() ? "allowed" : "denied"));
}
System.out.printf("bulk: %s%n", String.join(", ", answers));
}
}
java -cp "java/lib/*" authorization/attribute-policies/java/ReadRecords.java
Run against a LumoAuth organization.
#:package LumoAuth@1.7.0
#:property PublishAot=false
// Set attributes on a person and on three records, then ask LumoAuth which
// records the person may read.
//
// dotnet run authorization/attribute-policies/csharp/ReadRecords.cs
using LumoAuth;
using LumoAuth.Models;
// These calls take the access token of a signed-in person, not an API key.
var lumo = new LumoAuthClient(new LumoAuthOptions
{
AccessToken = Environment.GetEnvironmentVariable("USER_ACCESS_TOKEN"),
});
var department = Environment.GetEnvironmentVariable("DEPARTMENT") ?? "cardiology";
// The policies read stored values. An administrator sets them.
var me = await lumo.Abac.MyAttributesAsync();
await lumo.Abac.SetUserAttributeAsync(me["user_id"].GetString()!, "department", department);
await lumo.Abac.SetResourceAttributeAsync("record", "rec-1001", "record_department", "cardiology");
await lumo.Abac.SetResourceAttributeAsync("record", "rec-2001", "record_department", "oncology");
await lumo.Abac.SetResourceAttributeAsync("record", "rec-1002", "record_department", "cardiology");
await lumo.Abac.SetResourceAttributeAsync("record", "rec-1002", "legal_hold", true);
Console.WriteLine($"department of the caller: {department}");
var checks = new[] { "rec-1001", "rec-2001", "rec-1002" }
.Select(resourceId => new AbacCheck("record", "read", resourceId))
.ToList();
// The request names the resource and the action. The answer is about the caller.
foreach (var check in checks)
{
var decision = await lumo.Abac.CheckAsync(check);
Console.WriteLine($"read {check.ResourceId} -> {(decision.Allowed ? "allowed" : "denied")} ({decision.Reason})");
}
// One request for the three records.
var decisions = await lumo.Abac.CheckBulkAsync(checks);
var answers = decisions.Select(d => $"{d.ResourceId} {(d.Allowed ? "allowed" : "denied")}");
Console.WriteLine($"bulk: {string.Join(", ", answers)}");
dotnet run authorization/attribute-policies/csharp/ReadRecords.cs
Compiles. Not run against an organization. The program stops at the first check with a matched policy: this version of the .NET SDK expects the ID of a policy as text, and LumoAuth sends a number.
#!/bin/sh
# Set attributes on three records, then ask LumoAuth which records the caller
# may read, with curl.
#
# sh authorization/attribute-policies/http/records.sh
set -eu
ABAC="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1/abac"
DEPARTMENT="${DEPARTMENT:-cardiology}"
# These calls take the access token of a signed-in person, not an API key.
abac() {
method="$1"; path="$2"; shift 2
curl --silent --show-error --request "$method" "$ABAC$path" \
--header "Authorization: Bearer $USER_ACCESS_TOKEN" --header "Content-Type: application/json" "$@"
}
# The policies read stored values. An administrator sets them.
USER_ID=$(abac GET /my-attributes | sed -n 's/.*"user_id":"\([^"]*\)".*/\1/p')
abac PUT "/users/$USER_ID/attributes/department" --data "{\"value\": \"$DEPARTMENT\"}" > /dev/null
abac PUT /resources/record/rec-1001/attributes/record_department --data '{"value": "cardiology"}' > /dev/null
abac PUT /resources/record/rec-2001/attributes/record_department --data '{"value": "oncology"}' > /dev/null
abac PUT /resources/record/rec-1002/attributes/record_department --data '{"value": "cardiology"}' > /dev/null
abac PUT /resources/record/rec-1002/attributes/legal_hold --data '{"value": true}' > /dev/null
# The request names the resource and the action. The answer is about the caller.
for RECORD in rec-1001 rec-2001 rec-1002; do
abac POST /check --data "{\"resourceType\": \"record\", \"resourceId\": \"$RECORD\", \"action\": \"read\"}"
echo
done
# One request for the three records.
abac POST /check-bulk --data '{"checks": [
{"resourceType": "record", "resourceId": "rec-1001", "action": "read"},
{"resourceType": "record", "resourceId": "rec-2001", "action": "read"},
{"resourceType": "record", "resourceId": "rec-1002", "action": "read"}
]}'
echo
sh authorization/attribute-policies/http/records.sh
Run against a LumoAuth organization.
Check the result
department of the caller: cardiology
read rec-1001 -> allowed (Access allowed by policy: Cardiology reads its records)
read rec-2001 -> denied (No matching policies - default deny)
read rec-1002 -> denied (Access denied by policy: No reading on legal hold)
bulk: rec-1001 allowed, rec-2001 denied, rec-1002 denied
- Change the department of the caller: run the program again with
DEPARTMENT=oncology. The first record is now refused too, because no policy allows oncology anything. - In the portal, open Attribute rules under Access control. The Policy tester shows which policies matched for a person and a request.
Limits
- A condition compares one attribute with a fixed value. It cannot compare two attributes, such as "the department of the person equals the department of the record". Write one policy for each department.
- A check answers only for the person who holds the token. An API key cannot ask, and it cannot store a value on a person or on a resource.
- A check cannot send the attributes of the resource. LumoAuth reads the stored values. A request can send only the environment attributes that you defined.
- When no policy matches, the answer is "denied".
environment.ipis the address of the request that LumoAuth received. When your backend makes the call, that is the address of your backend.- Only a full administrator may store an attribute on their own account.