How to Create a Bearer Token


Here’s the code that I learned to create for generating an authorization token:

Writing the Test

The following test was written to generate a bearer token:

let ``get authorization token``() =
    let section  = ConfigurationManager.GetSection("section.bearerToken") :?> NameValueCollection;
    let kvPairs  = section.AllKeys.Select(fun k -> new KeyValuePair<string, string>(k, section[k]));
    let tenantId = kvPairs.Single(fun v -> v.Key = "tenant_id").Value;
    let clientId = kvPairs.Single(fun v -> v.Key = "client_id").Value;
    let secret   = kvPairs.Single(fun v -> v.Key = "client_secret").Value;
    let scope    = kvPairs.Single(fun v -> v.Key = "scope").Value;

    let token = BearerToken.Create(tenantId, clientId, secret, scope).Result
    token.Length > 1 |> should equal true

Adding a Configuration File

I added a config file to prevent sensitive data from getting checked in to source control.

Here’s the config file I put together:

<?xml version="1.0" encoding="utf-8" ?>
		<section name="section.bearerToken" type="System.Configuration.AppSettingsSection, System.Configuration, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

	<add key="tenant_id"	 value="some_value" />
	<add key="client_id"	 value="some_value" />
	<add key="client_secret" value="some_value" />
	<add key="scope"	 value="some_value" />

Creating an Authorization Token

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace IaC.MyApp;

public static class BearerToken
    public async static Task<string> Create(string tenantId, string clientId, string clientSecret, string scope)
        var tokenRequestBody = new Dictionary<string, string> {

            { "grant_type"   , "client_credentials" },
            { "client_id"    , clientId },
            { "client_secret", clientSecret },
            { "scope"        , scope }

        var url      = $"{tenantId}/oauth2/v2.0/token";
        var client   = new HttpClient() { BaseAddress = new Uri(url) };
        var content  = new FormUrlEncodedContent(tokenRequestBody);
        var response = await client.PostAsync("", content);

        if (response.IsSuccessStatusCode)
            var tokenResponse = await response.Content.ReadAsStringAsync();
            var valueFor      = JsonConvert.DeserializeObject<JsonSupport.AccessToken.Root>(tokenResponse);

            return valueFor.access_token;

        throw new Exception(response.ReasonPhrase);

JSON Support Classes

The following class is used to deserialize JSON to acquire an authorization token:

namespace JsonSupport.AccessToken;

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Root
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public int ext_expires_in { get; set; }
    public string access_token { get; set; }

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: