'sharepointonline userphoto.aspx not returning picture with bearer token

I am trying to retrieve the picture of a user within bot code using the following url using a Bearer token

https://mytenant.sharepoint.com/_layouts/15/userphoto.aspx?size=S&[email protected]

When I check via a browser the picture shows up fine. When trying to retrieve it programmatically, it returns an image but its the default placeholder silhouette grey image.

enter image description here

I gave the app in AAD a good amount of permissions

enter image description here

Any idea what I am missing? Tried all options I could think of.

My code is as follows:

using (HttpClient httpClient = new HttpClient())
{
    byte[] imageBytes = null;
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
    var responseMessage = await httpClient.GetAsync(@"https://mytenant.sharepoint.com/_layouts/15/userphoto.aspx?size=S&[email protected]");
    imageBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
    string filePath = "C:\\Data\\Trash\\MyImage.jpg";
    File.WriteAllBytes(filePath, imageBytes);
}


Solution 1:[1]

You are doing nothing wrong, just the page userphoto.aspx does not understand bearer token authentication. It understands only cookies, as far as I know.

Since you have User.ReadBasic.All anyway you can just use graph to get the photo instead. Replace

https://mytenant.sharepoint.com/_layouts/15/userphoto.aspx?size=S&[email protected]

with:

https://graph.microsoft.com/v1.0/users/[email protected]/photo/$value

And it should go

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1