我有一个可行的解决方案,但我想知道这是否是正确的方法。这是我到目前为止得到的结果。
我正在使用 ASP.Net Core 1.1.2 和 ASP.NET Core Identity 1.1.2。
Startup.cs 中的重要部分如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
app.UseFacebookAuthentication(new FacebookOptions
{
AuthenticationScheme = "Facebook",
AppId = Configuration["ExternalLoginProviders:Facebook:AppId"],
AppSecret = Configuration["ExternalLoginProviders:Facebook:AppSecret"]
});
}
FacebookOptions 附带 Microsoft.AspNetCore.Authentication.Facebook nuget 包。
AccountController.cs 中的回调函数如下所示:
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
//... SignInManager<User> _signInManager; declared before
ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
SignInResult signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
byte[] thumbnailBytes = null;
if (info.LoginProvider == "Facebook")
{
string nameIdentifier = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
string thumbnailUrl = $"https://graph.facebook.com/{nameIdentifier}/picture?type=large";
using (HttpClient httpClient = new HttpClient())
{
thumbnailBytes = await httpClient.GetByteArrayAsync(thumbnailUrl);
}
}
//...
}
所以这段代码工作得非常好,但是,如前所述,这是正确的方式(从技术上讲,不是基于意见的)吗?
最佳答案
要从 Facebook 获取头像,您需要配置 Facebook 选项并从 OAuth 订阅 OnCreatingTicket 事件。
services.AddAuthentication().AddFacebook("Facebook", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.ClientId = configuration.GetSection("ExternalLogin").GetSection("Facebook").GetSection("ClientId").Value;
options.ClientSecret = configuration.GetSection("ExternalLogin").GetSection("Facebook").GetSection("ClientSecret").Value;
options.Fields.Add("picture");
options.Events = new OAuthEvents
{
OnCreatingTicket = context =>
{
var identity = (ClaimsIdentity)context.Principal.Identity;
var profileImg = context.User["picture"]["data"].Value<string>("url");
identity.AddClaim(new Claim(JwtClaimTypes.Picture, profileImg));
return Task.CompletedTask;
}
};
});
关于c# - 如何使用 ASP.Net Core Identity 从登录用户检索 Facebook 个人资料图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45855660/