Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get external login profile picture from Microsoft account in asp.net core

Tags:

asp.net

how can I get profile picture from Microsoft account using Microsoft.AspNetCore.Authentication.Facebook library? I tried using Claims, but they don't have profile picture value... I also tried looking in account's source control by checking image url, but I noticed that the url is made of some parameters that I can't get with claims, so I can't construct url like I can with facebook... Can someone can help me?

like image 256
Nikas Žalias Avatar asked Oct 17 '22 12:10

Nikas Žalias


1 Answers

You can obtain the profile picture from Microsoft accounts by using Microsoft Graph: https://developer.microsoft.com/en-us/graph/quick-start

Specific instructions on how to request the profile picture: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/profilephoto_get

If you follow the quick start (select asp.net, click "Get an app ID and secret" and download the sample code), it's easy to obtain the data like so:

GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();

var photoStream = await graphService.GetCurrentUserPhotoStreamAsync(graphClient);

EDIT: Sorry, forgot the asp.net core part (it doesn't seem that Microsoft.Identity.Client is available for asp.net core).

In ExternalLoginCallback you can obtain the access token from the ExternalLoginInfo object returned by var info = await _signInManager.GetExternalLoginInfoAsync(); Remember to set SaveTokens to true when configuring authentication (otherwise the access token won't be available):

services.AddAuthentication()
    .AddMicrosoftAccount(options =>
    {
        options.ClientId = Configuration["ExternalProviders:Microsoft:ClientId"];
        options.ClientSecret = Configuration["ExternalProviders:Microsoft:ClientSecret"];
        options.SaveTokens = true;
        ...

Then it's just a matter of making a http request - something like this:

var httpClient = new HttpClient();
httpClient.SetBearerToken(info.AuthenticationTokens.Where(t => t.Name.Equals("access_token")).First().Value);
var pictureResult = httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photo/$value").Result;
like image 140
sje Avatar answered Oct 21 '22 09:10

sje