Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

How to get profile image from Azure Active Directory using Microsoft Graph?

I am implementing Microsoft Azure Active Directory authentication using Microsoft Graph and OAuth2 using this tutorial.

Here is my call which fetches me the displayName, givenName, surName, mail, etc.

$graph  = new Graph();
$graph->setAccessToken($accessToken->getToken());

$user   = $graph->createRequest('GET', '/me?$select=displayName,givenName,surName,mail,mailboxSettings,userPrincipalName') 
                ->setReturnType(ModelUser::class)
                ->execute();

$fname  = $user->getGivenName();
$mail   = $user->getMail();

Now using the same call, how can I fetch profile image of the user? I don't want to make a separate API call, but want to fetch the photo in same call.

How can I get the profile image?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cant get users profile image from AAD id token.

The best way of getting the picture is through MS Graph.

In MS Graph API, you can use the below endpoint to fetch photo from Azure AD:

https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/photo/$value

To get this, you need to set the app permission as

To Get profile picture you need at least one of the following permissions User.ReadBasic.All; User.Read.All; User.ReadWrite.All

C# code sample:

public static async Task<System.Drawing.Image> GetMePhotoAsync()
        {
            try
            {
                // GET /me
                Stream photoresponse = await graphClient.Me.Photo.Content.Request().GetAsync();

                if (photoresponse != null)
                {
                    MemoryStream ms = new MemoryStream();
                    photoresponse.CopyTo(ms);
                    System.Drawing.Image i = System.Drawing.Image.FromStream(ms);

                    return i;
                }
                else
                { return null; }
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting signed-in user profilephoto: {ex.Message}");
                return null;
            }
        }

Reference:

Azure AD Get photo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...