Reputation: 519
I am trying to implement Policy-based authorization in blazor server side. So I created a folder named Policy
inside of Blazor project. Within that folder contains a file named Policies.cs
. After implementing the contents of that file, I went to my Startup.cs
file and added services.AddAuthorization()
for the shared policies. After doing so, inside of my Index.razor
file I made it where certain conditions need to be met in order to have specific views based on the user that has a specific role. If I login as a regular user, BasicUser
then it will display what it should. However, when I login as an admin SuperAdmin
it will display both IsUserPolicy & IsAdmin policy view. I do not understand why it is displaying both instead of one.
Index.razor
:
@page "/"
@inject AuthenticationStateProvider GetAuthenticationStateAsync
<AuthorizeView Policy="@Policy.Policies.IsUser">
<p>You can only see this if you satisfy the IsUser policy.</p>
</AuthorizeView>
<AuthorizeView Policy="@Policy.Policies.IsAdmin">
<p>You can only see this if you satisfy the IsAdmin policy.</p>
</AuthorizeView>
Startup.cs
inside of ConfigureServices method
.....
services.AddAuthorization(options =>
{
options.AddPolicy(Policy.Policies.IsAdmin, Policy.Policies.IsAdminPolicy());
options.AddPolicy(Policy.Policies.IsUser, Policy.Policies.IsUserPolicy());
});
Policies.cs
:
public class Policies
{
public const string IsAdmin = "IsAdmin";
public const string IsUser = "IsUser";
public static AuthorizationPolicy IsAdminPolicy()
{
return new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
.RequireRole("Admin")
.Build();
}
public static AuthorizationPolicy IsUserPolicy()
{
return new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
.RequireRole("Basic")
.Build();
}
}
Upvotes: 0
Views: 1363
Reputation: 14613
I use something like this...
services.AddAuthorizationCore(options => options.ConfigurePolicies());
public static AuthorizationOptions ConfigurePolicies(this AuthorizationOptions options)
{
options.AddPolicy(Policies.IsAdmin, policy => policy.RequireRole("SuperAdmin"));
}
Note the policies are defined in the shared library so they can be used in both the client and server
Upvotes: 1