Search code examples
c#microsoft-graph-apidotnet-httpclient

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

enter image description here


Solution

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

    POST https://graph.microsoft.com/v1.0/me/getMemberGroups
    
    {
      "securityEnabledOnly": true
    }
    

    enter image description here

    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.

    enter image description here