How would you design an authorization system supporting dynamically-configurable, admin-managed permissions rather than hardcoded policies in code?
Short answer
Instead of hardcoding every policy's logic in Program.cs, store permission definitions and role-to-permission mappings in a database, then implement a custom IAuthorizationHandler that checks a generic "HasPermission" requirement against the database-driven mapping (often cached…
Advertisement
AModel answer
Instead of hardcoding every policy's logic in Program.cs, store permission definitions and role-to-permission mappings in a database, then implement a custom IAuthorizationHandler that checks a generic "HasPermission" requirement against the database-driven mapping (often cached for performance) -- letting administrators add, modify, or remove permissions and role assignments through an admin UI without requiring a code deployment for every permission change.
public class PermissionRequirement : IAuthorizationRequirement { public string Permission { get; } public PermissionRequirement(string p) => Permission = p; }
public class PermissionHandler : AuthorizationHandler<PermissionRequirement> {
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) {
var userId = context.User.FindFirst("sub")?.Value;
if (await _permissionService.UserHasPermissionAsync(userId, requirement.Permission))
context.Succeed(requirement);
}
}Real-world example
An enterprise SaaS platform lets customer administrators define custom roles with granular permission sets through a self-service admin UI, with the ASP.NET Core authorization system checking against this database-driven permission model rather than a fixed set of code-defined policies.
Likely follow-ups
- How do you efficiently cache permission lookups to avoid a database call on every authorization check?
- How does this dynamic model interact with the declarative [Authorize(Policy=...)] attribute syntax?
Related topics