【问题标题】:How to set required claims for IdentityServer4 API Resources?如何为 IdentityServer4 API 资源设置所需的声明?
【发布时间】:2018-05-18 10:33:22
【问题描述】:

我正在使用IdentityServer4 1.0.0 以及使用IdentityServer4.EntityFramework 1.0.0 包存储在SQL Server 中的客户端和API 资源的配置信息。

有没有办法在使用IdentityServer4.EntityFramework 1.0.0 包管理的表中设置访问我的 API 必须存在的声明列表?

【问题讨论】:

标签: entity-framework visual-studio-2015 identityserver4 asp.net-core-1.1


【解决方案1】:

我遇到了同样的问题,奇怪的是我添加的声明存在于访问令牌中,但安全 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

【讨论】:

  • 如何确保索赔不存在?
【解决方案2】:

在你的 API 启动中

services.AddAuthorization(options =>
        {
            options.AddPolicy("SecurePolicyName", policyUser =>
            {
                policyUser.RequireClaim("role", "admin");
            });
        });

然后在您的控制器中将授权属性与您的策略一起使用。

[Authorize(Policy = "SecurePolicyName")]

【讨论】:

  • 感谢您的回复。我正在寻找如何做同样的事情,但利用现有的 IdentityServer4 对象模型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 2020-05-26
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多