【问题标题】:Policy-based authorization vs authorize with role in .Net Core基于策略的授权与 .Net Core 中的角色授权
【发布时间】:2020-02-16 06:49:15
【问题描述】:

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

[Authorize(Policy = "RequiredAdminRole")]

[Authorize(Roles = "Admin")]

【问题讨论】:

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


    【解决方案1】:

    基于策略的授权为您提供了更大的灵活性。您可以使用带有策略的自定义授权处理程序来添加更复杂的逻辑,而不仅仅是检查您的用户是否具有特定角色。例如,您的数据库中有一些角色映射。您可以创建一个策略来检查您的用户是否根据该数据获得授权,或者可以是任何自定义逻辑。您还可以仅使用 .RequireRole("Admin") 创建策略,这在技术上与属性 [Authorize(Roles = "Admin")] 的作用相同 看看documentation中如何实现自定义授权处理程序

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 2020-02-10
        相关资源
        最近更新 更多