Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Facebook Authentication Middleware user picture

I'm trying to retrieve user profile picture with Facebook Authentication middleware in ASP.NET Core 1.0. I have managed to add these configurations to make the user picture availble

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

and to retrieve data

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

and

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

But How can I now retrieve user picture as there is not Claim Type for it?

like image 294
Ahmad Avatar asked Mar 02 '17 20:03

Ahmad


3 Answers

As Set said in his answer you can get the picture using the Facebook Graph API like this https://graph.facebook.com/{user-id}/picture.

Example code :

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

You might want to check if info is not null and if info.LoginProvider is facebook.

like image 158
tmg Avatar answered Oct 17 '22 02:10

tmg


Yes, in general, the standard (oauth) implementation of UserInfo Endpoint may return picture in response if you specify Fields = { "picture" }.

Facebook Graph API provides https://graph.facebook.com/v2.6/me as UserInformation endpoint and ASP.NET Core Facebook Auth Middleware uses it for claims population.

The problem is that Facebook Graph API doesn't return picture in response if you use this \me endpoint. They did so before but for some reason have removed that. Related SO: facebook oauth, no picture with basic permissions

But you can get the picture using: https://graph.facebook.com/USERNAME/picture

like image 32
Set Avatar answered Oct 17 '22 01:10

Set


In my project ASP.NET Core 2.2 I use this code:

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;
        };
    });

And in Controller, in ExternalLoginCallback action I retrieve value this way:

var info = await _signInManager.GetExternalLoginInfoAsync();
var picture = info.Principal.FindFirstValue("Picture");
like image 31
Hovhannes Bantikyan Avatar answered Oct 17 '22 01:10

Hovhannes Bantikyan