【问题标题】:How to get profile image from Azure Active Directory using Microsoft Graph?如何使用 Microsoft Graph 从 Azure Active Directory 获取配置文件图像?
【发布时间】:2021-01-06 12:15:31
【问题描述】:

我正在使用此tutorial 使用 Microsoft Graph 和 OAuth2 实施 Microsoft Azure Active Directory 身份验证。

这是我的电话,它为我获取了 displayName、givenName、surName、mail 等。

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

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

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

现在使用相同的调用,我如何获取用户的个人资料图片?我不想进行单独的 API 调用,但想在同一个调用中获取照片。

如何获取个人资料图片?

【问题讨论】:

    标签: azure azure-active-directory


    【解决方案1】:

    您无法从 AAD id 令牌获取用户个人资料图片。

    获取图片的最佳方式是通过 MS Graph。

    在 MS Graph API 中,您可以使用以下端点从 Azure AD 获取照片:

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

    要获得这个,你需要将应用权限设置为

    要获取个人资料图片,您至少需要以下一项 权限User.ReadBasic.All; User.Read.All; User.ReadWrite.All

    C# 代码示例:

    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;
                }
            }
    

    参考:

    Azure AD Get photo

    【讨论】:

      【解决方案2】:

      根据您在问题中的代码,我搜索了 Microsoft 文档,发现无法使用您提供的相同调用来获取个人资料图片。而根据the document,我们可以发现'List user'的api就可以提供这些属性。为了证明这个结论,我还看了creating userupdating user的文档,都显示这个api不支持头像。

      关于如何通过 api 获取头像,@Hari Krishna 提供了解决方案和文档。

      【讨论】:

        猜你喜欢
        • 2020-04-27
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 2021-10-02
        • 2019-12-20
        • 1970-01-01
        • 2021-05-06
        • 1970-01-01
        相关资源
        最近更新 更多