Home > Enterprise >  Retrieve logged in User Photo from Azure AD
Retrieve logged in User Photo from Azure AD

Time:10-18

We have hosted our web application in azure PaaS. We have used Active Directory authentication in our web application. We have used the below Graph URL and GraphApiVersion to get the user details from Azure AD. GraphApiVersion="2013-11-08" GraphUrl ="https://graph.windows.net"

We are able to fetch the logged in user details from azure AD but we are not able to get the logged in user photo from azure AD. Kindly share the c# sample code to fetch the logged in user photo from azure AD.

Thank you.

CodePudding user response:

I tried in my environment and got below results:

To retrieve the profile photo of logged-in user can be Ms Graph in graph explorer please try the below query:

https://graph.microsoft.com/beta/me/photo/$value

Response: enter image description here

Code:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var stream = await graphClient.Me.Photo.Content
.Request()
.GetAsync();

Response: enter image description here

Reference: Use Microsoft Graph to Retrieve Users Photos and Store Them as Azure Blobs With C# – Mihai-Albert.com

CodePudding user response:

We have used the below code to get the currently logged in user details. But we are not able to retrieve the photo. Please share the full c# code to get the logged in user photo details from Azure AD.

public async Task<ActionResult> UserIndex(string logonname)
        {
            string userPrincipalName = string.Empty;
             AuthenticationResult result = null;
            UserProfile profile;
            string SearchText = logonname;
            try
            {
                Session["tenantid"] = ADtenantid;
                var url = "https://graph.windows.net/"   tenant   "/users/"   SearchText   "@"   Domin   "?api-version="   System.Configuration.ConfigurationManager.AppSettings["ida:GraphApiVersion"];
                var graphUserUrl = string.Format(url);

                string userObjectID = Session["userObjectID"].ToString();
               
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                    new NaiveSessionCache(userObjectID));

                try
                {
                    if (Startup.RefreshToken != "")
                    {
                        ClientCredential credential = new ClientCredential(clientId, appKey1);
                        result = authContext.AcquireTokenByRefreshToken(Startup.RefreshToken, credential);
                        if (result == null)
                        {
                            credential = new ClientCredential(clientId, appKey2);
                            result = authContext.AcquireTokenByRefreshToken(Startup.RefreshToken, credential);
                        }
                    }
                    else if (Session["appKey1"].ToString() == "appKey1")
                    {
                        ClientCredential credential = new ClientCredential(clientId, appKey1);
                        result = authContext.AcquireTokenSilent(graphResourceId, credential,
                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
                    }
                    else
                    {
                        ClientCredential credential = new ClientCredential(clientId, appKey2);
                        result = authContext.AcquireTokenSilent(graphResourceId, credential,
                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
                    }
                }
                catch
                {
                    if (Session["appKey1"].ToString() == "appKey1")
                    {
                        ClientCredential credential = new ClientCredential(clientId, appKey1);
                        result = authContext.AcquireTokenSilent(graphResourceId, credential,
                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
                    }
                    else
                    {
                        ClientCredential credential = new ClientCredential(clientId, appKey2);
                        result = authContext.AcquireTokenSilent(graphResourceId, credential,
                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
                    }
                }

                string requestUrl = String.Format(
                    CultureInfo.InvariantCulture,
                    graphUserUrl,
                    HttpUtility.UrlEncode(ADtenantid));
                HttpClient client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = await client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    string responseString = await response.Content.ReadAsStringAsync()

                    profile = JsonConvert.DeserializeObject<UserProfile>(responseString);

                    userPrincipalName = profile.userPrincipalName.Split('@')[0];
                    if (userPrincipalName != null)
                    {
                        Session.Add("ADUserObjectID", profile.ObjectID);
                        Session.Add("FName", profile.GivenName);
                        Session.Add("LName", profile.Surname);
                        Session.Add("ADUserDisplayName", profile.DisplayName);
                        Session.Add("jobTitle", profile.jobTitle);
                        Session.Add("UserCode", userPrincipalName);
                        Session.Add("UserMailID", profile.Mail);
                        // var thumbnail = GetUserThumbnail(userPrincipalName,result);
                        GetADProfilePhoto ph = new GetADProfilePhoto();
                        var photo = await ph.GetMePhotoAsync(userPrincipalName, result);
                        return RedirectToAction("Login", "Login", new { logonname = userPrincipalName });
                    }
                    else
                    {
                        authContext.TokenCache.Clear();
                        profile = new UserProfile();
                        profile.GivenName = " ";
                        profile.Surname = " ";
                        profile.DisplayName = " ";
                        profile.Mail = "";
                        profile.jobTitle = "";
                        
                    }
                }
                else
                {
                    authContext.TokenCache.Clear();
                    profile = new UserProfile();
                    profile.GivenName = " ";
                    profile.Surname = " ";
                    profile.DisplayName = " ";
                    profile.Mail = "";
                    profile.jobTitle = "";
                    return RedirectToAction("InvalidUser", "Login");
                }
            }
            catch (Exception ex)
            {
                throw ex
            }
            return new EmptyResult()
        }
  • Related