【发布时间】:2017-07-14 12:04:07
【问题描述】:
我从我的问题开始。如何使用在 Azure AD 中执行的应用注册,使用 Microsoft Graph 从我的 AAD 中读取数据?现在详细...
我在我的 Azure Active Directory 中创建了一个应用注册,并允许在那里访问 Microsoft Graph:
确切地说,该应用具有以下权限:
- 应用程序权限
- 读取所有用户的相关人员列表并搜索目录
- 阅读所有用户的完整个人资料
- 委派权限 (无)
我在我的 ASP.NET MVC 应用程序中使用以下代码根据 AAD 对我的网站进行身份验证:
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties
{
RedirectUri = "/"
},
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
这几乎是进行组织身份验证的默认设置。这很有效,我什至可以从 AAD 个人资料中读出我的用户信息:
private string GetUserName()
{
var claimsPrincipal = ClaimsPrincipal.Current;
var firstName = claimsPrincipal.FindFirst(ClaimTypes.GivenName).Value;
var lastName = claimsPrincipal.FindFirst(ClaimTypes.Surname).Value;
return $"{firstName} {lastName}";
}
现在我尝试使用 Microsoft Graph 来选择头像图像。有一些官方的 MS 样本可用here。但它们都依赖于一个名为Microsoft.Identity.Client 的 NuGet 包,目前是预览版。另一件事是 MS 希望我在 Application Registration Portal 下注册我的应用程序,这对我来说毫无意义,因为我已经有一个注册的应用程序。
我已经尝试从我的声明身份中检索我的不记名令牌并在 Graph 中使用它,如下所示:
var ci = (System.Security.Claims.ClaimsIdentity)ClaimsPrincipal.Current.Identity;
var token = ((System.IdentityModel.Tokens.BootstrapContext)ci.BootstrapContext).Token;
var endpoint = "https://graph.microsoft.com/v1.0/me/photo/$value";
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, endpoint))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStreamAsync();
}
}
}
return null;
但这给了我的 401。
【问题讨论】:
标签: c# asp.net .net azure azure-active-directory