在使用Authorize属性和我在Startup.cs中定义的策略时,我遇到了问题。我编辑了我的控制器以手动检查声明。我可以看到包括正确范围的作用域声明,但是当我手动检查该声明/范围时,它返回false。我正在使用Azure AD B2C作为身份服务器,并成功获得验证令牌。
这是来自我的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
};
});
以下是我的控制器代码,我在其中手动检查声明:
// 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。
这是我的claim:
![enter image description here](https://istack.dev59.com/5ouGU.webp)
value.Split(' ').Contains('vendor.read')
? - juunasvar hasClaim8 = User.HasClaim(c => c.Type.Contains("scope") && c.Value.Contains("vendor.read"));
- stumpykilo