0

我已經從Git爲AAD圖形API下載了一個MVC應用程序。我跑這個應用程序,但每次我都沒有得到預期的結果。圖形API不通過項目代碼工作,但通過AD圖形瀏覽器工作的URL相同

要找到錯誤我運行相同的API使用郵遞員和下面生成的令牌是響應。

{ 
    "odata.error": { 
    "code": "Request_ResourceNotFound", 
    "message": { 
     "lang": "en", 
     "value": "Resource not found for the segment 'me'." 
    } 
    } 
} 

我使用下面獲取URL-

https://graph.windows.net/XXXXX/me?api-version=1.6 

此外,爲了確認是不是與AAD Grapg api explorer工作。登錄後,一切工作正常。

下面是我的代碼調用API - Grapg

// Get the access token from the cache 
      string userObjectID = 
       ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier") 
        .Value; 

      string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); 

      //AuthenticationContext authContext = new AuthenticationContext(authority, 
      // new NaiveSessionCache(userObjectID)); 
      ClientCredential credential = new ClientCredential(clientId, appKey); 
      AuthenticationContext authContext = new AuthenticationContext(authority, true); 
      result = await authContext.AcquireTokenAsync(graphResourceId.ToString(), credential); 
      var Token = result.AccessToken; 
      //// AcquireTokenSilentAsync 
      //result = await authContext.AcquireTokenSilentAsync(graphResourceId, credential, 
      // new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); 

      // Call the Graph API manually and retrieve the user's profile. 
      string requestUrl = String.Format(
       CultureInfo.InvariantCulture, 
       graphUserUrl, 
       HttpUtility.UrlEncode(tenantId)); 
      HttpClient client = new HttpClient(); 
      HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); 
      request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); 
      HttpResponseMessage response = await client.SendAsync(request); 

      // Return the user's profile in the view. 
      if (response.IsSuccessStatusCode) 
      { 
       string responseString = await response.Content.ReadAsStringAsync(); 
       profile = JsonConvert.DeserializeObject<UserProfile>(responseString); 
      } 

難道你們,請告訴我什麼是我的代碼的問題。爲什麼它在AAD瀏覽器上工作而不是用本地主機。

+0

你可以分享你的訪問令牌(模糊處理敏感信息之後)?您希望確保使用帶有用戶上下文的訪問令牌,否則Graph API將不知道「我」是誰。 –

回答

0

要請求Azure AD Graph REST的me端點,我們需要使用表示登錄用戶的委託令牌。

你上面的代碼獲得令牌使用客戶機憑證流動是請求訪問令牌表示用於不包含登錄用戶的信息的應用程序。

爲了在MVC應用程序中實現這一點,我們需要在用戶登錄後獲得授權碼後獲取令牌。下一次,我們可以根據登錄用戶從令牌緩存中獲取令牌。

這是給你的參考代碼(從here代碼示例):

result = await authContext.AcquireTokenSilentAsync(graphResourceId, credential, 
       new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); 
+0

謝謝Fei的回覆,我也嘗試過這段代碼,但是使用這段代碼我無法生成令牌。當我使用上面的代碼時,我得到了異常。有什麼缺失嗎? 另外,我已經從git下載了相同的項目,並根據我們的AAD進行配置。 –

+0

我爲這個問題創建了不同的線程,你可以在這裏找到(http://stackoverflow.com/questions/41586897/authcontext-acquiretokensilentasync-throwing-error) –

+0

你有什麼錯誤信息?當用戶在'Startup'類的'AuthorizationCodeReceived'代碼中登錄時,你能夠獲得訪問令牌嗎? –