使用HttpClient向Microsoft Graph请求用户列表时出现未授权的问题

问题描述 投票:0回答:1

我正在尝试通过Microsoft graph.api获取有关用户的信息,“ https://graph.microsoft.com/v1.0/users”。它在下面给我一个错误401未经授权的错误。

 {  
    "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure. Invalid audience.",
       "innerError": {
       "request-id": "3157d513-6f31-4d2d-a3d7-a97eed7207ba",
       "date": "2019-12-11T05:39:02"    
       }
    }
 }

我的.Net Core-C#代码,

 AuthenticationContext authContext = new AuthenticationContext(string.Format(CultureInfo.InvariantCulture,"https://login.microsoftonline.com/{0}", "arcadiso365.onmicrosoft.com"));
        ClientCredential clientCred = new ClientCredential("83ecc218-438f-44a5-931d-d054b50bdc9e", "YXs9T3DB4@ggP=pdFJbkhgM=XdZYOB7/");
        AuthenticationResult authenticationResult = authContext.AcquireTokenAsync("https://graph.windows.net",
                      clientCred).Result;
        var token = authenticationResult.AccessToken;

        var client = new HttpClient();
        var uri = "https://graph.microsoft.com/v1.0/me/";

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(token);
        var response = await client.GetAsync(uri);

我哪里做错了?为什么我没有获得正确的访问令牌?任何人都可以帮助我使用MS Graph吗?

jwt microsoft-graph access-token asp.net-core-2.1 azure-ad-graph-api
1个回答
0
投票

您使用了错误的资源,您需要获取Microsoft Graph的令牌而不是AAD Graph,它应该是https://graph.microsoft.com,而不是https://graph.windows.net

AuthenticationResult authenticationResult = authContext.AcquireTokenAsync("https://graph.microsoft.com",
                      clientCred).Result;

0
投票

[我认为,如果您要调用Microsoft Graph,则资源必须为https://graph.microsoft.com,而不是AAD Graph(graph.windows.net)。您可以在AcquireTokenAsync通话中尝试更改吗?

© www.soinside.com 2019 - 2024. All rights reserved.