2017-07-14 139 views
1

我從我的問題開始。如何使用Microsoft Graph使用Azure AD內部的應用程序註冊來讀取AAD中的數據?現在,細節...使用AAD App訪問Microsoft Graph

我在Azure的Active Directory中創建一個應用程序的註冊,並允許訪問Microsoft圖表有:

AAD portal with required permissions

其確切的應用具有以下權限:

  • 應用程序的權限
    • 閱讀所有用戶的相關人員名單和搜索導演Ÿ
    • 閱讀所有用戶的全部資料
  • 委託權限 (無)

我用下面的代碼在我的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

回答

0

你需要得到與ADAL使用令牌你的應用的客戶端ID和祕密。

您可以從的NuGet獲得ADAL:https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/

如:

string authority = "https://login.microsoftonline.com/your-tenant-id"; 
var authenticationContext = new AuthenticationContext(authority); 

string clientId = "your-app-client-id"; 
string clientSecret = "yourappclientsecret"; 
var clientCredential = new ClientCredential(clientId, clientSecret); 

string resource = "https://graph.microsoft.com"; 
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resource, clientCredential); 

string accessToken = authenticationResult.AccessToken; 

更換您的租戶-ID與Azure的AD租戶ID或域名(例如mytenant.onmicrosoft.com) 。將您的應用客戶端ID爲的替換爲在AAD中註冊的應用的客戶端ID /應用ID。使用爲AAD中的應用程序創建的客戶端密鑰/密鑰替換yourappclientsecret

我在示例中對它們進行了硬編碼,以使其更容易遵循。在生產中,你不應該在代碼中存儲憑據。

相關問題