【问题标题】:ASP.NET Core Facebook Authentication Middleware user pictureASP.NET Core Facebook 身份验证中间件用户图片
【发布时间】:2017-07-22 18:31:24
【问题描述】:

我正在尝试使用 ASP.NET Core 1.0 中的 Facebook 身份验证中间件检索用户个人资料图片。我已设法添加这些配置以使用户图片可用

app.UseFacebookAuthentication(new FacebookOptions()
        {
            AppId = Configuration["Authentication:Facebook:AppId"],
            AppSecret = Configuration["Authentication:Facebook:AppSecret"],
            Scope = { "public_profile" },
            Fields = { "picture" }
        });

并检索数据

var email = info.Principal.FindFirstValue(ClaimTypes.Email);

var userName = info.Principal.FindFirstValue(ClaimTypes.GivenName);

但是由于没有Claim Type,我现在如何检索用户图片?

【问题讨论】:

  • 在这种情况下你是如何定义info的?

标签: facebook authentication asp.net-core claims


【解决方案1】:

是的,一般情况下,如果您指定Fields = { "picture" },UserInfo Endpoint 的标准(oauth)实现可能会返回图片作为响应。

Facebook Graph API 提供 https://graph.facebook.com/v2.6/me 作为 UserInformation 端点,ASP.NET Core Facebook Auth 中间件将其用于声明填充。

问题在于,如果您使用此 \me 端点,Facebook Graph API 不会返回 picture 作为响应。他们以前这样做过,但由于某种原因已将其删除。相关SO:facebook oauth, no picture with basic permissions

但是您可以使用以下方法获取图片: https://graph.facebook.com/USERNAME/picture

【讨论】:

  • 那我必须用javascript来做吗?获取用户名/user_id 然后检索它?
  • 你能告诉我一些关于这个中间件的例子或文档吗?
  • @Ahmad 您可以在客户端或服务器端进行此调用 - 只需将访问令牌与请求一起使用。恐怕现在关于中间件的最好信息是github上的源代码github.com/aspnet/Security/tree/master/src/…
  • 泰!你能否请包括你将如何在服务器端做到这一点的例子......也许通过某种方式扩展这个中间件或其他东西
  • 因为我是 ASP.NET Core 的新手,所以我无法理解如何使用其他类似的答案来解决关于 SO 的一些类似问题。
【解决方案2】:

正如 Set 在他的回答中所说,您可以使用 Facebook Graph API 获取图片,例如 https://graph.facebook.com/{user-id}/picture

示例代码:

var info = await _signInManager.GetExternalLoginInfoAsync();
var identifier = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier); 
var picture = $"https://graph.facebook.com/{identifier}/picture";

您可能想检查info 是否不为空以及info.LoginProvider 是否为facebook。

【讨论】:

  • 那么NameIdentifier就是用户ID?
  • @Ahmad 可以,可以看源码here
  • tmg 提供的代码不返回 Facebook 用户 ID,而是返回 Web 应用程序中使用的用户 ID。如何获取 Facebook 用户 ID?
【解决方案3】:

在我的项目 ASP.NET Core 2.2 中,我使用以下代码:

services.AddAuthentication()
    .AddFacebook(options =>
    {
        options.AppId = Configuration["Authentication:Facebook:AppId"];
        options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
        options.Events.OnCreatingTicket = (context) =>
        {
            var picture = $"https://graph.facebook.com/{context.Principal.FindFirstValue(ClaimTypes.NameIdentifier)}/picture?type=large";
            context.Identity.AddClaim(new Claim("Picture", picture));
            return Task.CompletedTask;
        };
    });

在 Controller 中,在 ExternalLoginCallback 操作中,我以这种方式检索值:

var info = await _signInManager.GetExternalLoginInfoAsync();
var picture = info.Principal.FindFirstValue("Picture");

【讨论】:

    猜你喜欢
    • 2018-01-30
    • 1970-01-01
    • 2018-07-06
    • 2018-01-28
    • 2022-11-17
    • 2018-12-17
    • 2019-09-03
    • 1970-01-01
    • 2011-08-17
    相关资源
    最近更新 更多