Restsharp request to microsoft graph coming back unauthorized

I am attempting to access some graph items with a RestSharp request. I know I need to somehow use the client ID and secret to obtain a token and use that for authorization but an really new to all of this and have no clue how to do so. I am using openIDConnect for initial authorization to Azure and here is my code for the request:

protected void btnRestSharp_Click(object sender, EventArgs e)
{
    ClaimsIdentity identity = this.User.Identity as ClaimsIdentity;
    string email = identity.Claims.FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value;

    var client = new RestSharp.RestClient("https://graph.microsoft.com");

    var request = new RestSharp.RestRequest($"/v1.0/users/" + email + "?$select=jobTitle,employeeId,officeLocation,department", RestSharp.Method.Get);
    var callbackResult = client.Execute(request);

    if (callbackResult.StatusCode == HttpStatusCode.OK)
    {
        lblRestSharp.Text = "OK";
    }
    else
    {
        lblRestSharp.Text = "status code:  " + callbackResult.StatusCode.ToString();
    }
}

The above is my first and only attempt to access the graph that actually produced a response code.

Upvotes: 0

Views: 171

Answers (1)

Architect Jamie
Architect Jamie

Reputation: 2599

You neee to obtain a token first, from the identity server's OAuth endpoint.

You should use a service principal for authentication. If you haven't already created one, follow the steps here:

https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal

Once done, and you have the tenantId, clientId, and clientSecret, you can authenticate and make calls to the Graph API. Make sure you assigned roles/permissions to the service principal as required. The main thing here is that you're going to obtain a token from the auth server and send that as a Authorization header with future Graph requests. Here's an example using RestSharp.

using RestSharp;
using System;

class Program
{
    static void Main()
    {
        // Azure AD details
        string tenantId = "YOUR_TENANT_ID";
        string clientId = "YOUR_CLIENT_ID";
        string clientSecret = "YOUR_CLIENT_SECRET";
        string tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";

        // Authenticate and get access token
        var client = new RestClient(tokenEndpoint);
        var request = new RestRequest(Method.POST);
        request.AddParameter("scope", "https://graph.microsoft.com/.default");
        request.AddParameter("client_id", clientId);
        request.AddParameter("client_secret", clientSecret);
        request.AddParameter("grant_type", "client_credentials");

        var response = client.Execute(request);
        var tokenResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenResponse>(response.Content);
        string accessToken = tokenResponse.AccessToken;

        // Make API call to Azure Graph API
        var graphClient = new RestClient("https://graph.microsoft.com/v1.0/users");
        var graphRequest = new RestRequest(Method.GET);
        graphRequest.AddHeader("Authorization", $"Bearer {accessToken}");

        var graphResponse = graphClient.Execute(graphRequest);
        Console.WriteLine(graphResponse.Content);
    }
}

public class TokenResponse
{
    public string AccessToken { get; set; }
}

Upvotes: 0

Related Questions