Skip to main content
Version: 3.x

Authorization

UnambitiousFx.Synapse.Authorization authorizes requests inside the pipeline, so the same rules apply whether a request comes from an HTTP endpoint, an MCP tool, a background job or a CLI. Endpoint-level ASP.NET Core policies do not cover those other transports.

dotnet add package UnambitiousFx.Synapse.Authorization

:::info HTTP status codes

Denials are the typed UnauthenticatedFailure and UnauthorizedFailure from UnambitiousFx.Functional, so IHttpInvoker / IMvcInvoker answer 401 for an anonymous caller and 403 for an authenticated caller who lacks access, never a 500. To change a status, configure Functional's mapper with AddResultHttp before AddSynapseAspNetCore:

builder.Services.AddResultHttp(o => o.AddMapper<UnauthorizedFailure>(StatusCodes.Status401Unauthorized));
builder.Services.AddSynapseAspNetCore(); // TryAddSingleton: keeps the mapper above

:::

Setup​

Register an ICurrentPrincipal for your caller's identity, then call AddSynapseAuthorization. In ASP.NET Core, AddSynapseClaimsPrincipal registers the ready-made ClaimsCurrentPrincipal over HttpContext.User:

services.AddHttpContextAccessor();
services.AddSynapseClaimsPrincipal(sp => sp.GetRequiredService<IHttpContextAccessor>().HttpContext?.User);
services.AddSynapse(cfg => cfg.AddRegisterGroup(new RegisterGroup()));
services.AddSynapseAuthorization(o =>
{
o.QueryScope = "read"; // default
o.CommandScope = "write"; // default
o.Policy<LoanAccessPolicy>(); // IResourceAccessPolicy, scoped
o.DenialRecorder<AuditDenials>(); // IAuthorizationDenialRecorder, scoped, optional
});

ClaimsCurrentPrincipal handles the usual claim traps:

  • Scopes come from scope, scp (Microsoft Entra ID) and the long name ASP.NET Core maps scp to. Each claim is split on spaces ("read write"), and scopes are compared case-sensitively.
  • Roles go through ClaimsPrincipal.IsInRole, so the authentication handler's RoleClaimType applies. Add more types (role, roles) with RoleClaimTypes.
  • Id is sub, then ClaimTypes.NameIdentifier.
  • IsAuthenticated comes from User.Identity.IsAuthenticated, not from the presence of claims.

Change the claim types with the second argument: AddSynapseClaimsPrincipal(accessor, o => o.ScopeClaimTypes = ["permissions"]). Outside HTTP (a background job, an MCP session), create new ClaimsCurrentPrincipal(claimsPrincipal) yourself, or implement ICurrentPrincipal directly.

You can call AddSynapseAuthorization more than once, for example from a shared module and then from the host. Every call configures the same options, so a later call's QueryScope / CommandScope replace the earlier ones, and each call's policy and recorders are registered. An empty or whitespace default scope throws ArgumentException; use null to turn it off.

Anonymous requests​

Once authorization is registered, every request needs an authenticated caller. Mark the requests that must work without one, such as sign-in, sign-up or password reset, with IAllowAnonymous:

public sealed record SignIn(string Email, string Password) : ICommand<SessionToken>, IAllowAnonymous;

An IAllowAnonymous request:

  • passes the actor check, whoever the caller is;
  • is exempt from the default scope rule, because an anonymous caller has no write scope to give;
  • still gets the checks it declares itself. IRequiresRole, IRequiresScope and IResourceScoped apply as usual. A request that combines them with IAllowAnonymous therefore needs a caller who has them, which in practice means an authenticated one. Keep public requests free of those markers.

The checks​

Five behaviors run on every Result and Result<T> request, in a fixed order. The first one that denies the request short-circuits the pipeline: the handler and the later checks do not run.

