IdentityServer4如何访问用户电子邮件

时间:2017-10-05 06:43:02

标签: asp.net-core identityserver4

我继承了一个现有的项目,我是新手使用IdentityServer4所以请耐心等待。

我收到一个带有GET请求的令牌,如下所示:

http://my-identity-server/account/login?returnUrl=%2Fconnect%2Fauthorize%2Flogin%3Fclient_id%3Dmy.client%26redirect_uri%3Dhttp%253A%252F%252Flocalhost:8100/index.html%26response_type%3Dcode%2520id_token%2520token%26scope%3Dopenid%2520profile%2520MyAPI%26state%3D4bc18eac6a354ab3a6997e1b414e7f80%26nonce%3Dbc377c5bfd784f2f87b2621bd9cfeae2

然后我们尝试使用响应提供的access_token检索成员信息,并将其用作承载令牌。这似乎有效,但这里是我坚持的部分:

在API中,以下代码返回表示登录用户而不是电子邮件的GUID。

Claim cl = this.User.Claims.FirstOrDefault(x => x.Type == "sub");

我需要更改以允许sub提供已登录用户的电子邮件?

我已尝试添加电子邮件或个人资料,如上所示,只是在我的声明列表中输入名称为“scope”且值为“email”的条目。

修改

似乎我需要以某种方式生成令牌时更新范围。我在网上看到的所有例子都在内存设置中使用,我从数据库中获取设置。当我在te API上调用userinfo端点时,我也只能访问“sub”,例如

{
    "sub": "xx"
}

1 个答案:

答案 0 :(得分:1)

在IdentityServer端,在Config类中,在定义允许的范围时,请确保它包含以下电子邮件:

 ...
 AllowedScopes = new List<string>
 {
      IdentityServerConstants.StandardScopes.OpenId,
      IdentityServerConstants.StandardScopes.Profile,
      IdentityServerConstants.StandardScopes.Email
 }
 ...

然后在您的客户端,在启动类上,您也希望将电子邮件包含在范围内(在您的app.UseOpenIdConnectAuthentication方法中)。

 ...
 Scope = "openid profile email",
 ...

此时,当您在User.Identity.Claims中在客户端单步执行代码时,应该可以访问该电子邮件。

现在,如果您想更进一步,请将电子邮件用作&#34; UserID&#34;在客户端应用程序(而不是Guid子)中,您可以将以下内容添加到客户端上的app.UseOpenIdConnectAuthentication方法中:

 TokenValidationParameters = {
      NameClaimType = "email"
 }