Microsoft Graph API: Httpclient 403 禁止错误

Microsoft Graph API: Httpclient 403 Forbidden error

我有一个 C# MVC Web 应用程序,我试图通过它使用 Microsoft Graph API 读取用户组。但是,当我尝试使用 HttpClient 通过代码执行此操作时,出现“403 Forbidden”错误。 我拥有所有必需的权限,但仍然出现错误,无法获得错误原因或任何解决方案。我什至尝试 google 但找不到任何东西。

如果有人能帮忙。

 try
            {
                using (var httpClient = new HttpClient(HttpClientHelper.GetWinHttpHandler()))
                {
                    var json = @"{ 'securityEnabledOnly': true }";

                    var stringContent = new StringContent(json);

                    httpClient.DefaultRequestHeaders.Clear();
                    httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + graphapitoken);
                    httpClient.BaseAddress = new Uri("https://graph.microsoft.com/");
                    var response = Task.Run(() => httpClient.PostAsync($"v1.0/users/" + UsermailId + "/getMemberGroups", new StringContent(json, Encoding.UTF8, "application/json")));
                    response.Wait();

                    if (response.Result.IsSuccessStatusCode)
                    {
                        string strResponse = await response.Result.Content.ReadAsStringAsync();
                        object dec = JsonConvert.DeserializeObject(strResponse);
                        JObject obj = JObject.Parse(dec.ToString());
                        List<JToken> obj1 = obj["value"].ToList();
                        listAssociatedGroups = obj1.Values<string>().ToList();
                    }
                }
            }

获取令牌

 public class Token
{
    public static string GetToken()
    {
        return GraphToken(ConfigurationManager.AppSettings["ida:Tenant"],ConfigurationManager.AppSettings["ida:ClientId"], ConfigurationManager.AppSettings["ida:ClientSecret"]);
    }
    private static string GraphToken(string tenantId, string clientId, string clientSecret)
    {
        AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId);
        
        ClientCredential credential = new ClientCredential(clientId, clientSecret);
        AuthenticationResult result = authContext.AcquireTokenAsync("https://graph.microsoft.com", credential).GetAwaiter().GetResult(); 
        return result.AccessToken;

    }

    public static string TokenAsync(string tenantId, string clientId, string clientSecret, string resourceURI)
    {
        try
        {
            var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}");

            ClientCredential credential = new ClientCredential(clientId, clientSecret);

            var authenticationResult = authenticationContext.AcquireTokenAsync(resourceURI, credential).GetAwaiter().GetResult();
            return authenticationResult.AccessToken;
        }
        catch (Exception ex)
        {
            throw new Exception("Failed to retrive AAD token");
        }
    }
}

API 我拥有的权限

只是在黑暗中刺了一下: 其中一些权限需要 管理员同意 。 您的应用程序是否已获得这些权限的管理员许可?

首先,您可以直接用 Graph Explorer 测试这个 API。

POST https://graph.microsoft.com/v1.0/me/getMemberGroups

{
  "securityEnabledOnly": true
}

我不确定您在代码中使用了哪种流程来获取访问令牌。如果使用client credentials flow,则需要添加其中一项应用权限。委派权限可用于其他流程。