[SOLVED] How to Update Profile Picture with Microsoft Graph API

Issue

I’m developing a .Net Core 3.1 API that will connect to Microsoft Graph to update photos of company employees.

However, I searched in several places and didn’t find any code or method that could help me change a user’s photo without me being logged in with that user’s account.

Is there any way I can change the photo of a user with Microsoft Graph without me being logged in with the same?

Remembering that my user is the administrator of Azure AD and my application has "User.ReadWrite.All" released.

Solution

Firstly, what you need is this api, and as you can see it provides the application permission so that you can use client credential flow to generate access token and use it to call the api. Client credential flow makes users don’t need to sign in and generate access token, then it can meet your requirement.

Here’s the detail, you can generate token by this request, pls not you need to set User.ReadWrite.All application permission for you azure ad app:

enter image description here

and you can call the api with the token like this:

enter image description here

If you found your token can’t work correctly, maybe you can try to add Group.ReadWrite.All application permission to your azure ad app too, as this is a known issue mentioned in the api document.

And maybe what you need is code snippet, then you can use graph sdk to call ms graph api:

var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_client_id";
var clientSecret = "client_secret_for_the_azuread_app";
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
using var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(@"Binary data for the image"));

await graphClient.Users["user_id_which_you_wanna_change_photo_for"].Photo.Content
    .Request()
    .PutAsync(stream);

Answered By – Tiny Wang

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

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