我遇到了同样的问题,奇怪的是我添加的声明存在于访问令牌中,但安全 API 拒绝了它。您需要做的是将声明添加到您的客户端,假设我们有这个 API:
[Produces("application/json")]
[Authorize("Founder")]
[Route("api/ApiResourceWithPolicy")]
public class ApiResourceWithPolicyController : Controller
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(new { ResourceType = "With Policy", ResourceName = "Api2" });
}
}
在您的 startup.cs 中设置此策略:
ervices.AddAuthorization(options => options.AddPolicy("Founder", policy => policy.RequireClaim("Employee", "Mosalla")));
现在向您的客户添加必要的声明,这里的重点是将ClientClaimsPrefix 设置为空字符串:
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client1",
// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.ClientCredentials,
// secret for authentication
ClientSecrets =
{
new Secret("123654".Sha256())
},
// scopes that client has access to
AllowedScopes = {"Api1"},
Claims = new[]
{
new Claim("Employee", "Mosalla"),
new Claim("website", "http://hamidmosalla.com")
},
ClientClaimsPrefix = ""
}
}
这是因为 IdentityServer4 为声明添加了前缀,使资源服务器无法识别它们:
如果您需要更多解释,请访问my post about policy-based authorization with IdentityServer4。