Get profile image from Azure Active Directory

We have installed Azure AD as an identity provider in our application. We want to display the profile image that should be obtained from Azuare AD in the application. How to get profile picture from Azure AD?

To verify, I added one Windows Live Id account (which has a profile picture) in Azure AD. Then we tried to use Graph Explorer, but no luck.

Thanks in advance if someone can provide a help / sample code.

Hitesh

+4
source share
3 answers

You can use the Azure Active Directory Graph Client to get a photo of a user's sketch.

var servicePoint = new Uri("https://graph.windows.net");
var serviceRoot = new Uri(servicePoint, "<your tenant>"); //e.g. xxx.onmicrosoft.com
const string clientId = "<clientId>";
const string secretKey = "<secretKey>";// ClientID and SecretKey are defined when you register application with Azure AD
var authContext = new AuthenticationContext("https://login.windows.net/<tenant>/oauth2/token");
var credential = new ClientCredential(clientId, secretKey);
ActiveDirectoryClient directoryClient = new ActiveDirectoryClient(serviceRoot, async () =>
{
    var result = await authContext.AcquireTokenAsync("https://graph.windows.net/", credential);
    return result.AccessToken;
});

var user = await directoryClient.Users.Where(x => x.UserPrincipalName == "<username>").ExecuteSingleAsync();
DataServiceStreamResponse photo = await user.ThumbnailPhoto.DownloadAsync();
using (MemoryStream s = new MemoryStream())
{
    photo.Stream.CopyTo(s);
    var encodedImage = Convert.ToBase64String(s.ToArray());
}

Azure AD , Base64

+3

Graph Explorer . , "signedInUser" , ...

        #region get signed in user photo
        if (signedInUser.ObjectId != null)
        {
            IUser sUser = (IUser)signedInUser;
            IStreamFetcher photo = (IStreamFetcher)sUser.ThumbnailPhoto;
            try
            {
                DataServiceStreamResponse response =
                photo.DownloadAsync().Result;
                Console.WriteLine("\nUser {0} GOT thumbnailphoto", signedInUser.DisplayName);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting the user photo - may not exist {0} {1}", e.Message,
                    e.InnerException != null ? e.InnerException.Message : "");
            }
        }
        #endregion

REST, : GET https://graph.windows.net/myorganization/users//thumbnailPhoto?api-version=1.5 , ,

+2

Azure AD API API API, Microsoft Microsoft, API- Azure AD Graphs .

, Azure AD, URL:

https://graph.windows.net/myorganization/users/{user_id}/thumbnailPhoto?api-version={version}

For example (this is a fake user ID):

https://graph.windows.net/myorganization/users/abc1d234-01ab-1a23-12ab-abc0d123e456/thumbnailPhoto?api-version=1.6

The code below assumes that you already have an authenticated user with a token. This is a simplified example; you will want to change the return value according to your needs, add error checking, etc.

const string ThumbUrl = "https://graph.windows.net/myorganization/users/{0}/thumbnailPhoto?api-version=1.6";

// Attempts to retrieve the thumbnail image for the specified user, with fallback.
// Returns: Fully formatted string for supplying as the src attribute value of an img tag.
private string GetUserThumbnail(string userId)
{
    string thumbnail = "some base64 encoded fallback image";
    string mediaType = "image/jpg"; // whatever your fallback image type is
    string requestUrl = string.Format(ThumbUrl, userId);

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", GetToken());
    HttpResponseMessage response = client.GetAsync(requestUrl).Result;

    if (response.IsSuccessStatusCode)
    {
        // Read the response as a byte array
        var responseBody = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();

        // The headers will contain information on the image type returned
        mediaType = response.Content.Headers.ContentType.MediaType;

        // Encode the image string
        thumbnail = Convert.ToBase64String(responseBody);
    }

    return $"data&colon;{mediaType};base64,{thumbnail}";
}

// Factored out for use with other calls which may need the token
private string GetToken()
{
    return HttpContext.Current.Session["Token"] == null ? string.Empty : HttpContext.Current.Session["Token"].ToString();
}
0
source

Source: https://habr.com/ru/post/1584893/


All Articles