ASP.NET核心Facebook身份验证中间件用户图片

问题描述:

我试图用ASP.NET核心1.0中的Facebook身份验证中间件检索用户个人资料图片。我已成功地添加这些配置使用户图片availble的ASP.NET核心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); 

但我怎么能现在检索用户的图片作为有不是索赔类型它?

+0

你是怎么在这种情况下定义'info'的? –

诚如他回答说,你可以使用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。

+0

那么NameIdentifier是用户ID? – Ahmad

+0

@Ahmad是的,你可以看到源代码[这里](https://github.com/aspnet/Security/blob/release/src/Microsoft.AspNetCore.Authentication.Facebook/FacebookHandler.cs#L48)。 – tmg

+0

完美男人! TY!它的工作原理 – Ahmad

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

Facebook Graph API提供https://graph.facebook.com/v2.6/me作为UserInformation端点和ASP.NET Core Facebook Auth Middleware将其用于索赔人群。

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

但是你可以用得到的图片: https://graph.facebook.com/USERNAME/picture

+0

所以我必须在JavaScript中做到这一点?获取用户名/ user_id然后检索它? – Ahmad

+0

,你能指点我一些关于这个中间件的例子或文档吗? – Ahmad

+0

@Ahmad你可以在客户端或服务器端执行此调用 - 只需使用带有请求的访问令牌。恐怕现在有关中间件的最佳信息是github上的源代码https://github.com/aspnet/Security/tree/master/src/Microsoft.AspNetCore.Authentication.Facebook – Set