首页 > 解决方案 > MS Graph Api 调用丢弃“令牌不包含权限,或权限无法理解。”

问题描述

使用以下代码会丢弃带有以下消息的异常:“NoPermissionsInAccessToken 令牌不包含权限,或者无法理解权限。”

var clientId = "<GUID-goes-here>";  
var tenantId = "<GUID-comes-here>";  
var clientSecret = "<secret-goes-here>";
var scopes = new[] {"https://graph.microsoft.com/.default"};
var confidentialClientApplication = ConfidentialClientApplicationBuilder  
    .Create(clientId) 
    .WithClientSecret(clientSecret)          
    .WithTenantId(tenantId)
    .Build();  
var authResult = confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().Result;
string token = authResult.AccessToken;

var authenticationProvider = new DelegateAuthenticationProvider(async (request) => {
    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
    await Task.FromResult<object>(null);
});

var graphClient = new GraphServiceClient(authenticationProvider);

var queryOptions1 = new List<QueryOption>()
{
    new QueryOption("startDateTime", "2020-05-16" ),
    new QueryOption("endDateTime", "2020-05-21"),
};

var calendar = graphClient.Me.Calendar.CalendarView
    .Request(queryOptions1)
    .OrderBy("start/dateTime")
    .Top(3)
    .GetAsync()
    .Result;
// DROPS
// ServiceException: Code: NoPermissionsInAccessToken
// Message: The token contains no permissions, or permissions can not be understood.

该应用程序已注册,Calendars.Read,Calendars.Read.Shared 权限被授予。令牌值似乎不错 - 大约 1400 个字符长。

有人知道这里发生了什么吗?欢迎任何建议!谢谢。

标签: c#exceptionmicrosoft-graph-apitoken

解决方案


在这里,您使用的是客户端凭据流,您需要为此指定应用程序权限,以便它们可以显示在令牌中。

您可以通过将令牌放入https://jwt.ms来简单地解析令牌,然后查看您是否拥有令牌中的权限。

您在这里错过的另一件事是您me在代码中使用,这意味着应该有一个用户如何在此处登录,但没有用户,因为您正在使用 App 上下文流。因此,只需添加应用程序权限,然后调用 API,如下所示。

var calendarView = await graphClient.Users["userid"].CalendarView
    .Request( queryOptions )
    .GetAsync();

推荐阅读