c# - 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);
解决方案
我假设您已经禁用了应用服务身份验证并启用了 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 应用具有正确的权限集。
希望能帮助到你。
推荐阅读
- c# - 尝试创建列表时无法创建抽象类
使用 csv.GetRecords() 从 CSV - django-views - ModuleNotFoundError:没有名为“条带”的模块
- angular - 过滤器列表 - 逻辑问题
- excel - 另存为 xlsx 然后关闭而不关闭所有工作簿
- bash - 仅当不在 bash 中访问时才替换文件
- javascript - 如何将一组值从输入发送到控制器
- pyspark - 有没有办法从正在执行的 pyspark 脚本中获取胶水作业的成功或失败状态?
- pandas - 在 pandas 中的多行上解析带有日期时间值的转置 CSV
- python-3.x - 为什么在将字节字符串传递给 magic.from_buffer() 时会出现 TypeError?
- azure-digital-twins - 使用 SensorDataUnitType 创建传感器