C# Code

{Code Snippet}Get Access Token using Basic Authentication and Client credentials Grant Type

While working on one of the integration in our project, We had to get access token using Basic Auth from our external system to perform the CRUD operation. We have used HttpClient and Client credentials Grant Type.

Code to get Access Token using Basic Auth

private static async Task GetToken(string clientId, string clientSecret, string url)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                //Request Body
                JObject requestBody = new JObject
                {
                    {"grant_type", "client_credentials"}
                };
                httpClient.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                var byteArray = Encoding.ASCII.GetBytes(clientId + ":" + clientSecret);
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                HttpResponseMessage response = await httpClient.SendAsJsonAsync(HttpMethod.Post, url, requestBody);

                return !response.IsSuccessStatusCode ? null
                    : response.Content.ReadAsStringAsync().Result;
            }
        }

Use below code to invoke getToken method

string _accessToken = string.Empty;
var getTokenTask = Task.Run(async () => await GetToken(clientId, clientSecret, TokenUrl));
Task.WaitAll(getTokenTask);
if (getTokenTask.Result == null)
return;
//Deserialize the token response to get the access token
TokenResponse tokenResponse = JsonConvert.DeserializeObject(getTokenTask.Result);
_accessToken = tokenResponse.access_token;

Key points

  1. Pass token URL, Client ID and Client Secret to get access token from external system
  2. Use below class to Deserialize the response

[DataContract]
public class TokenResponse
{
[DataMember]
public string token_type { get; set; }
[DataMember]
public string expires_in { get; set; }
[DataMember]
public string ext_expires_in { get; set; }
[DataMember]
public string expires_on { get; set; }
[DataMember]
public string not_before { get; set; }
[DataMember]
public string resource { get; set; }
[DataMember]
public string access_token { get; set; }
}

Hope this helps!

One thought on “{Code Snippet}Get Access Token using Basic Authentication and Client credentials Grant Type

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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