AllowedBy SDK for C# and .NET#
This guide shows how a service written in C# accepts AI agents that act for a person. The concepts (routes, classes,
levels, the approval flow, the context) are explained once in docs/deploy-saas.md; this guide
shows them in C#. The SDK is in sdks/dotnet. It follows sdks/CONTRACT.md
and implements spec set 0.2.14.
Terms used below: a node issues agent passports and serves the approval page; a grant is a person's signed approval; a proof is a JWT (JSON Web Token) the agent signs for each request; ABY-2 is the specification of how a service verifies requests.
Install#
Answer: reference AllowedBy.AspNetCore (it brings AllowedBy); add AllowedBy.Redis for several instances.
The packages are not published on NuGet yet. Until they are, reference the projects from a clone next to your project (the same commands on Windows):
dotnet add reference ../allowedby/sdks/dotnet/src/AllowedBy.AspNetCore/AllowedBy.AspNetCore.csproj
dotnet add reference ../allowedby/sdks/dotnet/src/AllowedBy.Redis/AllowedBy.Redis.csprojOnce published: dotnet add package AllowedBy.AspNetCore and dotnet add package AllowedBy.Redis.
| Package | What | Depends on |
|---|---|---|
AllowedBy |
The core: configuration, route map, discovery documents, verification (ABY-2 §5), challenges, stores. No web framework. | BouncyCastle.Cryptography 2.5.1 |
AllowedBy.AspNetCore |
AddAllowedBy, UseAllowedBy, HttpContext.GetAllowedBy(), [FromAllowedBy], the background refresh. |
ASP.NET Core shared framework |
AllowedBy.Redis |
RedisStore: the store shared by every instance. |
StackExchange.Redis 2.8.16 |
Why each dependency:
- BouncyCastle.Cryptography (pinned 2.5.1): Ed25519 (EdDSA) signatures, which the .NET base class library does not
have. It is pure managed code (no native library to ship or patch), so it runs the same in any container. NSec
would need libsodium binaries. Everything else comes from the base class library: ECDSA P-256 (ES256), ECDH, SHA-256,
zlib,
System.Text.Json. - StackExchange.Redis (pinned 2.8.16, only in
AllowedBy.Redis): the standard Redis client for .NET.
Runtimes: the packages target net8.0 and run on .NET 8 and every later runtime; CI tests .NET 8 and .NET 10 on
Linux and .NET 10 on Windows. .NET 8 left Microsoft support on 2026-11-10: use .NET 10 (LTS) for new services.
Quick start#
Answer: AddAllowedBy(o => ...), app.UseAllowedBy(), and take AllowedByContext in your handler.
using AllowedBy;
using AllowedBy.AspNetCore;
using static AllowedBy.Routes;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAllowedBy(o =>
{
o.Origin = builder.Configuration["ALLOWEDBY_ORIGIN"]!; // your app's public URL
o.Node = builder.Configuration["ALLOWEDBY_NODE"]!; // the node you trust: people approve there
o.Org = new AllowedByOrg { LegalName = "Notes Ltd", Country = "FR" };
o.Routes = [Route("GET", "/notes", "notes:read", level: 1, resource: "note:*")];
o.Templates["notes:read"] = "Read your notes"; // what the person approves
});
var app = builder.Build();
app.UseAllowedBy();
app.MapGet("/notes", (AllowedByContext ctx) => new { notes = Array.Empty<string>(), person = ctx.HumanId });
app.Run();This is sdks/dotnet/examples/Recipes/Quickstart/Program.cs; CI runs it against a real node, agent and person.
See it work against the local node. In one terminal, start the demo (node on port 8700):
pip install -r requirements.txt
python demo/run.py --port 8700In another, run the app:
export ALLOWEDBY_ORIGIN=http://localhost:5000 ALLOWEDBY_NODE=http://localhost:8700
dotnet run --project sdks/dotnet/examples/Recipes/Quickstart --urls http://localhost:5000The same on Windows (PowerShell):
$env:ALLOWEDBY_ORIGIN = "http://localhost:5000"; $env:ALLOWEDBY_NODE = "http://localhost:8700"
dotnet run --project sdks/dotnet/examples/Recipes/Quickstart --urls http://localhost:5000Call it without a passport:
curl -i http://localhost:5000/.well-known/allowedby
curl -i http://localhost:5000/notesThe second call answers 401 passport_required with WWW-Authenticate: AllowedBy realm="localhost:5000", ...: the
route is protected. An agent (the Python or TypeScript agent SDK) gets a passport from the node, is challenged, asks
the person, and retries with the grant. The app in Docker instead:
docker run --rm --network host -v "$PWD":/src -w /src \
-e ALLOWEDBY_ORIGIN=http://localhost:5000 -e ALLOWEDBY_NODE=http://localhost:8700 \
mcr.microsoft.com/dotnet/sdk:10.0 \
dotnet run --project sdks/dotnet/examples/Recipes/Quickstart --urls http://localhost:5000With the hosted node instead of a local one, set ALLOWEDBY_NODE=https://demo.allowedby.com and ALLOWEDBY_ORIGIN to
your public origin (the node must reach your /.well-known/allowedby).
Routes and templates#
Answer: each route names a method, a path, a capability, a class and a level; each capability has the sentence the person signs.
Routes.Route(method, path, capability, cls, level, resource, ...) takes the same arguments as Python's route() and
validates them at once (an ArgumentException says what to fix). Requests whose method and path are not in the map
reach your app unchanged, without a context.
| Argument | Meaning |
|---|---|
method, path |
GET, POST, PUT, PATCH, DELETE; {name} is one path segment. HEAD is checked as GET. Literal segments match without case and empty segments (a trailing or doubled slash) are ignored, as ASP.NET Core routing does, so no spelling of a protected path reaches your handler unchecked. |
capability |
namespace:action, e.g. notes:read. null for a level-0 route (the agent's passport is enough): a level-0 route with a capability fails construction. |
cls |
read, write, write-hard, irreversible (ABY-3 §4). For write-hard and irreversible the SDK creates the approval itself, bound to this exact request (single use). |
level |
0 (agent only), 1 (passkey), 2 (verified identity), 3 (eIDAS high, hardware passkey). |
resource |
What the call acts on, e.g. note:{id}; default <namespace>:*. The grant's scope must cover it. |
amountField, currencyField |
JSON pointers into the body (/total, default /currency): the grant must cap the amount. |
classByAmount |
Thresholds instead of cls: [new() { UpTo = "1000.00", Class = "write-hard" }, new() { Class = "irreversible" }]. |
authn |
Minimum passkey class: synced or hardware. |
tier |
Minimum custody tier of the agent's key (OAID-3). |
maxLifetime |
Longest grant lifetime in seconds (60 s to 30 days; default the class's: 30 days, 7 days, 24 h, 1 h). |
levelProfile |
On a level-3 route: eu or na (OAID-7 §5.3). See Level profiles. |
nonce |
An AllowedBy-Nonce on this route, whatever its class (ABY-2 §3.2). Needs the service option Nonce: construction fails without it. See AllowedBy-Nonce. |
qes |
A qualified electronic signature. Not supported yet (it needs an EU trusted list): true fails construction. |
requireLink, accountParam |
The person must have linked their identity to one of your accounts (ABY-3 §6), and, on a path with the accountParam parameter (default account), to that account: 403 human_not_linked otherwise. Level 1 or more: on a level-0 route it fails construction. An accountParam you set must be a parameter of the path, as written (one that differs only by case fails construction). See Account linking. |
summary, body |
What the operation does and its body members, published in /openapi.json. |
Templates are the only source of the text the person signs (AMH-1 §4). A string is English for both the summary and
the line; for several languages give Summary and Lines per language code. Placeholders: {scope},
{amount.max}, {amount.currency}, {amount.per}, {fields}.
Inside AddAllowedBy (from sdks/dotnet/examples/Production/Program.cs):
o.Templates["notes:read"] = "Read your notes"; // English, for the summary and the line
o.Templates["invoices:pay"] = new AllowedByTemplate
{
Summary = new Dictionary<string, string>
{
["en"] = "Pay {scope}, up to {amount.max} {amount.currency}",
["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}",
},
Lines = new Dictionary<string, string>
{
["en"] = "Pay {scope}, up to {amount.max} {amount.currency}",
["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}",
},
};Options the Python reference accepts and this SDK does not enforce yet (Mandate, Disclose, DiscloseOptional,
Authority, Qes) make construction fail with a message naming the option: accepting an option and not enforcing it
would fail open.
Account linking#
Answer: your signed-in account page calls aby.LinkStart(account) and shows the code; the person gives it to their
agent, which sends it to POST /allowedby/link; their approval then links their identity to that account, and routes
with requireLink: true accept only a linked person (ABY-3 §6; an extended feature of sdks/CONTRACT.md).
-
The code.
LinkStart(account, ttl = 600)returns a code for one of your accounts (its id, 1 to 256 characters): 96 random bits, single use, validttlseconds (1 to 86400). A new code revokes no older one. Show it only to the signed-in owner of the account. -
The request. The agent sends
POST /allowedby/linkwith{"code": "<code>"}. The SDK serves this route itself (UseAllowedBy()answers it before routing; your app never sees it) and publishes it in its route map (aby:link, class write, level 1). An unknown, spent, revoked or expired code is refused with400 invalid_requestbefore any approval is asked for. Then the request is checked as any route, with a single-use approval only: the SDK creates it at the node (as for write-hard routes) and the person approves it with a passkey tap. -
The link. Accepted, the code is spent, the account's other pending codes are revoked, and the pair (the person's home node, their pairwise id for your origin) is linked to the code's account, in place of any person linked to it before (one person per account, one account per person). The answer is
200 {"linked": true}. -
The routes. On a route with
requireLink: true, a person who has not linked is refused with403 human_not_linked. When the path has theaccountParamparameter (defaultaccount), only the person linked to that account is accepted. Both members of the pair count: the same pairwise id from another home node is another person. An approval that names no person for your origin (nohuman.idfor it) is refused with401 grant_insufficient, here and onPOST /allowedby/link: an empty id would match every such approval. Under rule 5, a route covers arequireLinkroute whose path names the account only with the same parameter in the same segment. The context names the account (LinkedAccount). The approvals the SDK creates for such a route name the linked person (human_hint). -
Your authorisation. A route whose path names no account accepts any linked person. To decide yourself, set
o.LinkAuthorize = (account, route, values) => ...(Python'slink_authorize): onlytruepasses;false, or an exception it throws, refuses with403 human_not_linked. It is called only for a linked person (and only for the account the path names, when it names one), with the route and its path values, decoded once. -
Removing a link. When you delete an account, or the person asks to be forgotten, call
aby.Unlink(account)(ABY-3 §6, Removing a link): the stored pair and the account's pending codes go, so a code issued before cannot re-link it. ArequireLinkroute then refuses the person (403 human_not_linked) until they link again with a new code. It returns whether the account was linked (an unknown account is a no-op,false), and throwsArgumentExceptionfor an accountLinkStartrefuses.
From sdks/dotnet/examples/interop_ext/Program.cs, which sdks/interop/ext/interop_ext.py runs against a real node:
Route("GET", "/accounts/{account}/notes", "notes:read", level: 1, resource: "account:{account}",
requireLink: true, summary: "List the notes of an account"),Limits: codes and links are kept in the process's memory, bounded (10,000 pending codes, 100,000 links, the oldest
link dropped first). With several instances each keeps its own: link on the instance that serves the account page,
or run one. When 10,000 codes are pending, LinkStart throws InvalidOperationException: catch it, and show one code
per visit of the account page (not one per reload). Without ASP.NET Core (HttpListener), answer POST /allowedby/link yourself: when aby.IsLinkRequest(method, path), send what await aby.LinkAsync(request) returns, before
CheckAsync. Only the exact path as sent, /allowedby/link, is the endpoint: any other spelling (a trailing or
doubled slash, a dot segment, an encoded letter, another letter case) asks for no approval and links nothing, even with
a valid code, and CheckAsync refuses it (400 invalid_request, no challenge).
AllowedBy-Nonce#
Answer: o.Nonce = true makes every irreversible route, and each route with nonce: true, refuse a proof without a
current service nonce, so a proof captured earlier cannot be sent again later (ABY-2 §3.2).
- The refusal. Without a current nonce the request gets
401 invalid_signatureand a fresh nonce in theAllowedBy-Nonceresponse header. The agent signs again with it (the proof'snonceclaim) and retries once, whatever the route's class. With the RFC 9421 profile (o.Rfc9421), the nonce is the request'sAllowedBy-Nonceheader, and counts only when the signature covers it; a covered value that is no base64url nonce is401. - The nonces. A nonce is current for 300 s from its issue. Nothing is stored: a nonce is its issue time and a MAC
of it, under a key derived from the signing key (HKDF-SHA256,
sdks/CONTRACT.md, Extended: AllowedBy-Nonce). With aKeyFile, every instance takes the others' nonces, a restart keeps them current, and so does an SDK of any other language on the same key file. Without one, the key is new at each start. - Configuration. A route with
nonce: truewhileo.Nonceis off fails construction, naming the route.
Level profiles#
Answer: on a level-3 route, levelProfile: "eu" or "na" accepts only a person whose level 3 comes from that profile
(OAID-7 §5.3); another profile, or none, is 401 level_insufficient. Without it, a level-3 route accepts either
profile.
Rate limits#
Answer: every agent (the passport's sub) and every operator (operator.id) may make at most a given number of calls
in a sliding window; one more is refused with 429 rate_limited and Retry-After: 60.
- Defaults. 600 calls per 60 s per agent, 6000 per operator. Set them with
o.Rate, for examplenew Dictionary<string, int[]> { ["actor"] = [20, 60], ["operator"] = [1000, 60] }. Any other key, or a value that is not two positive integers (calls, seconds), fails construction: a misspelt limit would leave the default in place. - What counts. A call counts once its proof is verified and is no replay, whatever is decided after it (a call
refused as
grant_requiredcounts); a call refused by a limit counts for neither. The window slides ono.Clock: a call at t sees those at x with t - x < seconds. - Limits. The counts are kept in the process's memory (10,000 agents and operators at most, the least recent dropped first): with several instances, each counts its own calls.
From sdks/dotnet/examples/interop_ext/Program.cs, which sdks/interop/ext/interop_ext.py runs against a real node:
Route("POST", "/drafts", "drafts:write", cls: "write", level: 1, resource: "draft:new", nonce: true,
summary: "Save a draft", body: new Dictionary<string, string> { ["text"] = "the draft" }),
Route("GET", "/vault/eu/{id}", "vault:read", level: 3, resource: "vault:{id}", authn: "hardware",
levelProfile: "eu", summary: "Open a vault (EU level 3)"),
Route("GET", "/vault/na/{id}", "vault:read", level: 3, resource: "vault:{id}", authn: "hardware",
levelProfile: "na", summary: "Open a vault (North-America level 3)"),
];
o.Nonce = true; // AllowedBy-Nonce on /drafts and on every irreversible route
o.Rate = new Dictionary<string, int[]> { ["actor"] = [20, 60], ["operator"] = [1000, 60] };Tenants#
Answer: one service, several customers. A route whose path has the parameter tenant serves the tenant it names, and
o.Tenants lets each tenant tighten that route, never loosen it (ORG-1 §3.3).
- Overrides,
Routes[capability]:Level(the higher of the route's and the tenant's counts),Authn(the stronger),RequireLink(raises a level-0 route to level 1),MaxLifetime(the shorter),AmountMax(the lower: above it,403 capability_denied),Operators(an allowlist ofoperator.id: any other operator gets403 capability_denied). A tenant's resources stay its own: name the tenant in the resource (tenant:{tenant}:...), and an approval for one tenant never reaches another's. - Mandates.
Mandate = trueasks for a company mandate on the routes of that capability.MembersOnly = truewith anOrgasks for one on every route of the tenant, level-0 routes included. Until this SDK verifies mandates (CONTRACT: company mandates), such a tenant route refuses every request with401 mandate_required. The refusal comes before any other check and carries no challenge, so nobody is asked for an approval that could not pass.QesandAuthorityfail construction (not supported yet). - Validation. When the service is built: a tenant id of 1-64 letters, digits,
_or-; aNameof 1-200 characters; anOrgthat is an https origin with no path; capabilities of the route map; values of their shape. An override or a budget on a capability that has a route without{tenant}is refused, naming the route: it would never apply. The option is copied, so changing your objects afterwards changes nothing. In configuration, onlyName,OrgandMembersOnlycan be set (a capability, with its:, cannot be a configuration key): setRoutesandBudgetsin code; any other key underTenantsstops the app at startup.
Tenant budgets#
Answer: Budgets[capability] = new() { Max = "100.00", Currency = "EUR", Per = "day" } caps the amounts the service
accepts for a tenant per calendar day, week (from Monday) or month, in Tz (an IANA time zone, default UTC; ORG-1
§5.3).
- What counts. Every route with that capability has an
AmountField(else construction fails). An accepted request counts its amount in the store, in one call that checks and counts, so every instance on a shared store (Redis) shares the count. A request without an amount in the budget's currency (never converted), or over what is left, is refused with403 budget_exceeded, before any challenge: no approval is asked for. A refused request is not counted. - Giving back. When your handler refuses an accepted request (a wrong total, an unknown invoice), call
await aby.RefundBudgetAsync(HttpContext.GetAllowedBy()!): the amount is given back, once. The SDK's own refusals after the check give it back themselves. - The store. When the store does not answer, the request gets
503 status_staleandRetry-After: 5, and what the check had spent is given back.
From sdks/dotnet/examples/interop_ext/Program.cs, which sdks/interop/ext/interop_ext.py runs against a real node:
Route("POST", "/t/{tenant}/orders", "orders:place", cls: "write", level: 1, resource: "tenant:{tenant}:order:new",
amountField: "/total", summary: "Place an order"),o.Tenants = new Dictionary<string, AllowedByTenant>
{
["umbrella"] = new() { Name = "Umbrella" },
["hooli"] = new()
{
Name = "Hooli",
Routes = new Dictionary<string, AllowedByTenantRoute> { ["orders:place"] = new() { AmountMax = "50.00" } },
},
["budget"] = new()
{
Name = "Budget Co",
Budgets = new Dictionary<string, AllowedByBudget> { ["orders:place"] = new() { Max = "100.00", Currency = "EUR", Per = "day" } },
},
};Framework recipes#
Answer: minimal APIs take AllowedByContext as a parameter; controllers use [FromAllowedBy]; both come from
UseAllowedBy().
The middleware runs, in order: the SDK's own endpoints (GET|HEAD /.well-known/allowedby, /openapi.json,
/.well-known/api-catalog), then the check on every route of the map, then your app. On a route of the map it reads
the body once (at most MaxBodyBytes: 1 KiB to 64 MiB, 1 MiB by default), checks it is a JSON object, and gives the same bytes back
to your app. Place app.UseAllowedBy() before your endpoints. The route map uses the paths your endpoints see:
with app.UsePathBase("/api") (before UseAllowedBy()), declare /notes, while agents call and sign
/api/notes. Path rewriting onto a route of the map is refused (400): the SDK never checks
one path and lets the app serve another. Method-override headers (X-HTTP-Method-Override, X-HTTP-Method,
X-Method-Override) naming a protected route are refused (400), and after UseAllowedBy() any middleware that
changes the method or path to a protected route that was not checked (UseHttpMethodOverride, UseRewriter,
UsePathBase) is stopped (400); so put UsePathBase before UseAllowedBy(); and route paths are literal segments and {name} only (catch-all, optional, default
and constrained parameters are refused at construction, since the router would match them differently).
The handler of a route of the map runs only for requests checked for that route: see
What is refused and why. A control character in a protected path, and a map written with the path base in it, are refused
(400). Endpoint routing is required (the default).
Each app below is in sdks/dotnet/examples/frameworks; CI runs it on .NET 8 and .NET 10 against a real node, agent and
person (sdks/dotnet/examples/frameworks.json).
Minimal APIs (minimal-api/Program.cs, then minimal-api/NoteEndpoints.cs):
using AllowedBy;
using AllowedBy.AspNetCore;
using static AllowedBy.Routes;
var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration; // environment variables and appsettings.json
builder.WebHost.UseUrls("http://localhost:" + (config["PORT"] ?? "5000"));
builder.Services.AddAllowedBy(o =>
{
o.Origin = config["ALLOWEDBY_ORIGIN"] ?? "http://localhost:5000";
o.Node = config["ALLOWEDBY_NODE"] ?? "http://localhost:8700";
o.RefreshSeconds = config.GetValue("ALLOWEDBY_REFRESH_SECONDS", 5);
o.Org = new AllowedByOrg { LegalName = "Notes Interop Ltd", Country = "FR" };
o.Title = "Notes Interop API";
o.Routes =
[
Route("GET", "/me", level: 0, summary: "Who is calling"),
Route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"),
Route("POST", "/notes", "notes:write", cls: "write", level: 1, resource: "note:new", summary: "Add a note",
body: new Dictionary<string, string> { ["text"] = "the note" }),
Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}",
summary: "Delete a note"),
];
o.Templates = new Dictionary<string, AllowedByTemplate>
{
["notes:read"] = "Read your notes",
["notes:write"] = "Write new notes",
["notes:delete"] = "Delete note {scope}",
};
});
var app = builder.Build();
app.UseAllowedBy();
app.MapNotes();
app.Run();using System.Globalization;
using AllowedBy;
using AllowedBy.AspNetCore;
/// <summary>The endpoints: ordinary minimal APIs that take the verified context as a parameter.</summary>
internal static class NoteEndpoints
{
private static readonly Dictionary<string, List<Note>> People = [];
private static readonly object Gate = new();
private static int _lastId;
public static void MapNotes(this WebApplication app)
{
// outside the route map: it reaches the app unchecked, with no context
app.MapGet("/health", () => new { ok = true });
app.MapGet("/me", (AllowedByContext ctx) => new { agent = ctx.Agent, @operator = ctx.Operator, level = ctx.Level });
app.MapGet("/notes", ([FromAllowedBy] AllowedByContext ctx) =>
{
lock (Gate)
{
return new { notes = Mine(ctx).ToList() };
}
});
app.MapPost("/notes", (NewNote input, [FromAllowedBy] AllowedByContext ctx) =>
{
if (string.IsNullOrEmpty(input.Text) || input.Text.Length > 2000)
{
return Results.Json(new { error = "text: a string of 1 to 2000 characters" }, statusCode: 400);
}
lock (Gate)
{
var id = (++_lastId).ToString(CultureInfo.InvariantCulture);
Mine(ctx).Add(new Note(id, input.Text));
return Results.Json(new { id }, statusCode: 201);
}
});
app.MapDelete("/notes/{id}", (string id, [FromAllowedBy] AllowedByContext ctx) =>
{
lock (Gate)
{
Mine(ctx).RemoveAll(n => n.Id == id);
}
return new { deleted = id };
});
app.MapFallback(() => Results.Json(new { error = "not found" }, statusCode: 404));
}
/// <summary>This person's notes: HumanId is their id at this app. A level-0 route has no person (HumanId is
/// null): stop here rather than key anyone's notes by a missing id.</summary>
private static List<Note> Mine(AllowedByContext ctx)
{
var person = ctx.HumanId
?? throw new InvalidOperationException("HumanId is null: level-0 routes have no person; use level 1+");
if (!People.TryGetValue(person, out var notes))
{
People[person] = notes = [];
}
return notes;
}
}
internal sealed record Note(string Id, string Text);
internal sealed record NewNote(string? Text);AllowedByContext is registered per request, so a minimal-API parameter of that type is filled without an attribute
(/me above); [FromAllowedBy] says it explicitly. Asking for it on a request the SDK did not accept throws: a
handler never receives an unverified request. On an endpoint that also serves paths outside the map, call
HttpContext.GetAllowedBy(), which returns null there.
MVC controllers, with the routes in appsettings.json (mvc/; NoteStore.cs there keeps the notes):
using AllowedBy.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;
builder.WebHost.UseUrls("http://localhost:" + (config["PORT"] ?? "5000"));
builder.Services.AddSingleton<AllowedBy.Examples.Mvc.NoteStore>();
builder.Services.AddControllers();
builder.Services.AddAllowedBy(config.GetSection("AllowedBy"), o => // appsettings.json, then what each deployment sets
{
o.Origin = config["ALLOWEDBY_ORIGIN"] ?? o.Origin;
o.Node = config["ALLOWEDBY_NODE"] ?? o.Node;
o.RefreshSeconds = config.GetValue("ALLOWEDBY_REFRESH_SECONDS", o.RefreshSeconds);
});
var app = builder.Build();
app.UseAllowedBy();
app.MapControllers();
app.MapFallback(() => Results.Json(new { error = "not found" }, statusCode: 404));
app.Run();using AllowedBy.AspNetCore;
using Microsoft.AspNetCore.Mvc;
namespace AllowedBy.Examples.Mvc;
/// <summary>The person's notes. The routes, their levels and their sentences are in appsettings.json.</summary>
[ApiController]
[Route("notes")]
public sealed class NotesController(NoteStore store) : ControllerBase
{
/// <summary>GET /notes (notes:read, level 1).</summary>
[HttpGet]
public IActionResult List([FromAllowedBy] AllowedByContext ctx) => Ok(new { notes = store.List(Person(ctx)) });
/// <summary>POST /notes (notes:write, level 1), body {"text": "..."}.</summary>
[HttpPost]
public IActionResult Add([FromAllowedBy] AllowedByContext ctx, [FromBody] NewNote note) =>
string.IsNullOrEmpty(note?.Text) || note.Text.Length > 2000
? BadRequest(new { error = "text: a string of 1 to 2000 characters" })
: StatusCode(201, new { id = store.Add(Person(ctx), note.Text) });
/// <summary>DELETE /notes/{id} (notes:delete, write-hard, level 2): the person approved this exact request.</summary>
[HttpDelete("{id}")]
public IActionResult Delete(string id, [FromAllowedBy] AllowedByContext ctx)
{
store.Delete(Person(ctx), id);
return Ok(new { deleted = id });
}
/// <summary>The person the notes belong to. A level-0 route has no person (HumanId is null): stop here rather than
/// key anyone's notes by a missing id.</summary>
private static string Person(AllowedByContext ctx) =>
ctx.HumanId
?? throw new InvalidOperationException("HumanId is null: level-0 routes have no person; use level 1+");
}
/// <summary>The body of POST /notes.</summary>
/// <param name="Text">The note.</param>
public sealed record NewNote(string? Text);using AllowedBy.AspNetCore;
using Microsoft.AspNetCore.Mvc;
namespace AllowedBy.Examples.Mvc;
/// <summary>GET /me (level 0: the agent's passport only) and GET /health (outside the route map: unchecked).</summary>
[ApiController]
public sealed class AgentController : ControllerBase
{
/// <summary>Which agent is calling.</summary>
[HttpGet("/me")]
public IActionResult Me([FromAllowedBy] AllowedByContext ctx) =>
Ok(new { agent = ctx.Agent, @operator = ctx.Operator, level = ctx.Level });
/// <summary>The app's own path.</summary>
[HttpGet("/health")]
public IActionResult Health() => Ok(new { ok = true });
}{
"AllowedBy": {
"Origin": "http://localhost:5000",
"Node": "http://localhost:8700",
"Org": { "LegalName": "Notes Interop Ltd", "Country": "FR" },
"Title": "Notes Interop API",
"RefreshSeconds": 5,
"Routes": [
{ "Method": "GET", "Path": "/me", "Level": 0, "Summary": "Who is calling" },
{
"Method": "GET",
"Path": "/notes",
"Capability": "notes:read",
"Resource": "note:*",
"Summary": "List your notes",
"Template": "Read your notes"
},
{
"Method": "POST",
"Path": "/notes",
"Capability": "notes:write",
"Class": "write",
"Resource": "note:new",
"Summary": "Add a note",
"Body": { "text": "the note" },
"Template": "Write new notes"
},
{
"Method": "DELETE",
"Path": "/notes/{id}",
"Capability": "notes:delete",
"Class": "write-hard",
"Level": 2,
"Resource": "note:{id}",
"Summary": "Delete a note",
"Template": "Delete note {scope}"
}
]
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}In configuration a capability cannot be a dictionary key (: separates configuration sections), so give each
route's sentence as its Template (a string, or {"Summary": {"en": ...}, "Lines": {"en": ...}}).
Without ASP.NET Core (another server, a gateway): build an AllowedByService and call it yourself.
Handle(method, path) returns the discovery documents or null; MustCheck says whether to read the body;
CheckAsync(new AllowedByRequest(method, rawPath, rawQuery, headers, body)) returns the Context, or the Refusal to
send back as is. Dispatch on Context.Route, the route that was checked, and take its values from Context.Params (each decoded once: a%20b is a b, never decode it again), never from a
second reading of the path. Call
RunAsync(stoppingToken) once to keep the node's keys and revocation lists fresh; the first checks wait for its first
refresh (at most 5 s). The whole server, on HttpListener
(httplistener/Program.cs):
using System.Globalization;
using System.Net;
using System.Text.Json;
using AllowedBy;
using static AllowedBy.Routes;
static string Env(string name, string otherwise) => Environment.GetEnvironmentVariable(name) ?? otherwise;
using var aby = new AllowedByService(new AllowedByOptions
{
Origin = Env("ALLOWEDBY_ORIGIN", "http://localhost:5000"),
Node = Env("ALLOWEDBY_NODE", "http://localhost:8700"),
RefreshSeconds = int.Parse(Env("ALLOWEDBY_REFRESH_SECONDS", "5"), CultureInfo.InvariantCulture),
Org = new AllowedByOrg { LegalName = "Notes Interop Ltd", Country = "FR" },
Routes =
[
Route("GET", "/me", level: 0, summary: "Who is calling"),
Route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"),
Route("POST", "/notes", "notes:write", cls: "write", level: 1, resource: "note:new", summary: "Add a note",
body: new Dictionary<string, string> { ["text"] = "the note" }),
Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}",
summary: "Delete a note"),
],
Templates = new Dictionary<string, AllowedByTemplate>
{
["notes:read"] = "Read your notes",
["notes:write"] = "Write new notes",
["notes:delete"] = "Delete note {scope}",
},
});
_ = aby.RunAsync(CancellationToken.None); // keeps the node's keys and revocation lists fresh, in the background
var people = new Dictionary<string, List<Note>>();
var lastId = 0;
var web = new JsonSerializerOptions(JsonSerializerDefaults.Web); // camelCase
using var server = new HttpListener();
// http.sys on Windows: no firewall prompt, localhost needs no admin; elsewhere localhost would bind ::1 only
server.Prefixes.Add("http://" + (OperatingSystem.IsWindows() ? "localhost" : "*") + ":" + Env("PORT", "5000") + "/");
server.Start();
while (true)
{
var http = await server.GetContextAsync();
_ = Task.Run(async () =>
{
try
{
await Serve(http);
}
catch (Exception e) when (e is HttpListenerException or IOException or ObjectDisposedException)
{
http.Response.Abort(); // the client went away
}
catch (Exception e)
{
Console.Error.WriteLine("request failed: " + e.GetType().Name); // never the path, query or headers
try
{
http.Response.StatusCode = 500;
http.Response.Close();
}
catch (Exception)
{
http.Response.Abort();
}
}
});
}
async Task Serve(HttpListenerContext http)
{
var raw = http.Request.RawUrl ?? "/"; // as sent, still percent-encoded: what the agent signed
var q = raw.IndexOf('?', StringComparison.Ordinal);
var (path, query) = q < 0 ? (raw, null) : (raw[..q], raw[(q + 1)..]);
var method = http.Request.HttpMethod;
if (aby.Handle(method, path) is { } document) // /.well-known/allowedby, /openapi.json, ...
{
await Send(http, document.Status, document.Headers, document.Body);
return;
}
var headers = http.Request.Headers.AllKeys.Where(k => k is not null)
.Select(k => new KeyValuePair<string, string>(k!, http.Request.Headers[k] ?? "")).ToList();
if (!aby.MustCheck(new AllowedByRequest(method, path, query, headers, ReadOnlyMemory<byte>.Empty)))
{
await Json(http, path == "/health" ? 200 : 404, path == "/health" ? new { ok = true } : new { error = "not found" });
return;
}
var body = await ReadBody(http.Request.InputStream, aby.MaxBodyBytes + 1);
var result = await aby.CheckAsync(new AllowedByRequest(method, path, query, headers, body));
if (result.Refusal is { } refusal)
{
await Send(http, refusal.Status, refusal.Headers, refusal.Body); // as is: it carries the challenge
return;
}
if (result.Context is not { Route: { } route } ctx)
{
await Json(http, 404, new { error = "not found" });
return;
}
var (status, answer) = Dispatch(route.Method + " " + route.Path, ctx, body); // the route that was checked
await Json(http, status, answer);
}
(int Status, object Answer) Dispatch(string route, AllowedByContext ctx, byte[] body)
{
if (route == "GET /me")
{
return (200, new { agent = ctx.Agent, @operator = ctx.Operator, level = ctx.Level });
}
// A level-0 route has no person (HumanId is null): stop here rather than key anyone's notes by a missing id.
var person = ctx.HumanId
?? throw new InvalidOperationException("HumanId is null: level-0 routes have no person; use level 1+");
lock (people)
{
if (!people.TryGetValue(person, out var mine))
{
people[person] = mine = [];
}
switch (route)
{
case "GET /notes":
return (200, new { notes = mine.ToList() });
case "POST /notes":
using (var doc = JsonDocument.Parse(body.Length == 0 ? "{}"u8.ToArray() : body))
{
var text = doc.RootElement.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null;
if (text is null || text.Length is 0 or > 2000)
{
return (400, new { error = "text: a string of 1 to 2000 characters" });
}
var note = new Note((++lastId).ToString(CultureInfo.InvariantCulture), text);
mine.Add(note);
return (201, new { id = note.Id });
}
case "DELETE /notes/{id}":
var id = ctx.Params["id"]; // the value that was checked, decoded once: never the path read again
mine.RemoveAll(n => n.Id == id);
return (200, new { deleted = id });
default:
return (404, new { error = "not found" });
}
}
}
static async Task<byte[]> ReadBody(Stream input, int limit)
{
using var body = new MemoryStream();
var buffer = new byte[16384];
int n;
while (body.Length < limit && (n = await input.ReadAsync(buffer)) > 0)
{
body.Write(buffer, 0, Math.Min(n, limit - (int)body.Length));
}
return body.ToArray(); // one byte over the limit at most: CheckAsync then refuses it
}
Task Json(HttpListenerContext http, int status, object answer) => Send(http, status,
new Dictionary<string, string> { ["Content-Type"] = "application/json" },
JsonSerializer.SerializeToUtf8Bytes(answer, web));
static async Task Send(HttpListenerContext http, int status, IReadOnlyDictionary<string, string> headers, ReadOnlyMemory<byte> body)
{
http.Response.StatusCode = status;
foreach (var (name, value) in headers)
{
http.Response.AddHeader(name, value);
}
if (http.Request.HttpMethod != "HEAD")
{
http.Response.ContentLength64 = body.Length;
await http.Response.OutputStream.WriteAsync(body);
}
http.Response.Close();
}
internal sealed record Note(string Id, string Text);The service cannot see which handler your router chooses, so it refuses (400) every request that is not on the map but
that a mapped template would match if a parameter took several segments (DELETE /notes/7/x for DELETE /notes/{id},
for the method or one a method-override header names); GET /notes/7 with only GET /notes mapped goes through.
Declare a page of your own in Unprotected. The ASP.NET Core adapter applies the same rule to a request for which the
router selected no endpoint made for its path (none: a handler in app.Run or other terminal middleware, or routing
placed after UseAllowedBy(); or a fallback or a catch-all, after which middleware may still dispatch the path by hand);
where the router did select one, it judges that endpoint's handler instead. So with UseRouting()
after UseAllowedBy(), your own longer routes are refused too: DELETE /notes/7/comments, served by
MapDelete("/notes/{id}/comments", DeleteComment) next to DELETE /notes/{id} in the map, is a 400 until you either
call app.UseRouting() before app.UseAllowedBy() (the default WebApplication routes first) or declare
("DELETE", "/notes/{id}/comments") in Unprotected.
What is refused and why#
The handler of a route of the map never runs for a request the SDK did not check for that route (sdks/CONTRACT.md
§2.10). ASP.NET Core tells the middleware which endpoint the router selected, before or after UseAllowedBy(), so the
SDK decides by the handler, not by the path: a handler reached by a wider template acts on the values that template
gives it, so no path of it is safe to run unchecked. These requests are refused (400 invalid_request):
| Request without a check | Example (map: DELETE /notes/{id}) |
Why |
|---|---|---|
| An endpoint of the route whose template accepts more | MapDelete("/notes/{**id}"), {id?}, {id=1}, {id:int}/{more?}: DELETE /notes/7/x |
the protected handler runs with id = "7/x" |
| A catch-all that is the only endpoint of a route ending in a literal | map DELETE /notes/{id}/archive, MapDelete("/notes/{id}/{**rest}"): DELETE /notes/7/archive/x, DELETE /notes/7/other |
the catch-all takes the literal with the rest; its handler is the route's |
| A root catch-all that is the handler of a route | MapDelete("/{**path}") as the only endpoint of the route: DELETE /x/notes/7 |
any path reaches the same handler |
| A generic endpoint that serves a route | Map("/{a}/{**rest}"): POST /notes/7, GET /other/x/y |
the handler serves every method and every path of the template |
| Another endpoint of the same handler, of any method | MapDelete("/alias/{id}", Handler), MapGet("/notes/{id}", Handler) beside the protected MapDelete("/notes/{id}", Handler), MapGroup, a second [HttpDelete] template, a conventional MVC route, an inherited action, a dynamic MVC route, a RequestDelegate with or without endpoint filters |
the same code runs, and may read its input from the query; Unprotected never lifts it. The refusal names the fix: map that method too, or give it a handler of its own |
A path declared in Unprotected that a protected handler serves |
Unprotected = [("DELETE", "/notes/{id}/comments")] with MapDelete("/notes/{**id}"): DELETE /notes/7/comments |
Unprotected never lifts this refusal |
| A reverse proxy pipeline with one route in the map (YARP) | MapReverseProxy(): the proxy's other routes |
one pipeline is one handler |
A HEAD request a GET handler would answer |
MapMethods("/notes/{**id}", ["GET", "HEAD"]), [HttpHead] on another template, a middleware that turns HEAD into GET: HEAD /notes/7/x with GET /notes/{id} mapped |
HEAD is read as GET everywhere |
| A short-circuited endpoint of a protected handler | MapDelete("/notes/{id}", Delete).ShortCircuit() |
the router runs it before any middleware: the app does not start |
| A control character in a protected path | DELETE /notes/7%0A |
a router may match before it |
| A parameter no approval can carry (ABY-2 §6) | a value of the scope (the route's resource with the values of the normalised path: %61b is ab) that is not 1 to 64 of A-Z a-z 0-9 . _ - (a%20b, x%C3%A9, ~, :, *), a malformed escape, an escaped control character or /, or a scope over 256 bytes |
an approval of that scope could never satisfy the route; the scope goes back as it is, never re-encoded |
| A map written with the path base in it, a rewritten path, a method override naming a protected route | UsePathBase("/api") and /api/notes/{id} in the map |
the path checked would not be the path routed |
The safe pattern: give each page of your own an endpoint and a handler of its own, beside the protected ones
(MapDelete("/notes/{id}/comments", DeleteComment) next to MapDelete("/notes/{id}", DeleteNote)). Your endpoints,
longer routes, fallbacks and static catch-alls that serve no route of the map run unchanged. Prefer handlers with typed
parameters on protected routes: they are compared by their method in every case. o.Unprotected (a path, or a method and
a path, as your app routes it) declares a page of your own where no handler is judged (below): it lifts the refusal of a
longer path for its method only. It never lifts a method override onto a mapped route, nor the refusal of a protected
handler. An entry that reaches a route of the map, has no literal segment, is a template for a longer path of a route without naming its
method, or (exact) may be read as another path (//, ., .., ;, %) fails construction.
Catch-alls (sdks/CONTRACT.md §2.10 rule 5). An endpoint that also takes a route's path with one of its words
replaced (/{**path}, /{a}/{**rest}, /notes/{id}/{**rest} for DELETE /notes/{id}/archive), and any fallback,
is a catch-all of that route. The route's own handler is known when one of its endpoints is no catch-all of it and takes
a value for each of its parameters (MapDelete("/notes/{id:int}") for DELETE /notes/{id}). Then a request checked
for the route that the router gives to a catch-all (a value the route's own endpoint turns down) is refused (400); a
site-wide catch-all (/{**path}, MapFallback) is not the route's handler, so an SPA's pages run; a catch-all under
the route's prefix stays protected for that route, and so do its other endpoints. While the route's own handler is not
known and a catch-all is its only handler (a front controller, a router mounted at /), a request checked for the
route runs it, and unchecked requests that would run it are refused; for a site-wide one the SDK logs once at startup
DELETE /notes/{id} is served only by a site-wide catch-all: give it a handler of its own. A handler that serves
several routes of the map runs for a request checked for one of them, even through that route's own endpoint, only if
that route covers each other route the handler is known or protected for, whatever its shape: one delegate on
MapDelete("/notes/{id}") (level 3) and MapDelete("/items/{id}") (level 1) never runs for a request checked for
/items/7; one whose own handler is not known; one it serves as a catch-all; and the same template with another method
(one handler for both, which does not dispatch per method: MapMethods("/items/{id}", ["GET", "POST"], Handler), an
action with two Http* attributes, one delegate on MapGet and MapPost). The SDK logs once at startup each pair of
routes whose own endpoints run one handler where one does not cover the other, whatever their templates (DELETE /items/{id} and DELETE /notes/{id} run one handler, and one does not cover the other: map both at the same capability and level, or give each its own handler). Through a catch-all, another route's own handler is never run for it. Covering means the same capability,
resource, amount field and currency field; a level and tier at least as high; its lowest class at least the other's
highest; its longest grant at most the other's shortest; an authn at least as strong (hardware, then synced, then
none); and the levelProfile the other sets. Two routes
that share a catch-all without covering each other refuse each other: give each a handler of its own. Two limits
follow (sdks/CONTRACT.md §2.10 rule 5): a site-wide catch-all that dispatches protected actions on paths no route maps
(Map("/{**path}", Legacy) that deletes at /legacy/delete?id=7) is not something the SDK can see, as those paths are
no route of the map; and a front controller shared by routes of different capabilities or resources runs for none of
them. Give each protected route its own handler. An endpoint found for a route only under a path base the SDK guesses
(UsePathBase, Map) never makes the route's own handler known, so a site-wide catch-all stays protected there. Nothing is learnt
from requests: the endpoints decide, the same way for every request. An OPTIONS that the framework answers (405, a
CORS preflight answered from the endpoint's metadata) runs no code of yours and is not refused; an endpoint of yours
that takes OPTIONS (Map(...)) is refused like any other method.
A refusal (its title, detail and headers) and a log line never repeat the path, the query, a header, or a value read
from the passport or the grant (issuer, organisation, capability, key, subject, level), which may hold personal data or
tokens; the challenge's scope alone carries the path's values, back to the caller: the log names the route template (DELETE /notes/{id} -> passport_required, DELETE a longer path of /notes/{id} -> invalid_request).
A handler that no endpoint stands for (app.Run, Map branches that dispatch by hand) is not seen either, so for a
request with no endpoint the SDK refuses longer paths of mapped routes, as without ASP.NET Core (below). Not seen by the
SDK, so protect them yourself: code two handlers share (a lambda that calls another handler), and middleware that answers
a request in place of the endpoint the router selected for it (the SDK judges that endpoint). A fallback (MapFallback, MapFallbackToFile) that reaches a mapped route only by its template (the route's own
endpoint has a constraint, {id:int}, or there is none) serves your other pages, and is refused (400) for an unchecked path
that continues a mapped route of the request's method (DELETE /notes/7/archive/x); a fallback that runs a protected
handler is refused for every unchecked request. A CORS preflight that the router gives to a protected endpoint with CORS metadata reaches the CORS middleware with
that metadata; the endpoint itself refuses it (400) should anything pass it on (no CORS middleware, a policy that does
not resolve): its handler never runs for it. In a Startup-style or generic-host pipeline (UseAllowedBy() on a builder that is not a WebApplication), the SDK
cannot tell which data sources share one matcher, so no endpoint of one data source hides a wider one of another: a
catch-all of the app under a route's prefix (Map("/notes/{**path}") next to a protected action for
DELETE /notes/{id}/archive) counts as that action's handler and its unchecked requests get a 400. Give such pages endpoints of their own, or host on WebApplication. A short-circuited endpoint is
known by the full name of ASP.NET Core's internal metadata
(Microsoft.AspNetCore.Routing.ShortCircuit.ShortCircuitMetadata, .NET 8 and 10): the SDK's tests fail if a version of
ASP.NET Core adds another. One added at runtime (a data source that changes its endpoints) makes every request a 400
while it is there. With a matcher policy that
is not ASP.NET Core's own (API versioning, your own), no endpoint is taken to always win a route: wider endpoints of a
mapped route count as its handlers. Endpoint routing is
required (the default): with MvcOptions.EnableEndpointRouting = false the app does not start.
The context#
Answer: AllowedByContext says who the agent is, for which person, at which level, under which grant.
| Property | What |
|---|---|
HumanId |
The person's pairwise identifier for your service: stable for one person here, different at every other service. null on level-0 routes. Use it as the account key. |
Level |
The level reached for this request: 0 to 3. |
Agent |
The agent's identifier (its passport sub). |
Operator |
Who runs the agent (the operator id from its passport). |
Capabilities |
The capabilities of the grant used. |
Display |
The words the person approved: Summary, Lines, Lang. |
Gid, Rev, Jti |
The grant id, its revision (0, then +1 at each rebind) and the grant document's id. |
ActingFor |
The organisation under a company mandate. Always null here: mandates are not supported yet. |
Tenant |
The {tenant} path parameter, when the route has one. |
Route |
The route that matched: method, path pattern, capability, class of this request, level. |
Chain |
The delegation chain, leaf first: each grant's Gid and Rev. |
HumanIssuer |
The person's home node. |
LinkedAccount |
On a requireLink route: the account of yours the person linked (Account linking). Null elsewhere. |
ProofJti, Run, Call |
The proof's id, and the agent's run id and call counter when it sent them (audit only). |
Production#
Answer: set KeyFile, use RedisStore with several instances, keep the background refresh running, and read the
AllowedBy log category.
The AllowedBy log category names route templates, never a request's path, query or headers. ASP.NET Core's own
request lines (Microsoft.AspNetCore.Hosting.Diagnostics, at Information) do log the full URL, which may hold personal
data or tokens: the examples set "Microsoft.AspNetCore": "Warning" in their appsettings.json, and CI fails a run whose
log repeats a request path.
CI runs this app (sdks/dotnet/examples/Production) with Redis against a real node, agent and person:
using AllowedBy;
using AllowedBy.AspNetCore;
using AllowedBy.Redis;
using StackExchange.Redis;
using static AllowedBy.Routes;
var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;
if (string.IsNullOrEmpty(config["urls"])) // --urls or ASPNETCORE_URLS win
{
// loopback unless ALLOWEDBY_BIND says otherwise (the Dockerfile sets 0.0.0.0); an empty value counts as unset
var bind = config["ALLOWEDBY_BIND"];
var port = config["PORT"];
builder.WebHost.UseUrls("http://" + (string.IsNullOrEmpty(bind) ? "127.0.0.1" : bind) + ":" +
(string.IsNullOrEmpty(port) ? "8080" : port));
}
// One Redis connection per process; every instance shares the replay set, single-use set and counters.
builder.Services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(config["REDIS"] ?? "localhost:6379"));
builder.Services.AddSingleton<IAllowedByStore>(sp => new RedisStore(sp.GetRequiredService<IConnectionMultiplexer>()));
builder.Services.AddAllowedBy(o =>
{
o.Origin = config["ALLOWEDBY_ORIGIN"]!; // your public URL: construction fails, and says so, when it is missing
o.Node = config["ALLOWEDBY_NODE"]!;
o.Org = new AllowedByOrg { LegalName = "Notes Interop Ltd", Country = "FR", PrivacyPolicy = "https://notes.example/privacy" };
// The same keys on every instance and across restarts (created on first start, mode 0600).
o.KeyFile = config["ALLOWEDBY_KEY_FILE"] ?? "/var/lib/notes/allowedby-keys.json";
o.Routes =
[
Route("GET", "/me", level: 0),
Route("GET", "/notes", "notes:read", resource: "note:*"),
Route("POST", "/notes", "notes:write", cls: "write", resource: "note:new"),
Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}"),
Route("POST", "/invoices/{id}/pay", "invoices:pay", resource: "invoice:{id}", amountField: "/total",
classByAmount: [new() { UpTo = "1000.00", Class = "write-hard" }, new() { Class = "irreversible" }],
level: 2, authn: "hardware"),
];
o.Templates["notes:read"] = "Read your notes"; // English, for the summary and the line
o.Templates["invoices:pay"] = new AllowedByTemplate
{
Summary = new Dictionary<string, string>
{
["en"] = "Pay {scope}, up to {amount.max} {amount.currency}",
["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}",
},
Lines = new Dictionary<string, string>
{
["en"] = "Pay {scope}, up to {amount.max} {amount.currency}",
["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}",
},
};
o.Templates["notes:write"] = "Write new notes";
o.Templates["notes:delete"] = "Delete note {scope}";
});
var app = builder.Build();
app.UseAllowedBy();
app.MapPost("/invoices/{id}/pay", (string id, AllowedByContext ctx) => new { paid = id, by = ctx.HumanId, gid = ctx.Gid });
app.MapNotes(); // frameworks/minimal-api/NoteEndpoints.cs
app.Run();- Keys (
KeyFile): a JSON file{"signing": {"pem": ...}, "disclosure": {"pem": ...}}(PKCS#8 PEM), the same format as the Python SDK'skey_file: one file works in every SDK. Created on first start with mode 0600, atomically; when several instances start together, the first writer wins and the others read its keys (one atomiclink, so the file system needs hard links; on one without, the first start fails and says so: create the file once elsewhere). Keep it on a volume or in your secret store; never in the image. Without it the keys are new at each start, and agents re-fetch/.well-known/allowedby. - Store:
MemoryStore(the default) is for one process only: with several instances a replayed proof or a single-use grant could be accepted once per instance.RedisStoreuses compare-and-set transactions; its keys share one hash tag ({allowedby}:), so it also works on Redis Cluster. Register anyIAllowedByStorein DI, or seto.Store. A store error refuses the request (503,Retry-After: 5). - Refunds (sdks/CONTRACT.md, Refund on the SDK's own refusal): the check consumes a single-use approval and adds to
the grant's
countandamounttotals. When the SDK then refuses that request itself before its endpoint starts (rule 5, a method or path changed after the check), it gives back exactly what the check spent, so the approval stays usable for its own route. A refund the store does not take leaves the approval spent (logged). Nothing is refunded once the endpoint started, nor when your own middleware or handler answers. - Trust: by default the node's key is trusted on first use and pinned (a changed key is refused and logged). For
an OAID-5 signed trust list, set
o.TrustList(the compact JWS) ando.TrustListKey(the public JWK of your key that signed it): anchors, pinned program lists, vouching and witnesses are then evaluated by the background refresh. - Refresh:
AddAllowedByruns the refresh as a hosted service everyRefreshSeconds(1 to 60, default 5): node statement, status lists, trust list. Never on the request path. The host serves once the first refresh is over (done or failed, at most 5 s), so a service that starts cold (a new instance, one that scales to zero) answers its first request from a filled cache, not withuntrusted_nodeor503 status_stale(sdks/CONTRACT.md §2 item 4); without ASP.NET Core, the firstCheckAsynccalls wait for the first refresh ofRunAsyncthe same way, and never fetch anything themselves. Until a refresh succeeds, every agent request is refused (untrusted_node); a status list older than 60 s pauses write-hard and irreversible routes (503 status_stale), older than 3600 s pauses every route. - Logging: log category
AllowedBy. Each checked request logs its outcome code (never tokens, keys or bodies); failures of the refresh log[verifier] refresh failed: ...at Warning. Alert on those. - Origin and proxies:
Originis your public origin. The SDK rebuilds each request's URL fromOriginand the path as received (the raw request target), and ignoresHostandX-Forwarded-*. A proxy must not rewrite the path. - Clock:
o.Clockis aTimeProvider; every time check uses it (proofs from -120 s to +60 s, expiry, store deadlines). - Listening: the example listens on
ALLOWEDBY_BIND(default127.0.0.1, loopback only) andPORT(default8080), unless--urlsorASPNETCORE_URLSnames the addresses; an empty value counts as unset. The container setsALLOWEDBY_BIND=0.0.0.0.
Run it in a container (sdks/dotnet/examples/Production/Dockerfile):
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish sdks/dotnet/examples/Production -c Release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app .
ENV ALLOWEDBY_BIND=0.0.0.0 PORT=8080
ENTRYPOINT ["dotnet", "AllowedBy.Examples.Production.dll"]docker build -f sdks/dotnet/examples/Production/Dockerfile -t notes .docker run --rm --network host -e ALLOWEDBY_ORIGIN=http://localhost:8080 -e ALLOWEDBY_NODE=http://localhost:8700 notesAgents#
Answer: there is no agent SDK for .NET; agents use the Python or TypeScript agent SDK, and any of them can call a .NET service.
What your service needs from agents is in the protocol, not in a language: an agent passport, a grant and a proof on
each request (see docs/sdk/python.md and docs/sdk/js.md, section Agents). The interop test
below drives the .NET example app with the Python reference agent.
Errors#
Answer: every refusal is application/problem+json with type: https://allowedby.org/errors/<code>; challenges also
carry WWW-Authenticate: AllowedBy ....
| Code | Status | Meaning | What to do |
|---|---|---|---|
invalid_request |
400 | Malformed request, or the body is not one JSON object, repeats a member name (even with another case), or is larger than MaxBodyBytes. |
Send a JSON object body, each member once. |
passport_required |
401 | The agent sent no passport. | The caller is not an AllowedBy agent, or calls a protected route without one. |
invalid_signature |
401 | Bad, expired or replayed proof; tampered grant or passport. | Check the agent's clock (proofs must be within -120 s/+60 s) and the URL your app sees (scheme, host, port must match Origin). |
untrusted_node |
401 | The passport or grant comes from a node you do not trust, or the first refresh has not succeeded yet. | Check Node or your trust list, and the refresh log. |
insufficient_witnesses |
401 | The node's log is not witnessed by enough trusted nodes (trust list witnesses_min). |
Check the trust list. |
grant_required |
401 | No approval for this action. The challenge says what is needed. | Normal first call. The agent asks the person. |
grant_insufficient |
401 | The approval does not cover this resource, amount or request (or a one-time approval is for another request). | The agent asks for a wider approval. |
level_insufficient |
401 | The person's level is below the route's. | The person verifies their identity on the approval page. |
qes_required |
401 | A qualified signature is needed. | Not produced by this SDK (Qes routes are refused at construction). |
mandate_required |
401 | The approval was given for an organisation; this SDK checks no mandates. | The person approves for themselves. |
authority_required |
401 | The organisation's co-approvers are needed. | Not produced by this SDK (that route option is refused at construction). |
expired, actor_expired |
401 | The approval, or the agent's passport key, expired. | The agent rebinds or asks again. |
not_yet_valid |
401 | The approval starts later. | The agent retries later. |
revoked |
401 | The person withdrew the approval (or a parent grant in its chain). | The agent asks again. |
single_use_consumed |
401 | A one-time approval was already used. | Expected on retries of a serious action. |
class_lifetime_exceeded |
401 | The approval lasts longer than this class allows. | Lower the requested period. |
capability_denied |
403 | No such route. | Check the route map. |
tier_insufficient |
403 | The passkey or the agent's key custody is not of the required kind (authn, tier). |
The person uses a hardware passkey, or the agent a stronger key custody. |
human_not_linked |
403 | The route needs a linked account (requireLink), and the person has not linked theirs, or linked another one. No challenge: no approval fixes it. |
The person links their account: Account linking. |
budget_exceeded |
403 | The tenant's budget for this action is used up, or the request has no amount in its currency. No challenge. | Wait for the next period: Tenant budgets. |
rate_limited |
429 | Too many requests from this agent or operator. Retry-After: 60. |
The agent waits, then retries: Rate limits. |
envelope_too_large |
431 | Allowed-By and AllowedBy-Proof over 8 KiB, or a chain over two grants (depth 1: a root and one child). |
Usually a delegation chain too deep. |
status_stale |
503 | Your copy of the node's revocation list is too old, or the store failed; the action is paused. Retry-After: 5. |
Check that your app reaches the node and the store; look for [verifier] refresh failed in your logs. |
Testing#
Answer: dotnet run --project sdks/dotnet/tests/AllowedBy.Vectors, dotnet test sdks/dotnet/tests/AllowedBy.Tests,
and python sdks/interop/interop.py --cmd "..." for the end-to-end test.
The CONF-1 vectors (every case of the verifier profile, read from vectors/ at run time):
dotnet run --project sdks/dotnet/tests/AllowedBy.Vectors -c Release -f net10.0 -- vectorsIt prints each failure and N/N cases passed (481/481), and exits 1 on any failure or any case it cannot run. With
--ext after the vectors directory, it runs the extended vectors of the features this SDK ports (vectors/ext,
profiles.json features: 48/48).
Unit tests, real requests through the middleware (WebApplicationFactory) and the Redis store:
docker run -d --name allowedby-redis -p 6379:6379 redis:7.4-alpine
REDIS_URL=localhost:6379 dotnet test sdks/dotnet/tests/AllowedBy.Tests -c ReleaseOn Windows (PowerShell):
docker run -d --name allowedby-redis -p 6379:6379 redis:7.4-alpine
$env:REDIS_URL = "localhost:6379"; dotnet test sdks/dotnet/tests/AllowedBy.Tests -c ReleaseThe interop test runs the example app against a real node, the reference agent and a person with a software passkey (26 scenarios: discovery, approval, standing grants, replay, tampering, forged grants, serious actions at level 2, single use, revocation, paths outside the map, concurrency):
pip install -r requirements.txt
dotnet build sdks/dotnet/examples/frameworks/minimal-api -c Release
INTEROP_PORT_BASE=19500 python sdks/interop/interop.py --cmd "dotnet sdks/dotnet/examples/frameworks/minimal-api/bin/Release/net10.0/AllowedBy.Examples.MinimalApi.dll"On Windows (PowerShell):
pip install -r requirements.txt
dotnet build sdks/dotnet/examples/frameworks/minimal-api -c Release
$env:INTEROP_PORT_BASE = "19500"; python sdks/interop/interop.py --cmd "dotnet sdks/dotnet/examples/frameworks/minimal-api/bin/Release/net10.0/AllowedBy.Examples.MinimalApi.dll"To test your own app without a browser: refusals (discovery, 401 challenges, 400 bodies) need no node, so test
them with WebApplicationFactory (see sdks/dotnet/tests/AllowedBy.Tests/AspNetCoreTests.cs). For accepted requests,
use sdks/interop/interop.py as the model: it starts a node and plays the person with a software passkey
(demo/e2e.py, Human), and the reference agent (sdks/python/src/allowedby/agent.py) calls your routes.
Reference#
Answer: three public types do the work: AllowedByOptions, AllowedByService and AllowedByContext; the rest are
their parts.
Namespace AllowedBy (package AllowedBy):
| Type | Members |
|---|---|
AllowedByOptions |
Origin, Node, Org, Routes, Templates, KeyFile, Store, Unprotected, TrustList, TrustListKey, RefreshSeconds, NodeMaxLevel, Clock, Title, Version, Description, Rfc9421 (accept the RFC 9421 Web Bot Auth profile), MaxBodyBytes, HttpClient, Log, LinkAuthorize, Nonce, Rate, Tenants. |
AllowedByTenant, AllowedByTenantRoute, AllowedByBudget |
A tenant: Name, Routes, MembersOnly, Org, Budgets; an override: Level, Authn, Mandate, RequireLink, MaxLifetime, AmountMax, Operators (refused when set: Qes, Authority); a budget: Max, Currency, Per, Tz. |
AllowedByOrg |
LegalName, Country, Website, Support, PrivacyPolicy. |
AllowedByRoute |
Method, Path, Capability, Class, ClassByAmount, Level, Resource, AmountField, CurrencyField, Authn, Tier, MaxLifetime, LevelProfile, RequireLink, AccountParam, Nonce, Template, Summary, Body; refused when set: Mandate, Disclose, DiscloseOptional, Authority, Qes. |
AllowedByUnprotected |
Method, Path; a string converts to it. |
AllowedByAmountClass |
UpTo, Class. |
AllowedByTemplate |
Text, Summary, Lines; a string converts to it. |
Routes |
Route(method, path, capability, cls, level, resource, amountField, currencyField, authn, tier, maxLifetime, summary, body, classByAmount, levelProfile, qes, requireLink, accountParam, nonce). |
AllowedByService |
new AllowedByService(options), Handle(method, path), CheckAsync(request, ct), RefundBudgetAsync(context, ct), LinkStart(account, ttl), Unlink(account), IsLinkRequest(method, path) (the path as sent, still percent-encoded), LinkAsync(request, ct), InRouteMap(method, path), IsUnprotected(method, path), RouteMap, MustCheck(request), RefreshAsync(ct), RunAsync(stoppingToken), Origin, SigningKeyId, Store, RefreshInterval, MaxBodyBytes, Dispose(). |
AllowedByRequest |
new AllowedByRequest(method, path, query, headers, body, routePath, pathBase), Header(name), RoutePath, PathBase. |
AllowedByResult |
Allowed, Context, Refusal, InRouteMap. |
AllowedByResponse |
Status, Headers, Body, Code. |
AllowedByContext |
See "The context". |
AllowedByDisplay, AllowedByRouteInfo, AllowedByChainLink |
Parts of the context. |
IAllowedByStore |
AddAsync(key, until, now), GetAsync(key, now), ChargeAsync(charges, now). |
MemoryStore, AllowedByCharge |
The one-process store; one counter increment. |
Namespace AllowedBy.AspNetCore (package AllowedBy.AspNetCore): AddAllowedBy(Action<AllowedByOptions>),
AddAllowedBy(IConfiguration section, Action<AllowedByOptions>?), UseAllowedBy(), HttpContext.GetAllowedBy(),
[FromAllowedBy], IAllowedByFeature.
Namespace AllowedBy.Redis (package AllowedBy.Redis): new RedisStore(IConnectionMultiplexer, prefix = "{allowedby}:", database = -1).
What is implemented, against sdks/CONTRACT.md:
- Core, all of it: configuration with validation; the route map (classes, class by amount, levels, resources,
amounts, authn, tier, lifetime); discovery (
/.well-known/allowedbywith the signed organisation profile andLinkheader,/openapi.json,/.well-known/api-catalog, byte-compatible with Python'sjson.dumpsoutput); ABY-2 §5 steps 1-10 (proof JWT or RFC 9421, passports, grants and delegation chains, WebAuthnhuman_sigand batch approvals,human.reg,initiator, status lists with per-class freshness, lifetimes, ABY-3 constraints, request digest and single use, replay set, TOFU or OAID-5 trust lists with programs, vouching and witnesses, EdDSA and ES256 only); challenges with the service-initiated approval for write-hard and irreversible routes; background refresh; the context;MemoryStoreandRedisStore; the key file; the ASP.NET Core middleware. - Extended, implemented: account linking (
LinkStart,/allowedby/link,requireLinkandaccountParam; ABY-3 §6), AllowedBy-Nonce (Nonce; ABY-2 §3.2), level profiles (levelProfile; OAID-7 §5.3), rate limits (Rate), tenants and tenant budgets (Tenants; ORG-1 §3.3, §5.3). Each passes its files ofvectors/ext/(profiles.json,features) and its scenarios ofsdks/interop/ext/interop_ext.py, and is mutation tested (sdks/dotnet/tools/mutate.py). - Extended, not implemented (the route options are refused at construction): the disclosure callback and JWE
decryption (
/allowedby/callback), authority policies, company mandates (a tenant that asks for one refuses every request), the audit sink and the admin console. The disclosure key is kept in the key file but not published.