从AcquireTokenAsync获取令牌返回401未经授权的错误

时间:2017-10-03 10:59:15

标签: c# azure-active-directory access-token adal sharepoint-online

我有一个单页面的Web应用程序。当我通过错误" Failed to acquire token silently as no token was found in the cache. Call method AcquireToken" AcquireTokenSilent时。在我的函数中,我还检查是否存在类似的错误,我将调用AcquireToken,然后我就能获得令牌。

问题是当我访问我的资源(Sharepoint和Graph)时我无法使用该令牌,它通过错误:" The remote server returned an error: (401) Unauthorized."

这是我的功能:

var _appCredentials = new ClientCredential(_aadConfig.ClientId, _aadConfig.ClientSecret);

public async Task<string> GetAccessTokenAsync(string resource)
{
    try
    {
        var token = await _authContext.AcquireTokenSilentAsync(resource, _appCredentials, new UserIdentifier(_userId, UserIdentifierType.UniqueId));
        return token.AccessToken;
    }
    catch (AdalException ex)
    {
        var token = await _authContext.AcquireTokenAsync(resource, _appCredentials);
        return token.AccessToken;
    }
}

我理解当AcquireTokenSilentAsync函数无法获取缓存中的访问令牌并且刷新令牌失败时,会出现异常。当它没有通过异常时,我可以完美地使用该令牌,因此该权限没有问题。

当AcquireTokenSilent异常通过异常时,我希望我在AcquireTokenAsync中获得的令牌应该与AcquireTokenSilentAsync相同,但事实并非如此。 我无法访问我的资源。

我使用Sharepoint和Graph资源,我使用的API是:

Microsoft.SharePoint.Client.GetItems(CamlQuery myquery)
clientContext.Load(items, its => its.Include(
                      i => i["Title"],
                      i => i["ID"],
                      i => i["Author"],
                      i => i["Created"],
                      its => its.ListItemCollectionPosition);

// excute query
clientContext.ExecuteQuery();

GraphClient.Me.Planner.Tasks.Request()

例外情况如下:

   at Service.SharePointService.<GetDocumentTemplatesByCategoryId>d__4.MoveNext() in C:\WORKING\PROJECTS\develop\Service\SharePointService.cs:line 55
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Apps.SPA.Controllers.DocumentController.<GetDocumentTemplatesByCategoryId>d__9.MoveNext() in C:\WORKING\PROJECTS\develop\Apps.SPA\Controllers\DocumentController.cs:line 107

我还附加了我的解码令牌,它是从AcquireTokenAsync生成的,但在我在Sharepoint中查询文档时会返回401 Unauthorized错误。 enter image description here

enter image description here

任何帮助都将受到高度赞赏!

0 个答案:

没有答案