.net - 基于策略的授权与在.Net Core中的角色进行授权

标签 .net asp.net-core asp.net-roles

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

[Authorize(Policy =“RequiredAdminRole”)]



[Authorize(Roles =“Admin”)]

最佳答案

对于Role-based authorization,角色通过ClaimsPrincipal类上的IsInRole方法向开发人员公开。

我认为,如果您将策略配置为

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")的结果。

关于.net - 基于策略的授权与在.Net Core中的角色进行授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58464970/

相关文章:

.net - WCF 代理客户端单例模式性能

c# - 如何扫描网络上存在的无线设备

asp.net-core - 如何在 AspNet.Core 2.1 中通过依赖注入(inject)添加 UserManager?

ASP.NET MVC3 角色和权限管理 -> 使用运行时权限分配

c# - EntityFramework 中的 MySql ORDER BY FIELD()

c# - 启用 asp.net core 请求验证

.net - 根据用户请求访问的组织(每个请求)修改 .NET Core 角色

c# - 我应该如何将用户与域对象相关联?

c# - 如何在 asp.net 成员资格中设置嵌套角色

c# - 调用从 C# 获取指针的 C++ 函数