1
votes

I am trying to get access to SharePoint sites using Microsoft graph and i am getting "Un Authorized" in the response message.

Here is what i am trying to access to get SP sites: https://graph.microsoft.com/beta/sharePoint/sites

The query works in the graph explorer but not through my client code.

Note: the app has full delegated permissions for SharePoint Online and Microsoft Graph.

I tried calling other SharePoint resources from my app and i still get un authorized error messages.

Code:

 using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/beta/sharePoint/sites"))
                {
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    using (HttpResponseMessage response = await client.GetAsync("https://graph.microsoft.com/beta/sharePoint/sites"))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            msgResponse.Status = SendMessageStatusEnum.Sent;
                            msgResponse.StatusMessage = await response.Content.ReadAsStringAsync();
                        }
                        else
                        {
                            msgResponse.Status = SendMessageStatusEnum.Fail;
                            msgResponse.StatusMessage = response.ReasonPhrase;
                        }
                    }
                }
1

1 Answers

3
votes

I found the issue, i need to specify the JSON as a content type and to use SendAsync instead of GetAsync() since i have already have a request object.

 using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/beta/sharePoint/sites"))
                {
                    request.Headers.Accept.Add(Json);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    using (HttpResponseMessage response = await client.SendAsync(request))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            msgResponse.Status = SendMessageStatusEnum.Sent;
                            msgResponse.StatusMessage = await response.Content.ReadAsStringAsync();
                        }
                        else
                        {
                            msgResponse.Status = SendMessageStatusEnum.Fail;
                            msgResponse.StatusMessage = response.ReasonPhrase;
                        }
                    }
                }
            }

Hope this helps.