# AllowedBy for C# # How it works Four parties take part: the **agent**, your **app**, the **person**, and a **node** that the person and your app trust. ## Three documents | Document | Who signs it | What it says | |---|---|---| | Passport | The node | Which agent this is, who operates it, and which key it holds | | Grant | The person (passkey) and the node | What the person approved, for which app, for how long, with which limits | | Proof | The agent | This request: method, address, body and time, with the agent's key | The agent sends the first two in `Allowed-By` and the proof in `AllowedBy-Proof`. ## What your app checks The SDK does all of this offline, on each request, in about a millisecond: 1. The passport or grant comes from a node you trust, is not expired, and is not withdrawn. 2. The person's passkey signed exactly this grant, and their identity level is enough for the route. 3. The proof is for this exact request, by the agent the grant names, and was never seen before. 4. The grant covers the action, the resource and the amount. 5. A serious action has an approval made for this request only, and it has not been used. Anything unknown, missing or unreadable is refused. See [error codes](https://docs.allowedby.com/errors) for each refusal. ## Levels: how sure you are of the person | Level | The person | Use it for | |---|---|---| | 0 | is not asked: only the agent is identified | Public or per-agent data | | 1 | tapped a passkey | Everyday actions | | 2 | has a verified legal identity, and tapped a passkey | Orders, contracts, anything hard to undo | | 3 | is verified at the highest level, with a hardware passkey | Payments and signatures of value | ## Classes: how serious the action is | Class | Example | Approval | |---|---|---| | `read` | List notes | Reused until it ends | | `write` | Add a note | Reused until it ends | | `write-hard` | Delete, publish | For that request, once | | `irreversible` | Pay, sign | For that request, once | For the last two, your app creates the approval itself. The agent cannot change what the person will read. ## The node A node issues passports, shows the approval page, and countersigns grants. It learns what was approved, never the data in your app. You choose which nodes to trust: one hosted node, your own, or a signed list. --- # 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`](https://docs.allowedby.com/guides/accept-agents); 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): ```bash dotnet add reference ../allowedby/sdks/dotnet/src/AllowedBy.AspNetCore/AllowedBy.AspNetCore.csproj dotnet add reference ../allowedby/sdks/dotnet/src/AllowedBy.Redis/AllowedBy.Redis.csproj ``` Once 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. ```csharp 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(), 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): ```bash pip install -r requirements.txt python demo/run.py --port 8700 ``` In another, run the app: ```bash export ALLOWEDBY_ORIGIN=http://localhost:5000 ALLOWEDBY_NODE=http://localhost:8700 dotnet run --project sdks/dotnet/examples/Recipes/Quickstart --urls http://localhost:5000 ``` The same on Windows (PowerShell): ```powershell $env:ALLOWEDBY_ORIGIN = "http://localhost:5000"; $env:ALLOWEDBY_NODE = "http://localhost:8700" dotnet run --project sdks/dotnet/examples/Recipes/Quickstart --urls http://localhost:5000 ``` Call it without a passport: ```bash curl -i http://localhost:5000/.well-known/allowedby curl -i http://localhost:5000/notes ``` The 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: ```bash 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:5000 ``` With 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). | | `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 `:*`. 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](#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](#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](#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`): ```csharp o.Templates["notes:read"] = "Read your notes"; // English, for the summary and the line o.Templates["invoices:pay"] = new AllowedByTemplate { Summary = new Dictionary { ["en"] = "Pay {scope}, up to {amount.max} {amount.currency}", ["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}", }, Lines = new Dictionary { ["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`). 1. **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, valid `ttl` seconds (1 to 86400). A new code revokes no older one. Show it only to the signed-in owner of the account. 2. **The request.** The agent sends `POST /allowedby/link` with `{"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 with `400 invalid_request` before 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. 3. **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}`. 4. **The routes.** On a route with `requireLink: true`, a person who has not linked is refused with `403 human_not_linked`. When the path has the `accountParam` parameter (default `account`), 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 (no `human.id` for it) is refused with `401 grant_insufficient`, here and on `POST /allowedby/link`: an empty id would match every such approval. Under rule 5, a route covers a `requireLink` route 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`). 5. **Your authorisation.** A route whose path names no account accepts any linked person. To decide yourself, set `o.LinkAuthorize = (account, route, values) => ...` (Python's `link_authorize`): only `true` passes; `false`, or an exception it throws, refuses with `403 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. 6. **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. A `requireLink` route 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 throws `ArgumentException` for an account `LinkStart` refuses. From `sdks/dotnet/examples/interop_ext/Program.cs`, which `sdks/interop/ext/interop_ext.py` runs against a real node: ```csharp 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_signature` and a fresh nonce in the `AllowedBy-Nonce` response header. The agent signs again with it (the proof's `nonce` claim) and retries once, whatever the route's class. With the RFC 9421 profile (`o.Rfc9421`), the nonce is the request's `AllowedBy-Nonce` header, and counts only when the signature covers it; a covered value that is no base64url nonce is `401`. - **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 a `KeyFile`, 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: true` while `o.Nonce` is 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 example `new Dictionary { ["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_required` counts); a call refused by a limit counts for neither. The window slides on `o.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: ```csharp Route("POST", "/drafts", "drafts:write", cls: "write", level: 1, resource: "draft:new", nonce: true, summary: "Save a draft", body: new Dictionary { ["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 { ["actor"] = [20, 60], ["operator"] = [1000, 60] }; ``` ## 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](#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`): ```csharp 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 { ["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 { ["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(); ``` ```csharp using System.Globalization; using AllowedBy; using AllowedBy.AspNetCore; /// The endpoints: ordinary minimal APIs that take the verified context as a parameter. internal static class NoteEndpoints { private static readonly Dictionary> 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)); } /// 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. private static List 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): ```csharp using AllowedBy.AspNetCore; var builder = WebApplication.CreateBuilder(args); var config = builder.Configuration; builder.WebHost.UseUrls("http://localhost:" + (config["PORT"] ?? "5000")); builder.Services.AddSingleton(); 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(); ``` ```csharp using AllowedBy.AspNetCore; using Microsoft.AspNetCore.Mvc; namespace AllowedBy.Examples.Mvc; /// The person's notes. The routes, their levels and their sentences are in appsettings.json. [ApiController] [Route("notes")] public sealed class NotesController(NoteStore store) : ControllerBase { /// GET /notes (notes:read, level 1). [HttpGet] public IActionResult List([FromAllowedBy] AllowedByContext ctx) => Ok(new { notes = store.List(Person(ctx)) }); /// POST /notes (notes:write, level 1), body {"text": "..."}. [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) }); /// DELETE /notes/{id} (notes:delete, write-hard, level 2): the person approved this exact request. [HttpDelete("{id}")] public IActionResult Delete(string id, [FromAllowedBy] AllowedByContext ctx) { store.Delete(Person(ctx), id); return Ok(new { deleted = id }); } /// 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. private static string Person(AllowedByContext ctx) => ctx.HumanId ?? throw new InvalidOperationException("HumanId is null: level-0 routes have no person; use level 1+"); } /// The body of POST /notes. /// The note. public sealed record NewNote(string? Text); ``` ```csharp using AllowedBy.AspNetCore; using Microsoft.AspNetCore.Mvc; namespace AllowedBy.Examples.Mvc; /// GET /me (level 0: the agent's passport only) and GET /health (outside the route map: unchecked). [ApiController] public sealed class AgentController : ControllerBase { /// Which agent is calling. [HttpGet("/me")] public IActionResult Me([FromAllowedBy] AllowedByContext ctx) => Ok(new { agent = ctx.Agent, @operator = ctx.Operator, level = ctx.Level }); /// The app's own path. [HttpGet("/health")] public IActionResult Health() => Ok(new { ok = true }); } ``` ```json { "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`): ```csharp 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 { ["text"] = "the note" }), Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note"), ], Templates = new Dictionary { ["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>(); 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(k!, http.Request.Headers[k] ?? "")).ToList(); if (!aby.MustCheck(new AllowedByRequest(method, path, query, headers, ReadOnlyMemory.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 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 { ["Content-Type"] = "application/json" }, JsonSerializer.SerializeToUtf8Bytes(answer, web)); static async Task Send(HttpListenerContext http, int status, IReadOnlyDictionary headers, ReadOnlyMemory 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](#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: ```csharp 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(ConnectionMultiplexer.Connect(config["REDIS"] ?? "localhost:6379")); builder.Services.AddSingleton(sp => new RedisStore(sp.GetRequiredService())); 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 { ["en"] = "Pay {scope}, up to {amount.max} {amount.currency}", ["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}", }, Lines = new Dictionary { ["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's `key_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 atomic `link`, 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. `RedisStore` uses compare-and-set transactions; its keys share one hash tag (`{allowedby}:`), so it also works on Redis Cluster. Register any `IAllowedByStore` in DI, or set `o.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 `count` and `amount` totals. 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) and `o.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**: `AddAllowedBy` runs the refresh as a hosted service every `RefreshSeconds` (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 with `untrusted_node` or `503 status_stale` (sdks/CONTRACT.md §2 item 4); without ASP.NET Core, the first `CheckAsync` calls wait for the first refresh of `RunAsync` the 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**: `Origin` is your public origin. The SDK rebuilds each request's URL from `Origin` and the path as received (the raw request target), and ignores `Host` and `X-Forwarded-*`. A proxy must not rewrite the path. - **Clock**: `o.Clock` is a `TimeProvider`; every time check uses it (proofs from -120 s to +60 s, expiry, store deadlines). - **Listening**: the example listens on `ALLOWEDBY_BIND` (default `127.0.0.1`, loopback only) and `PORT` (default `8080`), unless `--urls` or `ASPNETCORE_URLS` names the addresses; an empty value counts as unset. The container sets `ALLOWEDBY_BIND=0.0.0.0`. Run it in a container (`sdks/dotnet/examples/Production/Dockerfile`): ```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"] ``` ```bash docker build -f sdks/dotnet/examples/Production/Dockerfile -t notes . ``` ```bash docker run --rm --network host -e ALLOWEDBY_ORIGIN=http://localhost:8080 -e ALLOWEDBY_NODE=http://localhost:8700 notes ``` ## Agents 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`](https://docs.allowedby.com/sdk/python) and [`docs/sdk/js.md`](https://docs.allowedby.com/sdk/js), 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/`; 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](#account-linking). | | `budget_exceeded` | 403 | A tenant budget. | Not produced by this SDK. | | `rate_limited` | 429 | Too many requests from this agent or operator. `Retry-After: 60`. | The agent waits, then retries: [Rate limits](#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): ```bash dotnet run --project sdks/dotnet/tests/AllowedBy.Vectors -c Release -f net10.0 -- vectors ``` It prints each failure and `N/N cases passed` (453/453), and exits 1 on any failure or any case it cannot run. Unit tests, real requests through the middleware (WebApplicationFactory) and the Redis store: ```bash 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 Release ``` On Windows (PowerShell): ```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 Release ``` The 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): ```bash 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): ```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`. | | `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)`, `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)`, `AddAllowedBy(IConfiguration section, Action?)`, `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/allowedby` with the signed organisation profile and `Link` header, `/openapi.json`, `/.well-known/api-catalog`, byte-compatible with Python's `json.dumps` output); ABY-2 §5 steps 1-10 (proof JWT or RFC 9421, passports, grants and delegation chains, WebAuthn `human_sig` and 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; `MemoryStore` and `RedisStore`; the key file; the ASP.NET Core middleware. - **Extended, implemented**: account linking (`LinkStart`, `/allowedby/link`, `requireLink` and `accountParam`; ABY-3 §6), AllowedBy-Nonce (`Nonce`; ABY-2 §3.2), level profiles (`levelProfile`; OAID-7 §5.3) and rate limits (`Rate`). Each passes its files of `vectors/ext/` (`profiles.json`, `features`) and its scenarios of `sdks/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`), tenants and tenant budgets, authority policies, company mandates, the audit sink and the admin console. The disclosure key is kept in the key file but not published. --- # Error codes Every SDK answers the same codes with the same statuses; `tools/docs.py` checks this table and every language guide against the verifier. A refusal is `application/problem+json` with `type: https://allowedby.org/errors/`. A `401` that the agent can resolve also carries a challenge in `WWW-Authenticate: AllowedBy ...` (ABY-2 §6). `429` and `503` carry `Retry-After`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a header is repeated or unreadable | Fix the request | | `passport_required` | 401 | No `Allowed-By` header | The agent gets a passport from its node and retries | | `invalid_signature` | 401 | A signature, proof, chain or `human_sig` check failed, or the proof was replayed | The agent signs a fresh proof; check its clock (-120 s to +60 s) | | `untrusted_node` | 401 | The grant or passport comes from a node this service does not trust | Use a trusted node, or add it (trust list) | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses | Retry later; the node operator fixes its witnesses | | `grant_required` | 401 | The route needs a person's approval and the agent showed only its passport | The agent asks the person (the challenge says what) | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator) | The agent asks for a grant that covers it | | `level_insufficient` | 401 | The person's identity level is below the route's | The person verifies their identity to that level | | `qes_required` | 401 | The route needs a qualified electronic signature | The person signs with a qualified signature | | `authority_required` | 401 | The organisation's co-approvers have not approved | The co-approvers approve | | `mandate_required` | 401 | The route needs a company mandate | The person acts with their company's mandate | | `expired` | 401 | The grant has expired | The agent asks again | | `not_yet_valid` | 401 | The grant's `nbf` is in the future | Check clocks; retry | | `revoked` | 401 | The person or the node withdrew the grant | The agent asks again; respect the person's choice | | `actor_expired` | 401 | The agent's key (passport) expired | The agent gets a new passport and rebinds its grants | | `class_lifetime_exceeded` | 401 | The grant lives longer than the route's class allows | The agent asks for a shorter grant | | `single_use_consumed` | 401 | A one-time grant was already used | The agent asks again for this request | | `capability_denied` | 403 | Not allowed at all (route unknown, operator not accepted, over a ceiling) | Do not retry | | `tier_insufficient` | 403 | The agent's key custody or the passkey kind is too weak | Use a stronger custody tier or passkey | | `human_not_linked` | 403 | The person has not linked their account here | The person links their account (`aby:link`) | | `budget_exceeded` | 403 | The organisation's budget for this action is used up | Wait for the next period or raise the budget | | `rate_limited` | 429 | Too many requests from this agent or operator | Wait (`Retry-After`) | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two grants (depth 1) | Send a shorter chain | | `status_stale` | 503 | The revocation list is too old to decide, or the replay store is unavailable | Retry after `Retry-After` | ## How an agent reacts - **Asks the person, then retries once:** `grant_required`, `grant_insufficient`, `level_insufficient`, `qes_required`, `expired`, `revoked`, `class_lifetime_exceeded`, `single_use_consumed`. - **Gets a new passport or rebinds:** `passport_required`, `actor_expired`. - **Waits, then retries:** `rate_limited`, `status_stale`. - **Signs again, once:** `invalid_signature` (a fresh proof; check the clock and the URL). - **Stops:** every other code. Retrying cannot succeed until someone changes something. --- # Build with an AI assistant Coding assistants integrate AllowedBy well when they read these pages rather than guess. Give them one of the following. ## The documentation as tools (MCP) ```bash claude mcp add --transport http allowedby-docs https://docs.allowedby.com/mcp ``` The assistant can then search the documentation, read a page, get a recipe in your language and look up an error. Any assistant that supports MCP over HTTP can use the same address. ## One file per language Everything needed to accept agents in one language, in one Markdown file: | Language | File | |---|---| | Python | [llms/python.txt](https://docs.allowedby.com/llms/python.txt) | | JavaScript | [llms/js.txt](https://docs.allowedby.com/llms/js.txt) | | Go | [llms/go.txt](https://docs.allowedby.com/llms/go.txt) | | Java | [llms/java.txt](https://docs.allowedby.com/llms/java.txt) | | C# | [llms/dotnet.txt](https://docs.allowedby.com/llms/dotnet.txt) | | PHP | [llms/php.txt](https://docs.allowedby.com/llms/php.txt) | | Ruby | [llms/ruby.txt](https://docs.allowedby.com/llms/ruby.txt) | | Rust | [llms/rust.txt](https://docs.allowedby.com/llms/rust.txt) | The index of every page is [llms.txt](https://docs.allowedby.com/llms.txt), and all guides together are [llms-full.txt](https://docs.allowedby.com/llms-full.txt). Any page is also Markdown at its own address with `.md` added. ## A prompt that works ```text Read https://docs.allowedby.com/llms/python.txt. Then add AllowedBy to this app: - list the routes an agent may call, and propose a capability, class and level for each; ask me before going on; - write the sentence a person will sign for each capability; - add the middleware, and key every query on the person's id from the context; - run the app, show me that a protected route answers 401, and write the tests from the "test" recipe. ``` Change `python` to your language. ## Rules an assistant must keep - Never take the person's identity from the agent's input: use the id in the verified context. - Never catch a refusal and continue. - Never log `Allowed-By`, `AllowedBy-Proof` or a request body. - Use a shared store as soon as there is more than one process, and a key file in production. - Put the middleware outside anything that rewrites the path or the method. A weekly test gives an assistant only these public pages, asks it to integrate AllowedBy in a new app, and runs the end-to-end scenarios on the result. --- # Recipes in C# (each is run against a real node on every version) ## Quickstart A whole app that lets agents in with the person's approval. ```dotnet 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(), person = ctx.HumanId }); app.Run(); ``` ## See which agent is calling Know the agent and its verified operator, before any person is involved. ```dotnet routes.Add(Route("GET", "/me", level: 0, summary: "Which agent is calling")); app.MapGet("/me", (AllowedByContext ctx) => new { agent = ctx.Agent, @operator = ctx.Operator }); ``` ## Let an agent read The person approves once with a passkey; the approval is reused until it expires or they withdraw it. ```dotnet routes.Add(Route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes")); templates["notes:read"] = "Read your notes"; app.MapGet("/notes", (AllowedByContext ctx) => new { notes = notes.List(Person(ctx)) }); // The person the data belongs to. A level-0 route has no person (HumanId is null): stop here rather than key // anyone's data by a missing id. static string Person(AllowedByContext ctx) => ctx.HumanId ?? throw new InvalidOperationException("HumanId is null: level-0 routes have no person; use level 1+"); ``` ## Let an agent write A change the person can undo: one approval, reused like a read. ```dotnet routes.Add(Route("POST", "/notes", "notes:write", cls: "write", level: 1, resource: "note:*", summary: "Add a note", body: new Dictionary { ["text"] = "the note" })); templates["notes:write"] = "Add and change your notes"; app.MapPost("/notes", (NoteInput input, AllowedByContext ctx) => Results.Json(notes.Add(Person(ctx), input.Text ?? ""), statusCode: 201)); ``` ## Ask before deleting A change that is hard to undo: your app asks the person for that exact request, and the approval works once. ```dotnet routes.Add(Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note")); templates["notes:delete"] = "Delete {scope}"; app.MapDelete("/notes/{id}", (string id, AllowedByContext ctx) => // The person approved this exact request, and it works once. notes.Delete(Person(ctx), id) ? Results.Json(new { deleted = id }) : Results.Json(new { error = "no such note" }, statusCode: 404)); ``` ## Take a payment The person approves the amount and the payee; any other amount or payee is refused. ```dotnet routes.Add(Route("POST", "/payees/{payee}/payments", "payments:send", cls: "irreversible", level: 2, resource: "payee:{payee}", amountField: "/amount", summary: "Pay someone", body: new Dictionary { ["amount"] = "a decimal string, e.g. 40.00", ["currency"] = "e.g. EUR" })); templates["payments:send"] = "Pay {amount.max} {amount.currency} to {scope}"; app.MapPost("/payees/{payee}/payments", (string payee, Payment payment) => // The payee, the amount and the currency are the ones the person approved. Results.Json(new { paid = payment.Amount, currency = payment.Currency, to = payee }, statusCode: 201)); ``` ## Take a high-value payment Level 3: a verified identity and a hardware passkey. Anything weaker is refused. ```dotnet routes.Add(Route("POST", "/payees/{payee}/transfers", "transfers:send", cls: "irreversible", level: 3, authn: "hardware", resource: "payee:{payee}", amountField: "/amount", summary: "Send a bank transfer", body: new Dictionary { ["amount"] = "a decimal string, e.g. 4000.00", ["currency"] = "e.g. EUR" })); templates["transfers:send"] = "Transfer {amount.max} {amount.currency} to {scope}"; app.MapPost("/payees/{payee}/transfers", (string payee, Payment order, AllowedByContext ctx) => // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. Results.Json(new { sent = order.Amount, currency = order.Currency, to = payee, level = ctx.Level }, statusCode: 201)); ``` ## Set a spending limit The person approves an amount per month once; the SDK keeps the total and refuses what goes over. ```dotnet routes.Add(Route("POST", "/orders", "orders:place", cls: "write", level: 1, resource: "order:new", amountField: "/total", summary: "Place an order", body: new Dictionary { ["total"] = "a decimal string, e.g. 60.00", ["currency"] = "e.g. EUR" })); templates["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}"; app.MapPost("/orders", (Order order) => // The SDK keeps the total of the period: an order over the limit the person approved never gets here. Results.Json(new { ordered = order.Total, currency = order.Currency }, statusCode: 201)); ``` ## Start and cancel a subscription The person approves the plan and its monthly price once; you charge it until they cancel. ```dotnet routes.Add(Route("POST", "/plans/{plan}/subscription", "plans:subscribe", cls: "write-hard", level: 1, resource: "plan:{plan}", amountField: "/monthly", summary: "Subscribe to a plan", body: new Dictionary { ["monthly"] = "the price per month, e.g. 12.00", ["currency"] = "EUR" })); routes.Add(Route("GET", "/subscription", "plans:read", level: 1, resource: "plan:*", summary: "Your subscription")); routes.Add(Route("DELETE", "/subscription", "plans:cancel", cls: "write-hard", level: 1, resource: "plan:mine", summary: "Cancel your subscription")); templates["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel"; templates["plans:read"] = "See your subscription"; templates["plans:cancel"] = "Cancel your subscription"; app.MapPost("/plans/{plan}/subscription", (string plan, Price price, AllowedByContext ctx) => // Approved once, with the price: your billing charges it every month (Subscriptions.cs) until it is cancelled. Results.Json(subscriptions.Start(Person(ctx), plan, price.Monthly), statusCode: 201)); app.MapGet("/subscription", (AllowedByContext ctx) => subscriptions.Get(Person(ctx)) is { } subscription ? Results.Json(subscription) : Results.Json(new { error = "no subscription" }, statusCode: 404)); app.MapDelete("/subscription", (AllowedByContext ctx) => subscriptions.Cancel(Person(ctx)) is { } subscription ? Results.Json(subscription) : Results.Json(new { error = "no subscription" }, statusCode: 404)); ``` ## Accept a sub-agent An agent hands a sub-agent part of its approval, never more, and it ends when the person withdraws the first. ```dotnet routes.Add(Route("GET", "/notes/{id}/summary", "notes:read", level: 1, resource: "note:{id}", summary: "Summarise one note")); app.MapGet("/notes/{id}/summary", (string id, AllowedByContext ctx) => { // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and HumanId is the same. if (notes.Get(Person(ctx), id) is not { } note) { return Results.Json(new { error = "no such note" }, statusCode: 404); } var words = note.Text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length; return Results.Json(new { words, delegated = ctx.Chain.Count > 1 }); }); ``` ## Let the person withdraw The person takes an approval back on their node; your app refuses it from the next refresh. ```dotnet routes.Add(Route("GET", "/export", "notes:export", level: 1, resource: "note:*", summary: "Export your notes")); templates["notes:export"] = "Export your notes"; app.MapGet("/export", (AllowedByContext ctx) => // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. new { approval = ctx.Gid, notes = notes.List(Person(ctx)) }); ``` ## Serve only the person's own data human_id is the same person every time at your app: look their data up with it. ```dotnet routes.Add(Route("GET", "/notes/{id}", "notes:read", level: 1, resource: "note:{id}", summary: "Read one note")); app.MapGet("/notes/{id}", (string id, AllowedByContext ctx) => // Person(ctx) is this person's id at your app, always the same. Look up with it, never by note id alone. notes.Get(Person(ctx), id) is { } note ? Results.Json(note) : Results.Json(new { error = "no such note" }, statusCode: 404)); ``` ## Refuse in your own handler Your rules still apply: the agent receives your status and your JSON, and can correct itself. ```dotnet routes.Add(Route("PUT", "/notes/{id}", "notes:write", cls: "write", level: 1, resource: "note:{id}", summary: "Change a note", body: new Dictionary { ["text"] = "1 to 280 characters" })); app.MapPut("/notes/{id}", (string id, NoteInput input, AllowedByContext ctx) => { var text = input.Text ?? ""; if (text.EnumerateRunes().Count() is < 1 or > 280) // characters: an emoji counts as one { return Results.Json(new { error = "text: 1 to 280 characters" }, statusCode: 422); // the agent gets this } return notes.Update(Person(ctx), id, text) is { } note ? Results.Json(note) : Results.Json(new { error = "no such note" }, statusCode: 404); }); ``` ## Test your app Run your app's tests without a browser, a phone or a node. ```dotnet using System.Net; using System.Text.Json; using Microsoft.AspNetCore.Mvc.Testing; using Xunit; public sealed class NotesTests(WebApplicationFactory app) : IClassFixture> { [Fact] public async Task A_request_without_a_passport_is_refused() { var response = await app.CreateClient().GetAsync("/notes"); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Contains("passport_required", response.Headers.WwwAuthenticate.ToString()); } [Fact] public async Task Agents_see_the_sentence_the_person_approves() { var json = await app.CreateClient().GetStringAsync("/.well-known/allowedby"); using var discovery = JsonDocument.Parse(json); var sentence = discovery.RootElement.GetProperty("templates").GetProperty("notes:read").GetProperty("summary"); Assert.Equal("Read your notes", sentence.GetProperty("en").GetString()); } } ```