C# Example to Generate an Access Token

Modified on Thu, 14 Sep 2023 at 03:16 PM

For supply queries, try using the code below:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace ClientCredentialsFlowExample
{
    internal class Program
    {
        public static async Task Main(string[] args)
        {
            string tokenEndpoint = "https://identity.nexar.com/connect/token";
            string clientId = "YOUR_CLIENT_ID";
            string clientSecret = "YOUR_CLIENT_SECRET";

            var httpClient = new HttpClient();

            var request = new HttpRequestMessage(HttpMethod.Post, tokenEndpoint);
            request.Headers.Authorization = CreateBasicAuthenticationHeader(clientId, clientSecret);
            request.Content = new FormUrlEncodedContent(
                new Dictionary<string, string>
                {
                    { "grant_type", "client_credentials" },
                    { "scope", "supply.domain" }
                });

            var response = await httpClient.SendAsync(request);
            response.EnsureSuccessStatusCode();

            string content = await response.Content.ReadAsStringAsync();
            var respObj = JsonSerializer.Deserialize<TokenResponse>(content);
            string accessToken = respObj.AccessToken;

            Console.WriteLine($"Access token: {accessToken}");
        }

        private static AuthenticationHeaderValue CreateBasicAuthenticationHeader(string clientId, string clientSecret)
        {
            string creds = $"{clientId}:{clientSecret}";
            string encodedCreds = Convert.ToBase64String(Encoding.UTF8.GetBytes(creds));
            return new AuthenticationHeaderValue("Basic", encodedCreds);
        }
    }

    internal class TokenResponse
    {
        [JsonPropertyName("access_token")]
        public string AccessToken { get; set; }

        [JsonPropertyName("expires_in")]
        public int ExpiresIn { get; set; }

        [JsonPropertyName("scope")]
        public string Scope { get; set; }
    }
}

For this code to work, you will need to ensure the NuGet package System.Text.Json is installed. The code assumes .NET Framework 4.8, so may need small adaptations to work on other .NET versions.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article