图形API StatusCode:403,

问题描述

我一直在尝试从下面的代码获取访问令牌。并且一直在使用此令牌从Graph REST API获取数据。传递此令牌时,我无法接收数据,并显示403错误

public static async Task Main(string[] args)
    {
        IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
           .Create("")
           .WithTenantId("fd49eed930e2db05de")
           .WithClientSecret("W9gF..e7JJ_q37Q9z_E3")
           .Build();

        var scopes = new string[] { "https://graph.microsoft.com/.default" };

        var authResult = await confidentialClientApplication.AcquiretokenForClient(scopes).ExecuteAsync();
        string token = authResult.Accesstoken;


        await CallWebApiAndProcessResultASync("https://graph.microsoft.com/v1.0/users",token,display);

    }

    public static async Task CallWebApiAndProcessResultASync(string webApiUrl,string accesstoken,Action<JObject> processResult)
    {
        if (!string.IsNullOrEmpty(accesstoken))
        {
            using (HttpClient HttpClient = new HttpClient())
            {
                var defaultRequestHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer",accesstoken);

                HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
                if (response.IsSuccessstatusCode)
                {
                    string json = await response.Content.ReadAsstringAsync();
                    JObject result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                    processResult(result);
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    string content = await response.Content.ReadAsstringAsync();

                    Console.WriteLine($"Content: {content}");
                }
                Console.ResetColor();
            }
        }
    }

    private static void display(JObject result)
    {
        foreach (JProperty child in result.Properties().Where(p => !p.Name.StartsWith("@")))
        {
            Console.WriteLine($"{child.Name} = {child.Value}");
        }
    }

请注意,我是Azure管理员

Reference Here

解决方法

您是否已针对Microsoft graph API检查了AAD应用程序的权限?

根据List Users的文档,我们需要以下权限之一才能调用此API:

User.Read.All,User.ReadWrite.All,Directory.Read.All,Directory.ReadWrite.All

您可以引用此document使权限名称与作用域名称匹配。