gpt4 book ai didi

c# - User.HasClaim 未成功读取 .NET Core 2.0 Web Api 中的声明属性

转载 作者:行者123 更新时间:2023-12-03 23:16:31 29 4
gpt4 key购买 nike

将 Authorize 属性与我在 Startup.cs 中定义的策略一起使用时遇到问题。我编辑了我的 Controller 以手动检查声明。我可以看到包含具有正确范围的范围声明的声明,但是当我手动检查该声明/范围时,它返回为 false。我使用 Azure AD B2C 作为我的身份服务器并成功获得了一个经过验证的 token 。

这是我的 Startup.cs 中的代码:

    services.AddAuthorization(options =>
{
var policyRead = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.RequireClaim("http://schemas.microsoft.com/identity/claims/scope", "vendor.read")
.Build();
options.AddPolicy("VendorRead", policyRead);

var policyWrite = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.RequireClaim("http://schemas.microsoft.com/identity/claims/scope", "vendor.write")
.Build();
options.AddPolicy("VendorWrite", policyWrite);
});

services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions =>
{
jwtOptions.Authority = $"{Configuration["AzureAdB2C:Instance"]}/{Configuration["AzureAdB2C:TenantId"]}/{Configuration["AzureAdB2C:SignUpSignInPolicyId"]}/v2.0/";
jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
jwtOptions.RequireHttpsMetadata = true;
jwtOptions.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = $"{Configuration["AzureAdB2C:Instance"]}/{Configuration["AzureAdB2C:TenantId"]}/v2.0/",
ValidAudience = Configuration["AzureAdB2C:ClientId"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AzureAdB2C:ClientSecret"]))
};
jwtOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = AuthenticationFailed,
OnTokenValidated = TokenValidated
};
});

这是我手动检查声明的 Controller 代码:
// GET: api/Vendor/5
[HttpGet("{id}")]
public async Task<IActionResult> Get(VendorRequest request)
{
var hasClaim1 = User.HasClaim(c => c.Type == "vendor.read");
var hasClaim2 = User.HasClaim(c => c.Type == "scope");
var hasClaim3 = User.HasClaim(c => c.Type == "scp");
var hasClaim4 = User.HasClaim(c => c.Type == "http://schemas.microsoft.com/identity/claims/scope");
var hasClaim5 = User.HasClaim("http://schemas.microsoft.com/identity/claims/scope", "vendor.read");
var hasClaim7= User.HasClaim("http://schemas.microsoft.com/identity/claims/scope", "vendor.write");
var allowed = await _authorization.AuthorizeAsync(User, "VendorRead");
if (!allowed.Succeeded)
{
return StatusCode(StatusCodes.Status403Forbidden);
}

唯一返回为 true 的 hasClaim 是 hasClaim4。

以下是我的主张:
enter image description here

关于我做错了什么的任何想法?我只是想让 vendor.read 范围现在可以工作。

最佳答案

范围声明是一个以空格分隔的列表,因此 RequireClaim() helper 在这种情况下不起作用,但更通用的 RequireAssertion() 将要。
范围声明示例

"scp": "demo.read demo.write user_impersonation Test-Value"
sample RequireAssertion()
services.AddAuthorization(options =>
{
options.AddPolicy("ScopeCheck", policyBuilder =>
policyBuilder.RequireAssertion(async handler =>
{
var scopeClaim = handler.User.FindFirst("http://schemas.microsoft.com/identity/claims/scope");
var scopes = scopeClaim?.Value.Split(' ');
var hasScope = scopes?.Where(scope => scope == "demo.write").Any() ?? false;
return hasScope;
}));
});

sample Controller
[Authorize("ScopeCheck")]
public class SecureController : Controller
{
[HttpGet]
public IActionResult Test()
{
return Ok(new { Message = "You are allowed" });
}
}
Full Sample Project - Sample token

Access Token Scope (RFC 6749 section-3.3)


The value of the scope parameter is expressed as a list of space-delimited, case-sensitive strings. The strings are defined by theauthorization server. If the value contains multiple space-delimitedstrings, their order does not matter, and each string adds anadditional access range to the requested scope

关于c# - User.HasClaim 未成功读取 .NET Core 2.0 Web Api 中的声明属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50007749/

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