首页 > 解决方案 > MS Graph 和 AAD Graph Rest api 在本地机器调试中工作正常,但在发布到 azure 应用服务后得到禁止响应

问题描述

我正在编写一些代码,分别从 AAD Graph API 和 Microsoft Graph 获取登录的用户个人资料图片和显示名称。

当我在本地调试时,代码运行良好,但在发布到 Azure Web App 服务后出现了 Forbidden 错误。

应用服务已通过 Azure 身份验证启用,并且应用已通过应用注册进行注册以使用 Graph 功能。

result = await authContext
    .AcquireTokenSilentAsync("https://graph.microsoft.com/",
        credential,
        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
    new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", resultpic.AccessToken);

HttpRequestMessage request =
    new HttpRequestMessage(HttpMethod.Get, requestUrl);

HttpResponseMessage response =
    await client.SendAsync(request);

标签: c#asp.net-core-mvcazure-active-directorymicrosoft-graph-api

解决方案


我假设您已经禁用了应用服务身份验证并启用了 Azure AD 作为身份提供者,如下所示:

在此处输入图像描述

要通过 Azure AD 轻松获取照片,目前可以使用以下 URL 模板:

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

下面的代码假设您已经有一个经过身份验证的用户,并带有一个令牌。这是一个简单的例子;您需要更改返回值以满足您的需要,添加错误检查等。

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:{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();
}

还请确保您的 Azure AD 应用具有正确的权限集。

希望能帮助到你。


推荐阅读