OrderBehaviorApplies toDenial
AuthorizationBehaviorOrder.ActorActorAuthorizationBehaviorevery request except IAllowAnonymousUnauthenticatedFailure when ICurrentPrincipal.IsAuthenticated is false
AuthorizationBehaviorOrder.RoleRoleAuthorizationBehaviorIRequiresRoleUnauthorizedFailure when the caller is not in Role
AuthorizationBehaviorOrder.ScopeScopeAuthorizationBehaviorqueries, commands, IRequiresScopeUnauthorizedFailure when the caller lacks the scope
AuthorizationBehaviorOrder.RequestPolicyRequestPolicyAuthorizationBehaviorrequest types with an IRequestAccessPolicy<TRequest>UnauthorizedFailure when the policy says no
AuthorizationBehaviorOrder.ResourceResourceAuthorizationBehaviorIResourceScoped, IOptionallyResourceScoped with a resourceUnauthorizedFailure when the policy says no

All five run in PipelineStage.Authorization: their Order values sit in that stage's band (PipelineStages.StartOf(PipelineStage.Authorization) + 1000, + 2000, ...). Observability behaviors (tracing, logging) therefore wrap them, and validation and transactions run inside them. See pipeline stages.

Place your own behaviors by stage rather than by number:

// tracing wraps authorization
[PipelineBehavior(Stage = PipelineStage.Observability)]
public sealed class TracingBehavior<TRequest, TResult> : IResultPipelineBehavior<TRequest, TResult> { ... }

// auditing runs once every check has passed
[PipelineBehavior(Stage = PipelineStage.Authorization, After = typeof(ResourceAuthorizationBehavior<,>))]
public sealed class AuditBehavior<TRequest, TResult> : IResultPipelineBehavior<TRequest, TResult> { ... }

Use cfg.ConfigureBehaviorOrdering(...) for a behavior the source generator does not see.

:::warning Putting a behavior between two checks Before / After only order the two behaviors they name. A behavior declared After = Actor, Before = Role runs before Role, but Scope and Resource, which it does not name, can then run before Role too. To sit between two checks, use the numeric gaps instead, which keep the checks in order: Order => AuthorizationBehaviorOrder.Resource - 1 loads a tenant just before the resource check. :::

Stream requests​

AddSynapseAuthorization() also authorizes stream requests (IStreamRequest<T>), with no extra registration. StreamAuthorizationBehavior runs the same checks in the same order, at AuthorizationBehaviorOrder.Actor. The markers, the resource and request policies, the denial recorders and the denial failure all apply. A stream counts as a query, so it needs QueryScope unless it implements IRequiresScope.

The checks run once, before the handler starts. A denied stream yields a single failed item (UnauthenticatedFailure or UnauthorizedFailure), and the handler never runs:

await foreach (var item in invoker.InvokeStreamAsync(new ExportLoans(householdId), ct))
{
if (item.TryGetFailure(out var failure))
{
// denied: this is the only item
break;
}
// ...
}

Over HTTP, IHttpInvoker.InvokeStreamAsync turns that denied first item into the matching 401 or 403 Problem Details response instead of streaming an empty 200.

The checks share one behavior on streams, so a behavior of your own cannot sit between two of them.

Markers​

// Default scope: a query needs QueryScope ("read").
public sealed record GetLoan(Guid Id) : IQuery<LoanView>, IResourceScoped
{
public string ResourceId => Id.ToString();
public string Access => "read";
}

// Default scope: a command needs CommandScope ("write"), plus the admin role.
public sealed record PurgeLoans : ICommand, IRequiresRole
{
public string Role => "admin";
}

// Its own scope instead of "read".
public sealed record ExportLoans : IQuery<byte[]>, IRequiresScope
{
public string Scope => "loans:export";
}

A request that targets a resource only for some arguments implements IOptionallyResourceScoped instead:

// All the caller's loans, or one account's.
public sealed record ListLoans(Guid? AccountId) : IQuery<LoanView[]>, IOptionallyResourceScoped
{
public string? OptionalResourceId => AccountId?.ToString();
public string Access => "read";
}

