我从我的问题开始。如何使用Microsoft Graph使用Azure AD内部的应用程序注册来读取AAD中的数据?现在,细节...使用AAD App访问Microsoft Graph
我在Azure的Active Directory中创建一个应用程序的注册,并允许访问Microsoft图表有:
其确切的应用具有以下权限:
- 应用程序的权限
- 阅读所有用户的相关人员名单和搜索导演Ÿ
- 阅读所有用户的全部资料
- 委托权限 (无)
我用下面的代码在我的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}";
}
现在我尝试使用微软图表来optain让说的头像图片。有一些官方MS样品可用here。但他们都依赖于当前预览的名为Microsoft.Identity.Client
的NuGet包。另一件事是,MS要我注册我的应用程序Application Registration Portal这对我来说没有意义,因为我已经有一个注册的应用程序。
我已经试图从我的声明身份找回我的承载令牌和使用它的图形是这样的:
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