Permission-based authorisation architecture: permissions vs roles, tenant-defined roles, token size and staleness vs per-request lookup, caching and invalidation, a dynamic IAuthorizationPolicyProvider with one generic handler, auditing and when to adopt an external engine (Zanzibar-style, OPA).
Separate permissions (fine-grained actions in code, such as invoices.approve) from roles (tenant-defined bundles of permissions stored as data). Endpoints only ever check permissions.
For tenant-defined roles I keep sub and tenant_id in the token and resolve permissions server-side, cached with HybridCache keyed by a permission version that is bumped on every role change. A custom IAuthorizationPolicyProvider turns "perm:invoices.approve" into a policy on demand, with one generic handler. The trade-off: freshness and flexibility in exchange for a cache you have to operate.
"I'd start by splitting two concepts that usually get blurred. Permissions are the fine-grained actions the code understands:
invoices.read,invoices.approve,payroll.export. They live in code as a catalogue, because a permission without code that checks it is meaningless. Roles are bundles of permissions, and in a SaaS product where customers define their own roles, roles are data per tenant. Endpoints never check roles, only permissions, so a customer creating an 'Accounts Payable Lead' role needs no deployment.Then the big decision: permissions in the token or looked up. Putting them in the access token is attractive because there's no lookup, but with [~150] permissions the token gets large, proxies and gateways start rejecting headers beyond [8 to 16 KB], and when an admin removes a permission the user keeps it until the token expires. So for this design I keep the token about identity:
sub,tenant_id, maybe a coarse plan claim. Permissions are resolved server-side from the user's roles in that tenant and cached inHybridCache, in-process L1 with Redis as L2, keyed by tenant, user and a permission version. When an admin changes a role, we bump the tenant's version and remove the cache tag, so the change is effective in seconds across every instance, with a short TTL as a backstop.In ASP.NET Core I don't register hundreds of policies. A custom
IAuthorizationPolicyProviderrecognises names likeperm:invoices.approveand builds a policy with aPermissionRequirementon demand, and onePermissionHandlerchecks the cached set. For example, at [company] we [moved from 40 hard-coded roles to tenant-defined roles this way]; role changes went from [a support ticket and a deploy] to [instant self-service], and the handler cost [under 0.1 ms] on a cache hit. The senior line: the token says who you are, the server decides what you can do, and the cache is designed around invalidation, not TTL."
| Approach | Strengths | Weaknesses | Fits |
|---|---|---|---|
| Permissions in the access token | No lookup, works across services | Token size, stale until expiry, leaks the permission model to clients | Few, stable permissions; short token lifetimes |
| Roles in token, permissions mapped in app | Small token, mapping changes without re-login | Role changes still stale until expiry | Fixed roles defined by you |
| Server-side lookup with cache | Fresh, small tokens, tenant-defined roles | Cache and invalidation to operate | Multi-tenant, customer-defined roles |
| External authorisation service (OpenFGA, OPA, Cedar) | Relationships, central policy, many services | Network hop, new infrastructure | Sharing models, many services, complex policies |
| Table | Owned by | Notes |
|---|---|---|
| Permission catalogue | Code (constants + migration seed) | Versioned with the application |
| Role (TenantId, Name) | Tenant admins | Customer-defined |
| RolePermission | Tenant admins | Audited |
| UserRole (TenantId, UserId, RoleId) | Tenant admins / SCIM | Audited, synced from IdP groups optionally |
| PermissionVersion (TenantId) | System | Bumped on any change |
With [~2,000] tenants and [~150] permissions, the cache hit rate was [above 99%], p95 authorisation overhead [0.08 ms] on hit and [4 ms] on miss, and role changes propagated across [12] instances in [under 2 seconds] via tag invalidation. Access tokens stayed under [1.5 KB].
Checks whether the candidate can design an authorisation model that scales across tenants and services, with clear reasoning about token contents, caching and freshness.
Green flags
Red flags
Bearer token { sub, tenant_id, scp }
-> AuthorizationMiddleware: endpoint metadata [RequiresPermission("invoices.approve")]
-> PermissionPolicyProvider.GetPolicyAsync("perm:invoices.approve")
-> new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
.AddRequirements(new PermissionRequirement("invoices.approve")).Build() (cached)
-> PermissionHandler
-> IPermissionService.GetAsync(tenant, user)
-> HybridCache L1 (memory) -> L2 (Redis) -> SQL: UserRole ⋈ RolePermission
-> set.Contains("invoices.approve") ? Succeed : no decision
exp. Revoking one permission means waiting or building revocation.Permissions in the token remain a good choice for a handful of stable, coarse permissions (OAuth scopes are exactly that).
Key: perms:{tenantId}:{userId}, tagged with tenant:{tenantId} and user:{userId}. On a role or assignment change, in the same transaction write an outbox message; a handler calls HybridCache.RemoveByTagAsync("tenant:{id}") (.NET 9+). L1 entries on other instances need a backplane or a short L1 expiry; HybridCache's L1 isn't invalidated across nodes on its own, so keep L1 at 30-60 seconds or broadcast invalidations (Redis pub/sub).
Alternative: put a perm_ver claim in the token and include the current version in the cache key; a version mismatch forces a reload.
IAuthorizationPolicyProvider is a singleton consulted for every policy name. Delegate unknown names to DefaultAuthorizationPolicyProvider, and cache built policies (policy objects are immutable). Since .NET 8 an attribute implementing IAuthorizationRequirementData can supply the PermissionRequirement directly, which avoids string parsing; the provider approach still helps for RequireAuthorization("perm:...") in Minimal APIs.
| Model | Question it answers | Example |
|---|---|---|
| RBAC | What can this role do? | Approvers can approve invoices |
| ABAC | Do attributes satisfy a rule? | Approve if amount < user's limit and same cost centre |
| ReBAC (Zanzibar, OpenFGA, SpiceDB) | Is there a relationship path? | User is editor of folder that contains doc |
Most SaaS products need RBAC for actions plus resource-based checks for ownership and a little ABAC for limits. Move to ReBAC when sharing and hierarchies dominate.
Log every role and permission change with who, when, before and after; expose it to tenant admins. For customers under the Privacy Act (APP 11 requires reasonable steps to protect personal information) or the Essential Eight (restricting administrative privileges), a reviewable access model and periodic access reviews are part of the answer.
perm:x and an unknown policy both resolve correctly.A permission catalogue, a dynamic policy provider, one generic handler and a cached permission service with tag invalidation.
// Authorization/Permissions.cs (.NET 10)
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
namespace Saas.Api.Authorization;
public static class Permissions
{
public const string InvoicesRead = "invoices.read";
public const string InvoicesApprove = "invoices.approve";
public const string PayrollExport = "payroll.export";
}
public sealed record PermissionRequirement(string Permission) : IAuthorizationRequirement;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequiresPermissionAttribute(string permission)
: AuthorizeAttribute(PermissionPolicyProvider.Prefix + permission);
public sealed class PermissionPolicyProvider(IOptions<AuthorizationOptions> options) : IAuthorizationPolicyProvider
{
public const string Prefix = "perm:";
private readonly DefaultAuthorizationPolicyProvider _fallback = new(options);
public Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
{
if (!policyName.StartsWith(Prefix, StringComparison.Ordinal))
return _fallback.GetPolicyAsync(policyName);
// Built on demand; the authorisation stack caches policies per endpoint.
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddRequirements(new PermissionRequirement(policyName[Prefix.Length..]))
.Build();
return Task.FromResult<AuthorizationPolicy?>(policy);
}
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => _fallback.GetDefaultPolicyAsync();
public Task<AuthorizationPolicy?> GetFallbackPolicyAsync() => _fallback.GetFallbackPolicyAsync();
}
public sealed class PermissionHandler(IPermissionService permissions) : AuthorizationHandler<PermissionRequirement>
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement req)
{
var tenantId = context.User.FindFirst("tenant_id")?.Value;
var userId = context.User.FindFirst("sub")?.Value;
if (tenantId is null || userId is null) return;
var granted = await permissions.GetAsync(tenantId, userId, CancellationToken.None);
if (granted.Contains(req.Permission)) context.Succeed(req);
}
}
// Authorization/PermissionService.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Hybrid;
namespace Saas.Api.Authorization;
public interface IPermissionService
{
ValueTask<IReadOnlySet<string>> GetAsync(string tenantId, string userId, CancellationToken ct);
Task InvalidateTenantAsync(string tenantId, CancellationToken ct);
}
public sealed class PermissionService(HybridCache cache, IDbContextFactory<SaasDb> dbFactory) : IPermissionService
{
private static readonly HybridCacheEntryOptions Options = new()
{
Expiration = TimeSpan.FromMinutes(10), // backstop; invalidation does the real work
LocalCacheExpiration = TimeSpan.FromSeconds(30) // bounds staleness on other instances
};
public async ValueTask<IReadOnlySet<string>> GetAsync(string tenantId, string userId, CancellationToken ct)
{
var list = await cache.GetOrCreateAsync($"perms:{tenantId}:{userId}", async token =>
{
await using var db = await dbFactory.CreateDbContextAsync(token);
return await db.UserRoles
.Where(ur => ur.TenantId == tenantId && ur.UserId == userId)
.SelectMany(ur => ur.Role.Permissions.Select(p => p.Permission))
.Distinct()
.ToArrayAsync(token);
}, Options, tags: [$"tenant:{tenantId}", $"user:{userId}"], cancellationToken: ct);
return list.ToHashSet(StringComparer.Ordinal);
}
public Task InvalidateTenantAsync(string tenantId, CancellationToken ct) =>
cache.RemoveByTagAsync($"tenant:{tenantId}", ct).AsTask();
}
// Program.cs
builder.Services.AddHybridCache();
builder.Services.AddStackExchangeRedisCache(o => o.Configuration = builder.Configuration["Redis"]); // L2
builder.Services.AddDbContextFactory<SaasDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Saas")));
builder.Services.AddSingleton<IPermissionService, PermissionService>();
builder.Services.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>();
builder.Services.AddSingleton<IAuthorizationHandler, PermissionHandler>();
builder.Services.AddAuthorization();
app.MapPost("/invoices/{id:int}/approve", (int id) => Results.NoContent())
.RequireAuthorization(PermissionPolicyProvider.Prefix + Permissions.InvoicesApprove);
IAuthorizationPolicyProvider or an IAuthorizationRequirementData attribute.invoices.approve doesn't mean any invoice in any tenant. Instead: combine permission checks with tenant filters and resource-based checks.Permission systems fail on freshness and auditability long before they fail on performance. I design the invalidation path first, keep the permission catalogue in code where it can't drift, and keep tokens about identity so that authorisation changes don't depend on token lifetimes.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Roles only | Few fixed roles you define | Lowest | Customer-defined roles |
| Permissions in token | Few stable scopes, many services reading them | Staleness, size | Hundreds of permissions, frequent changes |
| Server-side permissions + HybridCache | Multi-tenant SaaS, tenant-defined roles | Cache, invalidation, audit UI | Tiny apps |
| External engine (OpenFGA, OPA, Cedar) | Relationship sharing, many services, central policy | New infrastructure, network hop, policy language | One service with simple RBAC |
Measure it: cache hit rate, authorisation latency on hit and miss, time from role change to enforcement on every instance (test it in staging), and the count of permissions with no endpoint using them (dead permissions confuse admins).
A custom handler has two parts: a requirement, an immutable record implementing IAuthorizationRequirement, and a handler deriving from AuthorizationHandler<TRequirement> that calls context.Succeed(requirement) when the rule holds. Handlers are ordinary DI services, so they can inject a repository or TimeProvider; register them as IAuthorizationHandler (scoped if they use a DbContext).
Succeed is enough.Fail() is a veto that denies even if another handler succeeded, so use it only for a definite no (suspended account).IAuthorizationRequirementData lets an attribute carry the requirement.The trade-off: handlers run on every protected request, so keep them fast and cache what they look up.
Entra ID limits how many group ids it puts in a token: above 200 groups in a JWT (150 for SAML, 6 for implicit flow) it omits the groups claim and adds an overage indicator (_claim_names / _claim_sources pointing at Microsoft Graph, or hasgroups in some flows), so the app must call Graph (/me/getMemberObjects or /users/{id}/transitiveMemberOf) to get memberships, which needs a Graph permission, adds latency and should be cached. Better designs avoid raw groups: define app roles and assign them to groups, so the token carries a short roles list; or set the group claim to 'groups assigned to the application' only; or keep fine-grained permissions in the app and cache them. Code must handle the overage case explicitly, or users silently lose access.
Resource-based authorisation decides using the record itself: its owner, team, tenant or state (a paid invoice can't be edited). An endpoint policy can't do it alone because the authorisation middleware runs before your code loads the record.
AuthorizationHandler<TRequirement, TResource>, usually with OperationAuthorizationRequirement (Read, Update, Delete) so one handler holds every rule for a resource type: owner, team editor, viewer, admin.IAuthorizationService.AuthorizeAsync(User, document, Operations.Update), and return Forbid(), or NotFound() when even confirming the record exists would disclose information.The trade-off: it's imperative, so a developer can forget the call. Back it with tests and query filters.
How to tell it (STAR)
**S:** We had moved permissions into access tokens in our [finance SaaS], and when a tenant admin removed the payment-release permission from a user under investigation, that user still released a payment [20 minutes] later; admins with many roles were also hitting 431 errors at the gateway. **T:** I was asked to make permission changes take effect immediately without hurting performance. **A:** I revoked the user's sessions straight away, then redesigned the model: tokens carry identity only, permissions are resolved server-side from tenant roles and cached in HybridCache with tag invalidation on every role change, and a dynamic policy provider maps permission names to policies. I added a test that proves removal is enforced across instances within seconds. **R:** Permission changes now take effect in [under 2 seconds], token size dropped from [~9 KB] to [~1.2 KB], the 431s disappeared, and authorisation adds [under 0.1 ms] on a cache hit.
Last updated 23 Nov 2026.