IdentityServer4如何访问用户电子邮件

Joh*_*ohn 5 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%3Dbc377c5bfd784f2f87b2621bd9cfae2

然后,我们尝试使用响应提供的 access_token 作为不记名令牌来检索成员信息。这似乎有效,但这是我坚持的部分:

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

Claim cl = this.User.Claims.FirstOrDefault(x => x.Type == "sub");
Run Code Online (Sandbox Code Playgroud)

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

我尝试将电子邮件或个人资料添加到范围中,如您在上面看到的,该范围仅在我的声明列表中生成名称为“范围”和值“电子邮件”的条目。

编辑

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

{
    "sub": "xx"
}
Run Code Online (Sandbox Code Playgroud)

Dou*_*mms 6

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

 ...
 AllowedScopes = new List<string>
 {
      IdentityServerConstants.StandardScopes.OpenId,
      IdentityServerConstants.StandardScopes.Profile,
      IdentityServerConstants.StandardScopes.Email
 }
 ...
Run Code Online (Sandbox Code Playgroud)

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

 ...
 Scope = "openid profile email",
 ...
Run Code Online (Sandbox Code Playgroud)

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

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

 TokenValidationParameters = {
      NameClaimType = "email"
 }
Run Code Online (Sandbox Code Playgroud)