【问题标题】:Getting Identity Resources - Identity Server 4获取身份资源 - Identity Server 4
【发布时间】:2020-01-06 10:46:05
【问题描述】:

我是 Identity Server 4 的新手,我正在努力获取用户 identities。目前,我正在通过 Identity Server 保护的 API 显示 Claims

namespace API01.Controllers
{
    [Route("identity")]
    [Authorize]
    public class IdentityController : ControllerBase
    {
        // GET identity
        [HttpGet]
        public IActionResult Get()
        {          
            return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
        }
    }
}

问题在于,当我解码 jwt 时,email 资源只是显示为值 email

"scope": [
    "email",
    "openid",
    "api1"
  ],

我一直在尝试使用User.Identities,但到目前为止我无法从我的AllowedScopes {"email", "openid", "api1"} 获得所需的信息。

基本上,我想获得在我的情况下为test@test.com 的值。我不担心返回一个JsonResult,现在只要一个字符串就足够了,如果它会很困难的话。

【问题讨论】:

  • 添加新用户时,请确认您是否将声明与用户(即 AspNetuserClaims 表)进行映射。
  • 是的,但我刚才注意到了一些事情......我正在将claims 映射到users,但我没有使用Claims = new [] { new "claim 1", new "claim 2", ... },我的是Claims = { new "claim 1", new "claim 2", … }。我不确定这是否重要。将在我刚刚阅读文档中的 Quickstart 3 时进行测试。

标签: c# .net asp.net-core identityserver4


【解决方案1】:

如果您想在您的 id 令牌中包含电子邮件声明,您可以在 IDS4 的 IdentityResource 中添加 IdentityResources.Email()

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new List<IdentityResource>
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        new IdentityResources.Email()
    };
}

还在客户端配置中将AlwaysIncludeUserClaimsInIdToken 设置为true

new Client
{
    ClientId = "mvc",
    ClientName = "MVC Client",
    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,

    ....

    ....
    AlwaysIncludeUserClaimsInIdToken = true,
    AllowedScopes =
    {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
        "api1",
        IdentityServerConstants.StandardScopes.Email,
    },
    AllowOfflineAccess = true
},

你可以从Identity Server4 code samples开始。

如果您想在 jwt 令牌中找到 scopes,id 令牌将不包括 scopes 声明,但访问令牌包括,因为 api 应该验证它。

【讨论】:

  • 感谢答案,我已经尝试了上述方法,但我仍然无法从令牌或操作方法的jsonResult 访问电子邮件的实际值。我已经开始通过快速入门,我在 2 号 GrantTypes.ResourceOwnerPassword 这可能是一个问题,因为我注意到你有 GrantTypes.HybridAndClientCredentials。所以澄清一下,我收到的是 ID 令牌还是访问令牌?正如我所读到的,后者没有携带此类信息?
  • 使用混合流或资源所有者流不是问题。如果您获得 API 访问权限,那么您将获得 id token 和 access token 。 ID 令牌声明将映射到您可以通过 User.Claims 退休的用户原则
【解决方案2】:

范围数组表示允许访问的内容。 您可能希望在令牌中看到电子邮件声明。

为此,您需要实现 IProfilrService 并将所有声明从 Subject 添加到 IssuedClaims

【讨论】:

  • 感谢您的回复,我不介意它显示在令牌中,只是更感兴趣的是在我的 API 的 Get() 方法中获取它并用它做一些事情。
  • 是的,但是是什么创造了用户的所有声明?是中间件API吗?从令牌?它是否包含您需要的声明;-)
  • 我有一个令牌服务器(web api)、一个带有中间件的 web api 和一个作为客户端的控制台应用程序。你有一个例子,因为我不太确定这里需要什么。谢谢,
  • 令牌服务器是 Identity Server 4 吗? github.com/IdentityServer/IdentityServer4/issues/1596
  • 是的,它是 Identity Server 4
猜你喜欢
  • 2021-03-06
  • 2019-08-17
  • 2017-06-26
  • 2019-04-18
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
  • 1970-01-01
相关资源
最近更新 更多