c# - 如何使用 ASP.Net Core Identity 从登录用户检索 Facebook 个人资料图片?

标签 c# facebook-graph-api asp.net-core asp.net-identity facebook-oauth

我有一个可行的解决方案,但我想知道这是否是正确的方法。这是我到目前为止得到的结果。

我正在使用 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/

相关文章:

java - Android Studio Facebook SDK登录失败

c# - .NET Core 3.1 中具有自定义策略的 IdentityServer4 LocalApi

c# - 不规则形状的 Windows 窗体 (C#)

c# - 无法读取注册表 : System. Security.SecurityException,不允许请求的注册表访问

c# - Unity 将嵌套字典序列化为 JSON

facebook - 这个应用程序的开发者没有为 Facebook 登录正确设置这个应用程序?

c# - 了解使用固定{}、Marshal.AllocHGlobal() 和 GCHandle.Alloc() 之间的区别

php - 使用序列化将数组存储在数据库中,但在 php 中反序列化时出现偏移错误。

c# - 无法在 Razor 组件中呈现原始 html

c# - 如何在asp.net core razor Pages项目中调用 Controller 中定义的函数