Ahmad
Ahmad

Reputation: 2707

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?

Upvotes: 5

Views: 1608

Answers (3)

Hovhannes Bantikyan
Hovhannes Bantikyan

Reputation: 371

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

Upvotes: 1

tmg
tmg

Reputation: 20413

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.

Upvotes: 6

Set
Set

Reputation: 49789

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

Upvotes: 2

Related Questions