简体   繁体   中英

Microsoft Graph API: Httpclient 403 Forbidden error

I am having a C# MVC web application through which I'm trying to read the user's group using Microsoft Graph API. But when I'm trying to do so through code using HttpClient I'm getting "403 Forbidden" error. I have all the required permissions but still getting the error, can't get the reason for the error or any solution for it. I even tried to google it but couldn't find anything.

If anyone can help.

 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();
                    }
                }
            }

Getting Token

 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 Permissions I have

在此处输入图片说明

Just a stab in the dark: Some of those permissions require admin consent . Does your application have admin consent for those permissions?

First, you could test this API with Graph Explorer directly.

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

{
  "securityEnabledOnly": true
}

在此处输入图片说明

I'm not sure which kind of flows that you used to get access token in your code. If you use client credentials flow , you need to add one of the application permissions. Delegated permissions can be used for the other flows.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM