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

Introduction

ASP.NET is a popular programming language used for building web applications. In this article, we will discuss how to get an external login profile picture from a account in ASP.NET Core.

Step 1: Configure Microsoft Authentication

The first step is to configure Microsoft authentication in your ASP.NET Core application. This can be done by adding the necessary configuration in the Startup.cs file. Here is an :


 void ConfigureServices(IServiceCollection services)
{
    // Other 

    services.AddAuthentication()
        .AddMicrosoftAccount( =>
        {
            options.ClientId = "YOUR_CLIENT_ID";
            options.ClientSecret = "YOUR_CLIENT_SECRET";
        });

    // Other configurations
}

In the above code, replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your actual client ID and client secret obtained from the Microsoft Developer Portal.

Step 2: Profile Picture

Once the Microsoft authentication is configured, you can retrieve the profile picture of the logged-in user. Here is an example:


[HttpGet]
public  Task GetProfilePicture()
{
    var user = await _userManager.GetUserAsync(User);
    var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync(user.Id);

    if (externalLoginInfo?.Principal is ClaimsPrincipal claimsPrincipal)
    {
        var pictureUrl = claimsPrincipal.("urn:Microsoft:picture");

        // Use the picture URL as needed
        // ...
    }

    // Handle the case when profile picture is not available
    // ...
}

In the above code, we are using the UserManager and SignInManager to retrieve the external login information of the logged-in user. We then check if the external login info contains a ClaimsPrincipal and retrieve the profile picture URL using the claim type urn:Microsoft:picture.

Step 3: Display Profile Picture

Finally, you can display the retrieved profile picture in your ASP.NET Core application. Here is an example:


Profile Picture

In the above code, we are using the retrieved profile picture URL to display the image in an tag. You can customize the HTML markup as per your application's requirements.

Conclusion

In this article, we discussed how to get an external login profile picture from a Microsoft account in ASP.NET Core. By the outlined above, you can easily retrieve and display the profile picture of the logged-in user in your ASP.NET Core application.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents