gpt4 book ai didi

c# - 多个范围的 ASP.NET Core ClaimsAuthorizationRequirement 未按预期工作?

转载 作者:行者123 更新时间:2023-11-30 22:54:40 27 4
gpt4 key购买 nike

我遇到了一些事情,如果这是有意为之的行为或主要的安全风险,想征求您的意见。

我打算做的是授权两个具有不同策略的 API Controller 操作。一个策略需要一个范围,另一个策略需要两个范围。

因此我定义了范围

  • 范围:1
  • 范围:2

我打算授权的 Controller 以及授权方式如下:

  [ApiController]
[Route("api/v1/[controller]")]
//intentionally no authorize here
public class TestContoller : ControllerBase
{

[HttpGet("single")]
[Authorize(AuthenticationSchemes = "Bearer", Policy = nameof(SingleScopePolicy))]
public IActionResult GetSingle() { return Ok("success"); }

[HttpGet("double")]
[Authorize(AuthenticationSchemes = "Bearer", Policy = nameof(DoubleScopePolicy))]
public IActionResult GetDouble() { return Ok("success"); }

}

预期的行为(正如我现在理解的那样)是当 SingleScopePolicy 检测到它没有范围时返回禁止:1 并且 DoubleScopePolicy 检测到它没有范围:1 AND 范围:2 . AND 是相关部分!

在 Startup.cs 中,我配置了授权并添加了范围(故意没有用于测试的默认策略)

public void ConfigureService(IServiceCollection service) 
{
// ...

services.AddAuthorization
(
options =>
{
options.AddPolicy(nameof(SingleScopePolicy), new SingleScopePolicy());
options.AddPolicy(nameof(DoubleScopePolicy), new DoubleScopePolicy());
}
);

// ...
}

我通过代码定义了我的两个策略:

  public class SingleScopePolicy : AuthorizationPolicy
{
public SingleScopePolicy() : base
(
new IAuthorizationRequirement[]
{
new ClaimsAuthorizationRequirement("scope", new string[] { "scope:1 })
},
new string[] { "Bearer" }
) { }
}

public class DoubleScopePolicy : AuthorizationPolicy
{
public DoubleScopePolicy() : base
(
new IAuthorizationRequirement[]
{

// does not work (never returns forbid)
//new ClaimsAuthorizationRequirement("scope", new string[] { "scope:1", "scope:2" })

// works
new ClaimsAuthorizationRequirement("scope", new string[] { "scope:1" }),
new ClaimsAuthorizationRequirement("scope", new string[] { "scope:2" }),
},
new string[] { "Bearer" }
) { }
}

我现在的问题是,DoubleScopePolicy 中的声明授权要求是否有效,或者是否有意使其无效。

使用下面的行实际上永远不会返回禁止并且总是允许访问。这种让我惊叹的原因是它为您提供了一个字符串[],我将其理解为“嘿,给我两个,我会检查是否都有”。如果我在两行中单独定义它,它会按预期工作(由我)。

new ClaimsAuthorizationRequirement("scope", new string[] { "scope:1", "scope:2" }) 

最佳答案

source ClaimsAuthorizationRequirement 显示 AllowedValues 属性被视为操作:

found = context.User.Claims.Any(
c => string.Equals(c.Type, requirement.ClaimType, StringComparison.OrdinalIgnoreCase)
&& requirement.AllowedValues.Contains(c.Value, StringComparer.Ordinal));

// ...

if (found)
{
context.Succeed(requirement);
}

正如您已经描述的,您可以添加多个 ClaimsAuthorizationRequirement,以便将检查视为 and 操作。

关于c# - 多个范围的 ASP.NET Core ClaimsAuthorizationRequirement 未按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56055649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com