访问令牌验证失败Microsoft Graph API

时间:2019-10-15 14:12:07

标签: c# .net console-application microsoft-graph

我正在用C#构建console application
我想对 Microsoft Graph API 进行一些调用,以访问和编辑 SharePoint中的一些Excel文件< / em>,这样我就可以自动化组织中的某些流程。


应用程序的逻辑很简单。

  1. 我致电Azure Active Directory使用 clients凭据流验证此控制台应用程序,这意味着我们将提供一个clientID和AppKey。我从Azure Active Directory>应用程序注册中获取了clientID和AppKey。 enter image description here
  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"
    }
  }
}

下面,您将找到应用程序的完整代码,其中包括获取访问令牌和调用Graph 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上运行查询并正常运行。
enter image description here 为什么在控制台应用程序上会出现此错误?

2 个答案:

答案 0 :(得分:1)

我认为问题出在您在代码中指定的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";

答案 1 :(得分:1)

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

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

但是您仍然需要在应用程序中选择要定位的范围。 目前,您的操作方式似乎已经获得/设置了Graph Explorer为您完成的相关范围。

我建议您遵循此快速入门教程,了解如何构建点网核心控制台应用程序,您应该立即启动并运行。 它使用的MSAL库比您在方案中使用的ADAL库更好。

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