Policy-based authorization vs authorize with role in .Net Core
Asked Answered
S

2

22

What is the difference between using policy-based authorization and authorize with role, or there is no difference?

[Authorize(Policy = "RequiredAdminRole")]

and

[Authorize(Roles = "Admin")]
Scandian answered 19/10, 2019 at 15:2 Comment(0)
F
21

Policy-based authorization gives you more flexibility. You can use custom authorization handlers with policies to add more complex logic than just checking if your user has a specific role. For example, you have some roles mappings in your database. You can create a policy that will check if your user is authorized according to that data or that can be any custom logic. You can also create policy only with .RequireRole("Admin") which technically will do the same as an attribute [Authorize(Roles = "Admin")] Take a look at how to implement custom authorization handlers in documentation

Folium answered 19/10, 2019 at 15:22 Comment(0)
I
9

For Role-based authorization, Roles are exposed to the developer through the IsInRole method on the ClaimsPrincipal class.

In my opinion,there is no difference if you mean the Policy is configured as

services.AddAuthorization(options =>
          options.AddPolicy("RequiredAdminRole",
          policy => policy.RequireRole("Admin"));
        }

From RequireRole:

public AuthorizationPolicyBuilder RequireRole(IEnumerable<string> roles)
    {
        if (roles == null)
        {
            throw new ArgumentNullException(nameof(roles));
        }

        Requirements.Add(new RolesAuthorizationRequirement(roles));
        return this;
    }

and RolesAuthorizationRequirement

public IEnumerable<string> AllowedRoles { get; }

    /// <summary>
    /// Makes a decision if authorization is allowed based on a specific requirement.
    /// </summary>
    /// <param name="context">The authorization context.</param>
    /// <param name="requirement">The requirement to evaluate.</param>

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolesAuthorizationRequirement requirement)
    {
        if (context.User != null)
        {
            bool found = false;
            if (requirement.AllowedRoles == null || !requirement.AllowedRoles.Any())
            {
                // Review: What do we want to do here?  No roles requested is auto success?
            }
            else
            {
                found = requirement.AllowedRoles.Any(r => context.User.IsInRole(r));
            }
            if (found)
            {
                context.Succeed(requirement);
            }
        }
        return Task.CompletedTask;
    }

You can see that the policy is just to check the result of context.User.IsInRole("Admin").

Isomerous answered 21/10, 2019 at 9:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.