How to retrieve a user image from azure ad using microsoft graph in .net .

yuvraj khanna 5 Reputation points
2024-06-19T06:42:39.6366667+00:00

For Microsoft graph version 5.56.0 . how to retreive user image file with given email address from microsoft entra Id . I have the single tenant id option selected only .

<PackageReference Include="Microsoft.Graph" Version="5.56.0" />

var scopes = new[] { "User.Read" };
            var tenantId = "xxxxxxxxxxxxxxxxx";
            var clientId = "xxxxxxxxxxxxxxxxx"; 
            var clientSecret = "xxxxxxxxxxxxxxxxxxxx";
            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
            };

            var clientSecretCredential = new ClientSecretCredential(
                tenantId, clientId, clientSecret, options);

            var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

            var userEmail = "user@example.com";

            try
            {
               
                var user = await graphClient.Users[userEmail].Request().GetAsync();

               
                if (user != null && !string.IsNullOrEmpty(user.ProfilePictureUrl))
                {
                    Console.WriteLine($"User's Profile Picture URL: {user.ProfilePictureUrl}");
                }
                else
                {
                    Console.WriteLine("User not found or does not have a profile picture.");
                }
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
Developer technologies ASP.NET ASP.NET Core
Microsoft Security Microsoft Entra Microsoft Entra ID
Microsoft Security Microsoft Graph
{count} votes

2 answers

Sort by: Most helpful
  1. Anonymous
    2024-06-19T09:05:25.15+00:00

    Hi @yuvraj khanna , you might try my codes below as I noticed that you are using new ClientSecretCredential. This means you are using client credential flow which requires Application type of API permission. Client credential flow doesn't require a user to sign in first. The codes below allow the application to get profile photo of any user in your tenant base on the user id.

    using Microsoft.Graph;
    using Azure.Identity;
    public async Task<IActionResult> clientAsync() {
        var scopes = new[] { "https://graph.microsoft.com/.default" };
        var tenantId = "tenant_id";
        var clientId = "client_id";
        var clientSecret = "client_Secret";
        var clientSecretCredential = new ClientSecretCredential(
                        tenantId, clientId, clientSecret);
        var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
        var users = await graphClient.Users.GetAsync();
        var photo = await graphClient.Users["user_id/user_principle_name"].Photo.Content.GetAsync();
        return File(photo, "image/jpeg");
    }
    

    The error does not contain a definition for 'Request'... you faced is due to you are using codes for SDK v4.X, but you are using V5.56.0.

    ========================================

    Asking user to sign-in first and get his/her profile photo requires the application to integrate Azure AD authentication, then we can use the Graph SDK for .net to call Graph API. We should have codes below in Program.cs

    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
        .AddInMemoryTokenCaches();
    

    In appsetting.json, my configuration is like this.

    "AzureAd": {
      "Instance": "https://login.microsoftonline.com/",
      "ClientId": "client_id",
      "ClientSecret": "client_secret",
      "Domain": "tenant_id",
      "TenantId": "tenant_id",
      "CallbackPath": "/signin-oidc"
    },
    "DownstreamApi": {
      "BaseUrl": "https://graph.microsoft.com/v1.0",
      "Scopes": "User.Read.All"
    },
    

    Then in the controller, we should inject GraphClient:

    private GraphServiceClient _graphServiceClient;
    public HomeController(GraphServiceClient graphServiceClient)
    {
        _graphServiceClient = graphServiceClient;
    }
    public async Task<IActionResult> IndexAsync()
    {
        var me = await _graphServiceClient.Me.GetAsync();
        var photo = await graphClient.Me.Photo.Content.GetAsync();
        return File(photo, "image/jpeg"); 
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Tiny

    1 person found this answer helpful.

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    1 deleted comment

    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.