我已經從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瀏覽器上工作而不是用本地主機。
你可以分享你的訪問令牌(模糊處理敏感信息之後)?您希望確保使用帶有用戶上下文的訪問令牌,否則Graph API將不知道「我」是誰。 –