基于策略的授权与在.Net Core中的角色进行授权 [英] Policy-based authorization vs authorize with role in .Net Core

查看:485
本文介绍了基于策略的授权与在.Net Core中的角色进行授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用基于策略的授权与使用角色授权有什么区别,或者没有区别?

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

[Authorize(Policy ="RequiredAdminRole")]

[Authorize(Policy = "RequiredAdminRole")]

[Authorize(Roles ="Admin")]

[Authorize(Roles = "Admin")]

推荐答案

对于

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"));
        }

来自 RequireRole :

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

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

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;
    }

您可以看到该策略只是检查context.User.IsInRole("Admin")的结果.

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

这篇关于基于策略的授权与在.Net Core中的角色进行授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