Connect to the Microsoft Graph API

Before making any calls to the Graph API, you will need to get an access token. To do this, use the AuthenticationContext and AuthenticationResult classes that are part of the Microsoft.IdentityModel.Clients.ActiveDirectory library.

First, add a reference to Microsoft.IdentityModel.Clients.ActiveDirectory to your solution.

Then add the following using statement in your class.

Now you are ready to get an access token from login.windows.net:

private static async Task<string> GetAccessToken()
{
    var authenticationUrl = "https://login.windows.net/" + "yourtenantupndomain";
    AuthenticationContext authenticationContext = new AuthenticationContext(authenticationUrl, false);

    // Config for OAuth client credentials 
    ClientCredential clientCred = new ClientCredential(
        "yourclientid",
        "yourclientsecret");

    AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl,
        clientCred);
    string token = authenticationResult.AccessToken;
    Token = token;
    return token;
}

The access token is just a string (a very, very long string).

The code above demonstrates steps one and two of the diagram below, comprising the authorization flow.

The request flow (steps 3 and 4 above) is fulfilled with a method like the one I wrote below. You can use this method for almost any Graph API call, as the HTTP method (GET, POST, etc.) can be passed in, as well as the body of the REST call. The body is optional is not needed for simple calls.

  private static string MakeGraphCall(string endpoint, string url, Method method, object body = null)
        {
            var client = new RestClient("https://graph.microsoft.com");
            var request = new RestRequest("/v1.0/"+ endpoint +"/" + url, method);
           
            if (body != null)
            {
                request.RequestFormat = DataFormat.Json;
                request.AddBody(body);
            }
            
            request.AddHeader("Authorization", "Bearer " + Token);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            var response = client.Execute(request);
            return response.Content;
        }

Next is an example of calling the above method for a simple GET request. This code calls the Graph API to load a user object by calling the /users endpoint and passing in the username.

   string userobject = MakeGraphCall("users", username, Method.GET);
   JObject personJson = JObject.Parse(userobject);
   JToken personidtoken = personJson["id"];

This next example shows a DELETE operation. For some more context, it deletes the permissions associated with an item in OneDrive. It uses the /drives/items endpoint.

var deleteResults = MakeGraphCall("users", personid + "/drive/items/" + itemid + "/permissions/" + perm.SelectToken("id").ToString(), Method.DELETE);

The following example uses a PATCH command to rename an item in OneDrive. In this example, it is renaming a folder. The first step is to build the body object so that I can pass it into the PATCH operation.

dynamic body = new ExpandoObject();
body.name = "Previously Shared with Everyone";

Now I am ready to make the REST call to update the folder name.

renameResults = MakeGraphCall("users", personid + "/drive/items/" + folderid, Method.PATCH, body);
%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close