GUITACA BLOGS
Blogs from our authors

Office 365: The best recipes for developers
Gustavo Velez
Learn more and buy
Return to Blogs
RestSharp to get the Azure AD tokens for Microsoft GraphGustavo Velez
RestSharp is a library for CSharp that simplifies working with REST. It can be used to get the authentication tokens from Azure AD to work with Microsoft Graph26-10-2020
Graph

RestSharp is an Open Source REST API client library for .NET (http://restsharp.org). The source code can be found on the GitHub site https://github.com/restsharp/RestSharp. RestSharp can strongly simplify the source code used to make any REST call.

One of the characteristics of RestSharp is its ability to use OAuth 2, making it suitable to get tokens from Azure AD and to make calls to Microsoft Graph.

To use RestSharp in Visual Studio, install the NuGet RestSharp by John Sheehan in the solution, or download it from https://www.nuget.org/packages/RestSharp and install it in the development computer. Then, add a directive using RestSharp; at the beginning of the code in the Visual Studio solution.

Any call to Microsoft Graph must always retrieve the Azure AD token given by one App Registration, and then send the token in the query call. The next routine shows how to use RestSharp to get the token for an App Permissions registration.

static string GetTokenRestSharpAppPerm()
{
    // Uses MSAL + RestSharp
    string LoginUrl = "https://login.microsoftonline.com";
    string ScopeUrl = "https://graph.microsoft.com/.default";
    string myTenantName = "m365x934477.onmicrosoft.com";
    string myUri = LoginUrl + "/" + myTenantName + "/oauth2/v2.0/token";

    RestClient myClient = new RestClient();
    RestRequest myRequest = new RestRequest(myUri, Method.POST);
    myRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded");
    string myBody = "Scope=" + HttpUtility.UrlEncode(ScopeUrl) + "&" +
                    "grant_type=client_credentials&" +
                    "client_id=" + clientIdAppPerm + "&" +
                    "client_secret=" + clientSecretAppPerm;
    myRequest.AddParameter("", myBody, ParameterType.RequestBody);
    string tokenJSON = myClient.Execute(myRequest).Content;
    AdAppToken tokenObj = JsonConvert.DeserializeObject(tokenJSON);

    return tokenObj.access_token;
}

And for a Delegated Permissions registration, the routine would be as follows.

static string GetTokenMsalRSharpDelPerm()
{
    // Uses MSAL + RestSharp
    string LoginUrl = "https://login.microsoftonline.com";
    string ScopeUrl = "https://graph.microsoft.com/.default";
    string myTenantName = "m365x934477.onmicrosoft.com";
    string myUri = LoginUrl + "/" + myTenantName + "/oauth2/v2.0/token";

    RestClient myClient = new RestClient();
    RestRequest myRequest = new RestRequest(myUri, Method.POST);
    myRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded");
    string myBody = "Scope=" + HttpUtility.UrlEncode(ScopeUrl) + "&" +
                    "grant_type=Password&" +
                    "client_id=" + clientIdDelPerm + "&" +
                    "Username=" + userNameDelPerm + "&" +
                    "Password=" + userPwDelPerm;
    myRequest.AddParameter("", myBody, ParameterType.RequestBody);
    string tokenJSON = myClient.Execute(myRequest).Content;
    AdAppToken tokenObj = JsonConvert.DeserializeObject(tokenJSON);

    return tokenObj.access_token;
}

In both cases, the token is returned as a JSON string. To facilitate the recovering on the token (of any of the other properties), the JSON is deserialized to an object using the next class definition:

public class AdAppToken
{
    public string token_type { get; set; }
    public string expires_in { get; set; }
    public string ext_expires_in { get; set; }
    public string expires_on { get; set; }
    public string not_before { get; set; }
    public string resource { get; set; }
    public string access_token { get; set; }
}

Both routines use some variables containing the data from the App Registration:

static string tenantId = "9e5f418c-8a47-4228-aa48-17d7555e2400";

static string clientIdAppPerm = "f3ac8ba4-5039-4db7-95df-728ee8f19140";
static string clientSecretAppPerm = "WJoH95-6UG12A-o2VN-xO87jqq_FAO_Ztu";

static string clientIdDelPerm = "2c51655f-204a-4c26-a85c-fd0c31776668";
static string userNameDelPerm = "user@domain.onmicrosoft.com";
static string userPwDelPerm = "MyVerySafePw";

The tenantId and ClientID are shown in the Azure App Registration:

The clientSecret can be copied when the secret is created. A Delegated Permissions always uses the name and password credentials of the account, of the me keyword, which is just an alias for both.

Return to Blogs