I have been trying to add Authorization and permissions to my project.
I have managed to generate the database tables as such:
AspNetRoleClaims
AspNetUserClaims
AspNetRoles
AspNetUsers
ApsNetUserRoles
These tables got generated using PMC, I committed these tables after the blazer web assembly template was used.
In the PMC I entered:
update-database
Which generated those tables described above.
So when i use:
<AuthorizeView Roles="Admin">
<div class="wrapper">
<ContentLayout Title="@_greeting">
<Card>
<CardContent>
Hi @context.User.Identity!.Name
</CardContent>
</Card>
</ContentLayout>
</div>
<div>
</div>
</AuthorizeView>
Works great and only Admin can view the content.
Now what my problem is how do I add Policy-Based Authorisation, I have searched to find a solution but I tried examples but no luck.
What I'm trying to do is find a way of adding Policy-Based Authorization without any logic so it's built-in with this table, is this possible?
Or can someone please share how I can achieve Policy-Based Authorization?
These are the data in the tables:





And what is was trying for Policies:
<AuthorizeView Policy="CanBuy">
<div>hello</div>
</AuthorizeView>
But i get error:

The accepted answer is NOT good practice.
Here's a better solution that follows the recommended approach for ASP.NET Core and Blazor applications:
Option 1: validating within bootstrapping code; suggest using this with simple validation only.
services.AddAuthorizationCore(options => {
options.AddPolicy("CanBuyPolicy", policy =>
policy.RequireClaim("permission.canbuy", "CanBuy"));
});
OR
services.AddAuthorizationCore(options => {
options.AddPolicy("CanBuyPolicy", policy =>
policy.RequireRole("admin", "user"));
});
Option 2: setup policy handlers, and bootstrap them;
Create a Policy class that does the Authorization Handling of your requirement:
public class UserCanBuyPolicy : IAuthorizationHandler
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context)
{
//claim-based validation
if (context.User.HasClaim("permission.canbuy", "CanBuy"))
context.Succeed(requirement);
//role-based validation
if (context.User.IsInRole("admin") || context.User.IsInRole("user"))
context.Succeed(requirement);
return Task.CompletedTask;
}
}
Then you need to register your policy in your application bootstrapping:
services.AddScoped<IAuthorizationHandler, UserCanBuyPolicy>();
services.AddAuthorizationCore(options => {
options.AddPolicy("CanBuyPolicy", policy => policy.Requirements.Add(UserCanBuyRequirement));
});
The latter option offers more flexibility and can be scaled to include more custom logic as needed.
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With