我目前正在开发一个 ASP.NET MVC 5 站点,该站点使用 Microsoft Graph API 应用程序来检索数据并将其插入 Microsoft Planner。所述站点已经具有 Azure Active Directory 身份验证。我目前正在使用以下代码获取访问令牌以登录到 Graph API 应用程序。
public async Task<ActionResult> SignIn()
{
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
string redirectUri = Url.Action("Authorize", "Planner", null, Request.Url.Scheme);
Uri authUri = await authContext.GetAuthorizationRequestUrlAsync("https://graph.microsoft.com/", SettingsHelper.ClientId,
new Uri(redirectUri), UserIdentifier.AnyUser, null);
// Redirect the browser to the Azure signin page
return Redirect(authUri.ToString());
}
public async Task<ActionResult> Authorize()
{
// Get the 'code' parameter from the Azure redirect
string authCode = Request.Params["code"];
// The same url we specified in the auth code request
string redirectUri = Url.Action("Authorize", "Planner", null, Request.Url.Scheme);
// Use client ID and secret to establish app identity
ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
TokenCache fileTokenCache = new FilesBasedAdalV3TokenCache("C:\\temp\\justin.bin");
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthorityTenantID, fileTokenCache);
AuthenticationResult authResult = null;
try
{
// Get the token silently first
authResult = await authContext.AcquireTokenAsync(SettingsHelper.O365UnifiedResource, credential);
}
catch (AdalException ex)
{
authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, fileTokenCache);
authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
authCode, new Uri(redirectUri), credential, SettingsHelper.O365UnifiedResource);
return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
}
finally
{
// Save the token in the session
Session["access_token"] = authResult.AccessToken;
}
return Redirect(Url.Action("Index", "Planner", null, Request.Url.Scheme));
}
上面的代码毫无问题地获取了访问令牌。我能够毫无问题地获取活动目录的所有用户并将它们存储在数据库中。但是,当我尝试获取与任务相关的任何数据时,我不断收到以下错误
{
StatusCode:401,
ReasonPhrase:'Unauthorized',
Version:1.1,
Content:System.Net.Http.StreamContent,
Headers:{
Transfer-Encoding: chunked request-id:40 b53d20-c4fc-4614-837b-57a6bebb8d79 client-request-id:40 b53d20-c4fc-4614-837b-57a6bebb8d79 x-ms-ags-diagnostic:{
"ServerInfo":{
"DataCenter":"North Europe",
"Slice":"SliceC",
"Ring":"2",
"ScaleUnit":"000",
"Host":"AGSFE_IN_17",
"ADSiteName":"NEU"
}
} Duration:28.4537 Strict-Transport-Security: max-age=31536000 Cache-Control: private Date:Fri,
07 Dec 2018 14:12:50 GMT Content-Type:application/json
}
}
我检查了 azure 应用程序,它具有完全访问权限。对此的任何帮助将不胜感激