IdentityServer4 如何访问用户邮箱

IdentityServer4 How to access user email

我继承了一个现有项目,但我是 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 下面的代码中 returns 代表登录用户的 GUID 而不是电子邮件。

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

我需要更改什么才能让 sub 提供登录用户的电子邮件?

我已经尝试添加电子邮件或个人资料,如您在上面看到的那样,只是在我的声明列表中生成名称为 "scope" 和值为 "email".[=13= 的条目的范围]

编辑

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

{
    "sub": "xx"
}

在 IdentityServer 端,在您的配置 class 中,当您定义允许的范围时,请确保它包含这样的电子邮件:

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

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

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

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

现在,如果您想更进一步,在您的客户端应用程序中使用电子邮件作为 "UserID"(而不是 Guid sub),那么您可以将以下内容添加到 app.UseOpenIdConnectAuthentication 客户端方法:

 TokenValidationParameters = {
      NameClaimType = "email"
 }