📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Design permission-based authorisation for a large multi-tenant SaaS product where customers define their own roles. Would you put permissions in the access token or look them up per request? How do you cache them, keep them fresh when an admin changes a role, and express them as ASP.NET Core policies without registering hundreds of them?

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).

Senior Architecture Advanced architecture authorization caching multi-tenant permissions security

🎯 Key points

  • Endpoints check fine-grained permissions (invoices.approve); roles are tenant-defined bundles of permissions
  • Permissions in the token: no lookup, but token bloat (header limits ~8-16 KB at proxies) and staleness until expiry
  • Look up per request: fresh and small tokens, but needs a cache (HybridCache L1+L2) and invalidation
  • Typical design: identity token carries sub + tenant; permissions resolved server-side, cached by (tenant, user, version)
  • Invalidate with tags or a permission version bumped on role change, plus a short TTL backstop; tell users when their access changed
  • Dynamic IAuthorizationPolicyProvider builds 'perm:invoices.approve' policies on demand; one PermissionHandler
  • Permission catalogue in code, tenant role mappings in data; audit every role change and monitor denials and cache hit rate
  • Relationship-based needs (sharing, hierarchies) push you to ReBAC (OpenFGA/Zanzibar) or policy engines (OPA)

⏱ 30-second answer

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.

  • Permissions in the token avoid a lookup but bloat the token and stay stale until it expires.
  • Server-side lookup keeps tokens small and changes immediate, at the cost of a cache and invalidation.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 in HybridCache, 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 IAuthorizationPolicyProvider recognises names like perm:invoices.approve and builds a policy with a PermissionRequirement on demand, and one PermissionHandler checks 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."


Token vs lookup

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

Data model

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

Production example

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].

🔍 What the interviewer is checking

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

  • Separates permissions (code) from roles (data)
  • Weighs token size and staleness against lookup cost with numbers
  • Designs invalidation, not just a TTL
  • Uses a dynamic policy provider and one generic handler
  • Mentions auditing and when ReBAC or a policy engine is warranted

Red flags

  • Puts everything in the JWT without considering size or revocation
  • Hard-codes role checks in endpoints
  • Forgets ownership and tenant boundaries

📚 Learn in depth

1. The request path

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

2. Why not just put permissions in the token

  • Size: each permission string is ~20-30 bytes; 150 of them base64url-encoded approaches 5 KB, plus signature and other claims. Many reverse proxies and WAFs default to 8 KB header limits; cookies cap at ~4 KB per cookie (ASP.NET Core chunks them).
  • Staleness: a JWT is valid until exp. Revoking one permission means waiting or building revocation.
  • Coupling: every service that reads the token learns your permission model; changes need token reissue.

Permissions in the token remain a good choice for a handful of stable, coarse permissions (OAuth scopes are exactly that).

3. Cache design

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.

4. Dynamic policies

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.

5. Beyond RBAC

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.

6. Auditing and compliance

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.

Try it yourself

  1. Implement the provider and handler below and test that perm:x and an unknown policy both resolve correctly.
  2. Measure a 150-permission JWT's size and send it through a proxy with an 8 KB header limit.
  3. Benchmark the handler on cache hit vs miss with BenchmarkDotNet.
  4. Change a role in one instance and measure how long another instance takes to see it, with and without tag invalidation.
  5. Model a folder-sharing rule in OpenFGA and compare it with the RBAC version.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Endpoints checking role names in a product with customer-defined roles. Why it is wrong: every new role needs a deployment. Instead: endpoints check permissions; roles map to permissions as data.
  • Mistake: Putting every permission into the JWT. Why it is wrong: tokens exceed proxy header limits and permissions stay valid until expiry. Instead: identity in the token, permissions resolved server-side, or only a few coarse scopes in the token.
  • Mistake: Caching permissions with only a long TTL. Why it is wrong: a removed permission keeps working for the TTL. Instead: tag or version-based invalidation on change, with a short TTL as a backstop and bounded L1 expiry.
  • Mistake: Registering one named policy per permission at start-up. Why it is wrong: hundreds of lines that drift from the catalogue. Instead: a dynamic IAuthorizationPolicyProvider or an IAuthorizationRequirementData attribute.
  • Mistake: Letting tenants create arbitrary permission strings. Why it is wrong: permissions with no code behind them confuse admins and auditors. Instead: a code-owned catalogue; tenants compose roles from it.
  • Mistake: Forgetting that permissions don't cover ownership. Why it is wrong: invoices.approve doesn't mean any invoice in any tenant. Instead: combine permission checks with tenant filters and resource-based checks.
  • Mistake: No audit trail for role changes. Why it is wrong: you can't answer "who gave this user payroll.export?" during an incident. Instead: append-only audit records for every role and assignment change, visible to tenant admins.

🏛 Senior insight: trade-offs

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).

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes a PermissionHandler Why: Checks they can implement the generic permission handler correctly
    How to answer

    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).

    • Several handlers for one requirement combine as OR: any Succeed is enough.
    • Fail() is a veto that denies even if another handler succeeded, so use it only for a definite no (suspended account).
    • Since .NET 8, 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.

  2. When: Candidate mentions token size or syncing roles from Entra ID groups Why: Checks they know the token-size limits that push permissions server-side (Entra groups overage)
    How to answer

    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.

  3. When: Candidate implies a permission grants access to every record Why: Checks they know permissions alone don't cover ownership of specific records
    How to answer

    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.

    • Write an AuthorizationHandler<TRequirement, TResource>, usually with OperationAuthorizationRequirement (Read, Update, Delete) so one handler holds every rule for a resource type: owner, team editor, viewer, admin.
    • In the endpoint, load the record, call IAuthorizationService.AuthorizeAsync(User, document, Operations.Update), and return Forbid(), or NotFound() when even confirming the record exists would disclose information.
    • For lists, filter in the database query; never load everything and check one by one.

    The trade-off: it's imperative, so a developer can forget the call. Back it with tests and query filters.

🛠 Real-world problems: how you handle them

Removed permissions kept working for an hour after moving permissions into the JWT
Situation
A [B2B finance SaaS] with [~2,000] tenants moved permissions into access tokens to save a database lookup. Tokens lived [60 minutes]. A tenant admin removed `payments.release` from a user under investigation for [suspected fraud].
Signals
The tenant reported the user released [a payment] [20 minutes] after the permission was removed; the API gateway started returning 431 Request Header Fields Too Large for [admin users with many roles]; token sizes in logs reached [~9 KB].
Investigation
Decoded tokens on jwt.ms and confirmed the permission was still present until `exp`; measured token sizes by role count; reviewed gateway limits; checked the audit log to confirm the timeline of the role change versus the payment release for the tenant.
Resolution
Immediate: revoked the user's refresh tokens and blocked the account, which ended the session within minutes. Then redesigned: tokens carry only `sub`, `tenant_id` and scopes; permissions resolved server-side through HybridCache with tag invalidation on role changes; a dynamic policy provider replaced the static policies.
Prevention
An integration test that removes a permission and asserts denial within [5 seconds] across two instances; an alert on token size above [4 KB]; an ADR recording why permissions aren't in tokens; audit log of role changes exposed to tenant admins.

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.

↩ Usually asked after

More in Authorization

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me