首页 > 解决方案 > 获取身份资源 - Identity Server 4

问题描述

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

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 });
        }
    }
}

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

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

我一直在尝试,User.Identities但到目前为止我无法从我的AllowedScopes {"email", "openid", "api1"}.

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

标签: c#.netasp.net-coreidentityserver4

解决方案


如果你想在你的 id token 中包含 email 声明,你可以添加 IDS4 的IdentityResources.Email()in IdentityResource

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

在客户端配置中也设置AlwaysIncludeUserClaimsInIdTokentrue

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 代码示例开始。

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


推荐阅读