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}");
            }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,295 questions
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,106 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,157 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Tiny Wang-MSFT 2,006 Reputation points Microsoft Vendor
    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. Soaad Nahas 0 Reputation points
    2024-06-19T09:40:27.9733333+00:00

    قبول الاجاية وجزيل الشكر علي الإجابة المتقنه

    0 comments No comments

  3. Soaad Nahas 0 Reputation points
    2024-06-19T09:43:53.3+00:00

    اجابه ممتازة ومنظمة

    0 comments No comments