c# - 访问 token 验证失败 Microsoft Graph API

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

我正在用 C# 构建一个控制台应用程序
我想调用 Microsoft Graph API 来访问和编辑我的一些 Excel 文件 < em>SharePoint 这样我就可以在我的组织中自动化一些流程。


应用程序的逻辑很简单。

  1. 我调用 Azure Active Directory 以使用客户端凭据流验证此控制台应用程序,这意味着我们将提供 clientsID 和 AppKey。我从 Azure Active Directory > App Registrations 中获取了 clientsID 和 AppKey。 enter image description here
  2. 然后我想接收访问 token 并使用它向 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"
    }
  }
}

在下面您将找到我的应用程序的完整代码以及获取访问 token 和调用图形 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 为什么我会在控制台应用程序上收到此错误?

最佳答案

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

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

但是您仍然需要选择您希望在应用程序中定位的范围。 您目前执行此操作的方式似乎确实获取/设置了 Graph Explorer 为您完成的相关范围。

我建议您按照这个关于如何构建 dot net 核心控制台应用程序的快速入门教程进行操作,您应该会立即启动并运行。 它使用的 MSAL 库比您在场景中使用的 ADAL 库效果更好。

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

关于c# - 访问 token 验证失败 Microsoft Graph API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58396709/

相关文章:

c# - 在 lambda 表达式中取反 Func<T, bool>

c# - 如何在我的 Windows Mobile 应用程序中显示模态对话框?

.net - 在 app.config 中使用 <codebase> 元素

c# - 如何使用 LINQ 从 IEnumerable<T> 的属性中获取单个 IENumerable<X>?

c# - 如何从 xml 构建 .xsd 文件?

PHP shell_exec 不适用于两个不同的应用程序版本

c# - 面板背景图像重复 C#

c# - Breeze - 如何在保存更改调用之前处理同一 View 中两个实体的状态

c++ - 如何获得对控制台的完全控制?

Delphi 控制台管道已切换?