我從我的問題開始。如何使用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