When OptionalResourceId is null, the resource check is skipped and the policy is not called. Otherwise the policy receives the request as usual, with ResourceId equal to OptionalResourceId. The actor, role and scope checks run either way.

  • Scopes. A request that implements IRequiresScope needs its Scope. Otherwise an IQuery<T> needs QueryScope and an ICommand / ICommand<T> needs CommandScope. A plain IRequest that declares no scope needs none.
  • Turning the default off. o.DisableDefaultScopes() (or setting QueryScope / CommandScope to null) stops the query / command rule. Requests that implement IRequiresScope are still checked.
  • Roles. IRequiresRole.Role is checked with ICurrentPrincipal.IsInRole.
  • Blank values are bugs. An IRequiresScope.Scope or IRequiresRole.Role that is null, empty or whitespace, or an IOptionallyResourceScoped.OptionalResourceId that is empty or whitespace, throws InvalidOperationException naming the request type when the request is dispatched. It is not treated as "no requirement" (that would fail open), and it is not a silent denial of every caller (that would hide the bug behind ordinary 401/403s). Recorders are not called for it, because no caller was denied.

Resource policy​

Only the policy is application-specific: who may access which resource.

public sealed class LoanAccessPolicy(LoansDbContext db) : IResourceAccessPolicy
{
public async ValueTask<bool> IsAllowedAsync(ICurrentPrincipal principal, IResourceScoped request,
CancellationToken cancellationToken = default)
{
var loanId = Guid.Parse(request.ResourceId);
return await db.Loans.AnyAsync(l => l.Id == loanId && l.OwnerId == principal.Id, cancellationToken);
}
}

request is the request itself, so you can pattern-match it to read more than ResourceId and Access. Without a registered policy, every IResourceScoped request is denied: the behavior fails closed.

Hiding a resource the caller cannot see​

A denied resource answers 403, which tells the caller the resource exists. To answer as if it did not exist, so that probing identifiers tells nothing, override CheckAsync and return ResourceAccess.Hidden:

public sealed class LoanAccessPolicy(LoansDbContext db) : IResourceAccessPolicy
{
public ValueTask<bool> IsAllowedAsync(ICurrentPrincipal principal, IResourceScoped request,
CancellationToken cancellationToken = default)
=> throw new NotSupportedException(); // CheckAsync is overridden, so the behaviors never call it

public async ValueTask<ResourceAccess> CheckAsync(ICurrentPrincipal principal, IResourceScoped request,
CancellationToken cancellationToken = default)
{
var loan = await db.Loans.FindAsync([Guid.Parse(request.ResourceId)], cancellationToken);
if (loan is null || !loan.IsVisibleTo(principal.Id))
{
return ResourceAccess.Hidden; // 404, same as a missing loan
}

return request.Access == "read" || loan.OwnerId == principal.Id
? ResourceAccess.Allowed
: ResourceAccess.Denied; // 403: the caller can read it, so it knows it exists
}
}
CheckAsync returnsFailureHTTPDenial reason
Allowednone, the request goes on
DeniedUnauthorizedFailure (UNAUTHORIZED)403ResourceAccessDenied
HiddenNotFoundFailure (NOT_FOUND), fixed message404ResourceHidden

By default CheckAsync maps IsAllowedAsync to Allowed or Denied, so existing policies are unchanged. Keep Denied for a caller who can read the resource but not do what the request asks: a 404 would look like a bug to someone who just read it. default(ResourceAccess) is Denied, so a value that was never set fails closed.

warning

The behaviors call CheckAsync, not IsAllowedAsync. A mocked policy (Substitute.For<IResourceAccessPolicy>()) set up on IsAllowedAsync alone now denies every request, because the mock's CheckAsync returns Denied: configure CheckAsync instead.

Request policies​

A request that creates a resource has no resource to check yet, but often still needs a check on what it asks for: an invoice for a customer the caller may bill, an account in a branch the caller belongs to, a booking in an open period. Write a policy for that request type:

public sealed class InvoiceCreationPolicy(IBillingRights rights) : IRequestAccessPolicy<CreateInvoice>
{
public ValueTask<bool> IsAllowedAsync(ICurrentPrincipal principal, CreateInvoice request,
CancellationToken cancellationToken = default)
=> rights.MayBillAsync(principal.Id!, request.CustomerId, cancellationToken);
}

