如何使用 identityserver4 从外部提供者处获取个人资料图片?

How do I get profile pictures from external providers using identityserver4?

我在 Net Core 中使用 identityserver4。我可以使用 Google、Facebook、Twitter、LinkedIn 和 Microsoft 进行身份验证,但现在我想通过外部提供商获取用户的个人资料图片。我正在使用 GrantTypes.Implicit 的客户端,并尝试按如下方式添加新的 IdentityResource:

new IdentityResource {
    Name = "picture",
    UserClaims = new List<string> {"picture" }
}

然后我将 "picture" 添加为我的客户的允许范围。这一切都是在黑暗中拍摄的,因为我仍在努力围绕身份资源和允许的范围进行思考。

因为我是 identityserver4 的新手,所以请尽可能详细。提前致谢!

名为 "profile" 的身份资源中应该已经有 "scope" 具有一组用户声明 - 其中一个是 "picture"。

由于您使用的是 ASP.NET 身份,因此您需要将任何给定用户的记录插入到 AspNetUserClaims table 中,声明类型为 "picture",其中值为url 的在线图像。

已获得 "profile" 范围的客户端在向 UserInfo 端点发出请求时应收到此 "picture" 声明。

如果您想将该图片作为 id_token 的一部分,那么您还需要将 "picture" 声明添加到 "openid" scope/resource到 "profile" scope/resource.

(术语范围和资源在 Identity Server 数据模型中混合在一起。)

--

要从 Google 获取图片声明,您可以这样做:

info.Principal.Claims.Where(x => x.Type == "picture").Select(x => x.Value).FirstOrDefault()

--

当使用Microsoft.AspNetCore.Authentication.Google时,即app.UseGoogleAuthentication(google.Options(externalCookieScheme),Google不发送图片声明。

如果您切换到使用 OIDC 方法,那么 Google 会向您发送图片声明。

        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            AuthenticationScheme = "oidc-google",

            DisplayName = "Google",
            Authority = "https://accounts.google.com",
            ClientId = "",
            ClientSecret = "",
            Scope = { "profile", "email", "openid" },
            CallbackPath = "signin-google",
            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                RoleClaimType = "role",
                ValidateIssuer = false
            }
        });