访问令牌验证失败 Microsoft Graph API

Access token validation failure Microsoft Graph API

我正在用 C# 构建一个 console application
我想调用 Microsoft Graph API 来访问和编辑我的 SharePoint 中有一些 Excel 文件,这样我就可以在我的组织中自动执行一些流程。


应用程序的逻辑很简单。

  1. 我调用 Azure Active Directory 验证 这个控制台应用程序使用 clients 凭据流 这意味着我们将提供一个 clientsID 和应用密钥。我从 Azure Active Directory > App Registrations 中获取了 clientsID 和 AppKey。
  2. 然后我想接收访问令牌并使用它向 Microsoft Graph API 发出 GET 请求。
    例如https://graph.microsoft.com/v1.0/me/

    但是 回复 我得到的是:

{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure. Invalid audience.",
    "innerError": {
      "request-id": "0a3ec**************",
      "date": "2019-10-15T13:54:33"
    }
  }
}

下面您将找到我的应用程序的完整代码,其中包含获取访问令牌和调用图形的两种方法 API:

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using AuthenticationContext = Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext;

namespace Project_Budget
{
    class Program
    {
        private const string clientId = "14f1****************";
        private const string aadInstance = "https://login.microsoftonline.com/{0}";
        private const string tenant = "******.onmicrosoft.com";
        private const string resource = "https://graph.windows.net";
        private const string appKey = "IKV***********";
        static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

        private static HttpClient httpClient = new HttpClient();
        private static AuthenticationContext context = null;
        private static ClientCredential credential = null;

        static void Main(string[] args)
        {
            context = new AuthenticationContext(authority);
            credential = new ClientCredential(clientId,appKey);

            Task<string> token = GetToken();
            token.Wait();
            //Console.WriteLine(token.Result + "\n");

            Task<string> graphCall = GetExcelFile(token.Result);
            graphCall.Wait();
            Console.WriteLine(graphCall.Result + "\n");
            Console.ReadLine();

        }

        private static async Task<string> GetExcelFile(string result)
        {
            string apiJsonResult = null;
            
            var apiCallString = "https://graph.microsoft.com/v1.0/me/";
         
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
            var getResult = await httpClient.GetAsync(apiCallString);

            if (getResult.Content != null)
            {
                apiJsonResult = await getResult.Content.ReadAsStringAsync();
            }

            
            return apiJsonResult;
        }

        private static async Task<string> GetToken() 
        {
            AuthenticationResult result = null;
            string token = null;
            result = await context.AcquireTokenAsync(resource, credential); //authentication context object
            token = result.AccessToken;
            return token;
        }

        
    }
}

我已将应用程序所需的所有 访问权限 授予 运行。此外,我 运行 对 Graph Explorer 和 运行 的查询正确。
为什么我会在控制台应用程序上收到此错误?

我认为问题在于您在代码中指定的 resource 值。

当前代码:(此资源值 https://graph.windows.net 对应于较早 API 的 Azure AD Graph API)

private const string resource = "https://graph.windows.net";

尝试将其更改为:(此资源值 https://graph.microsoft.com 对应于较新的 Microsoft Graph API,这是您在稍后的代码中调用的 var apiCallString = "https://graph.microsoft.com/v1.0/me/";

private const string resource = "https://graph.microsoft.com";

理想情况下,资源实际上应该是

private const string resource = "https://graph.microsoft.com";

但您仍然需要 select 您希望在应用程序中定位的范围。 您目前的操作方式似乎 acquire/set Graph Explorer 为您完成的相关范围。

我建议您遵循这个关于如何构建 dot net 核心控制台应用程序的快速入门教程,您应该很快就可以 运行 了。 它使用的 MSAL 库比您在场景中使用的 ADAL 库效果更好。

https://docs.microsoft.com/en-us/graph/tutorials/dotnet-core