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:

  • Permissions are stored in a database table and assigned to a user (in my case, they are assigned to a role, which is assigned to a user). But this can be any structure.
  • Permissions are placed as claims on the user during authentication.
  • Permissions are based on a page name and a specific permission such as “Allow Create”.
    • The claim will be in the form of Type=”Permission”, Value = “Users – Allow View”
  • Ability to attribute the Razor / Blazor pages with something similar to the Authorize attribute such as [PagePermissions(PageName = "Users", Permission=Permission.View)]
  • Ability to use <AuthorizeView ...> ... </AuthorizeView> in the same fashion with the page name and permission.

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.

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật