asp.net-coreblazorblazor-webassembly

ASP.NET Core / Blazor: How to implement Permissions based (non-Policy) Authorization


Using Blazor WASM, I want to implement a dynamic permissions based authorization system that isn't definable at build time. The current "Policy based" authorization built-in system requires that policies are defined at build time and this doesn't work for me as all of my permissions are assigned via my own permissions system that is database based.

Requirements:

The ASP.NET Core built in authorization works on policies, which need to be defined at build time such as so:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AtLeast21", policy =>
        policy.Requirements.Add(new MinimumAgeRequirement(21)));
});

Roles work the same as it uses the policy system under the covers.

Neither of these work for my scenario as none of my information is known at build time.


Solution

  • (Note this should work for both ASP.NET Core and Blazor)

    Searching all over the internet, I didn't find any good examples for this. I downloaded the ASP.NET Core code and tried to decipher the authorization code and stumbled upon a sample here that I was able to extrapolate into a solution for myself. This sample utilizes Policies under the covers via a naming convention and en/decodes that at runtime.

    My implementation starts with a custom AuthorizeAttribute:

    public enum PagePermission
    {
        None,
        View,
        Create,
        Edit,
        Delete,
    }
    
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class PagePermissionAttribute : AuthorizeAttribute
    {
        public const string PolicyPrefix = "PagePermissionsPolicy";
        public const string PolicySeparator = "%&#"; //Random characters that should never show up in an actual page or permission name
    
        public PagePermissionAttribute(string pageName, PagePermission permission)
        {
            Policy = $"{PolicyPrefix}{PolicySeparator}{pageName}{PolicySeparator}{(int)permission}";
        }
    }
    

    And its related IAuthorizationRequirement implementation:

    public class PagePermissionRequirement(string pageName, PagePermission permission) : IAuthorizationRequirement
    {
        public string PageName { get; private set; } = pageName;
        public PagePermission Permission { get; private set; } = permission;
    }
    

    The IAuthorizationRequirement requires an AuthorizationHandler:

    public class PagePermissionAuthorizationHandler(ILogger<PagePermissionAuthorizationHandler> logger) : AuthorizationHandler<PagePermissionRequirement>
    {
        // Check whether a given PagePermissionRequirement is satisfied or not for a particular context
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PagePermissionRequirement requirement)
        {
            logger.LogInformation("Evaluating authorization requirement for Page: '{pageName}', Permission: '{permission}'.", requirement.PageName, requirement.Permission);
    
            bool isAuthorized = false;
            var pagePermissions = context.User.FindAll(c => c.Type == "Permission" && c.Value.StartsWith(requirement.PageName));
    
            if (pagePermissions != null)
            {
                bool allowCreate = pagePermissions.Any(x => x.Value.Contains("Allow Create"));
                bool allowDelete = pagePermissions.Any(x => x.Value.Contains("Allow Delete"));
                bool allowEdit = pagePermissions.Any(x => x.Value.Contains("Allow Edit"));
                bool allowView = pagePermissions.Any(x => x.Value.Contains("Allow View"));
    
                isAuthorized = requirement.Permission switch
                {
                    PagePermission.None => false,
                    PagePermission.View => allowCreate | allowDelete | allowEdit | allowView,
                    PagePermission.Create => allowCreate,
                    PagePermission.Edit => allowEdit,
                    PagePermission.Delete => allowDelete,
                    _ => throw new NotImplementedException(),
                };
            }
    
            if (isAuthorized)
            {
                logger.LogInformation("Page permissions authorization requirement satisfied");
                context.Succeed(requirement);
            }
            else
            {
                logger.LogInformation("Page permissions do not exist for requested Page: '{pageName}', Permission: '{permission}'.",
                    requirement.PageName,
                    requirement.Permission);
            }
    
            return Task.CompletedTask;
        }
    }
    

    And then finally a custom IAuthorizationPolicyProvider:

    // ASP.NET Core only uses one authorization policy provider, so if the custom implementation doesn't handle all policies (including default policies, etc.)
    // it should fall back to an alternate provider.
    public class PagePermissionPolicyProvider(IOptions<AuthorizationOptions> options) : IAuthorizationPolicyProvider
    {
        public DefaultAuthorizationPolicyProvider FallbackPolicyProvider { get; } = new DefaultAuthorizationPolicyProvider(options);
    
        public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => FallbackPolicyProvider.GetDefaultPolicyAsync();
    
        public Task<AuthorizationPolicy?> GetFallbackPolicyAsync() => FallbackPolicyProvider.GetFallbackPolicyAsync();
    
        // Policies are looked up by string name, so expect 'parameters' to be embedded in the policy names.
        public async Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
        {
            if (policyName.StartsWith(PagePermissionAttribute.PolicyPrefix, StringComparison.OrdinalIgnoreCase))
            {
                var parts = policyName.Split(PagePermissionAttribute.PolicySeparator);
    
                if (parts.Length >= 3 && int.TryParse(parts[2], out int permission))
                {
                    var policy = new AuthorizationPolicyBuilder();
                    policy.AddRequirements(new PagePermissionRequirement(parts[1], (PagePermission)permission));
                    return policy.Build();
                }
            }
    
            // If the policy name doesn't match the format expected by this policy provider, try the fallback provider.
            // If no fallback provider is used, this would return Task.FromResult<AuthorizationPolicy>(null) instead.
            return await FallbackPolicyProvider.GetPolicyAsync(policyName);
        }
    }
    

    which is hooked up in your site's initialization code:

    // Replace the default authorization policy provider with our own custom provider which can return authorization policies for given
    // policy names (instead of using the default policy provider)
    builder.Services.AddSingleton<IAuthorizationPolicyProvider, PagePermissionPolicyProvider>();
    builder.Services.AddSingleton<IAuthorizationHandler, PagePermissionAuthorizationHandler>();
    

    (Blazor only) And then finally a custom implementation of AuthorizeView (thanks to this post for helping me on that one):

    public class AuthorizePagePermissionView : AuthorizeView
    {
        [Parameter]
        public string PageName { get; set; } = string.Empty;
    
        [Parameter]
        public PagePermission Permission { get; set; }
    
        protected override IAuthorizeData[] GetAuthorizeData()
        {
            return [new PagePermissionAttribute(PageName, Permission)];
        }
    }
    

    which can be used like this:

    <AuthorizePagePermissionView PageName="@PageName" Permission="@Authorization.PagePermission.Create">
        // Components you want restricted
    </AuthorizePagePermissionView>
    

    I hope this helps anyone else wanting a similar implementation. I took me way to long to piece it all together.