services.AddSynapseAuthorization(o => o.RequestPolicy<CreateInvoice, InvoiceCreationPolicy>());

RequestPolicy<TRequest, TPolicy>() registers it as a scoped service, replacing any policy already registered for that request type. Registering IRequestAccessPolicy<CreateInvoice> in the container yourself works too.

  • It runs after the scope check and before the resource check, for requests and streams. A request type without a policy is not checked: no marker is needed.
  • A denial is an UnauthorizedFailure, reported to the recorders with the reason RequestDenied.

Recording denials​

Every denial is passed to each registered IAuthorizationDenialRecorder before the failure is returned:

public sealed class AuditDenials(ILogger<AuditDenials> logger) : IAuthorizationDenialRecorder
{
public ValueTask RecordAsync(AuthorizationDenial denial, CancellationToken cancellationToken = default)
{
logger.LogWarning("{Request} denied for {Principal}: {Reason} {Requirement} {Resource}",
denial.Request.GetType().Name, denial.PrincipalId, denial.Reason, denial.Requirement, denial.ResourceId);
return ValueTask.CompletedTask;
}
}

AuthorizationDenial carries the request, the Reason (Unauthenticated, MissingRole, MissingScope, ResourceAccessDenied, RequestDenied, ResourceHidden), the caller's Id, the missing role, scope or access in Requirement, and the ResourceId for resource denials.

Background work​

Jobs, schedulers, migrations and outbox handlers send requests through the same pipeline as users, but run as a technical identity that belongs to no user. Run them as SystemPrincipal.Instance instead of faking a principal that every policy must special-case:

// the worker host's container
services.AddSingleton<ICurrentPrincipal>(SystemPrincipal.Instance);

A principal whose ICurrentPrincipal.IsSystem is true skips the checks that SystemBypass names. A skipped check calls no policy and records no denial:

o.SystemBypassActor, role, scopeRequest policy, resource
SystemBypass.All (default)skippedskipped
SystemBypass.ResourceCheckschecked as for any callerskipped
SystemBypass.Nonechecked as for any callerchecked as for any caller

SystemPrincipal.Instance is authenticated, holds every scope and role, and its Id is system. For a system identity that should keep its role and scope checks, implement ICurrentPrincipal with IsSystem => true and only the scopes and roles it needs, and set o.SystemBypass = SystemBypass.ResourceChecks.

IsSystem is a default interface member that returns false, so existing ICurrentPrincipal implementations are unaffected.

Denial failures​

By default a denial returns an UnauthenticatedFailure (code UNAUTHENTICATED) or an UnauthorizedFailure (code UNAUTHORIZED) with a fixed English message such as Requires role 'admin'.. To give clients a domain code to branch on, and a message the application shows or translates, set DenialFailure:

services.AddSynapseAuthorization(o => o.DenialFailure = denial => denial.Reason switch
{
AuthorizationDenialReason.MissingRole => new UnauthorizedFailure("This action is reserved to administrators.")
{ Code = "core.admin_required" },
AuthorizationDenialReason.MissingScope => new UnauthorizedFailure($"The '{denial.Requirement}' scope is required.")
{ Code = "core.scope_required" },
_ => null // the default failure
});

It receives the same AuthorizationDenial as the recorders, for requests and streams alike, and runs only when a request is denied. The recorders are still called.

The failure keeps its type, since transports map it to 401 / 403 / 404 and the MCP invoker hides existence behind it. Return an UnauthenticatedFailure for Unauthenticated, a NotFoundFailure for ResourceHidden and an UnauthorizedFailure for every other reason. Any other type throws InvalidOperationException, so a denial cannot become a 404 or a 422 by mistake: only the resource policy decides to hide a resource (see Hiding a resource the caller cannot see).

Limits​

  • Events are not authorized.
  • The behaviors are registered closed for each request type, so the package works with Native AOT, value-type requests included.
  • AddSynapse and AddSynapseAuthorization must be called on the same IServiceCollection. A request registered in another collection (a child or tenant container, a collection built by copying descriptors) is not authorized.