Obtain an authentication token (C#)

Abstract

How to use the GetToken request using C# programming.

Bearer token authentication is used for systems calling the Commerce Engine directly, without going through Sitecore Commerce Engine Connect. To execute any operation in the Sitecore Experience Commerce (XC) system, the calling system must first connect to the Sitecore Identity Server to obtain an authentication token and include it in every call it makes to the Commerce Engine. Other operations can re-use the same token for as long as the token is valid.

The following shows an example of a GetToken request using C#:

public static class SitecoreIdServerAuth
{
  public static async Task<string> GetToken()
  {
    using (var client = new HttpClient())
    {
      client.BaseAddress = new Uri(Console.Program.SitecoreIdServerUri);
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      var content = new FormUrlEncodedContent(new []
      {
        new KeyValuePair<string, string>("client_id", "postman-api"),
        new KeyValuePair<string, string>("scope", "openid EngineAPI postman_api"),
        new KeyValuePair<string, string>("grant_type", "password"),
        new KeyValuePair<string, string>("username", "myUserName"),
        new KeyValuePair<string, string>("password", "myPassword")
       });
      var response = await client.PostAsync("connect/token",content);
      var result = JsonConvert.DeserializeObject<TokenResponse>(response.Content.ReadAsStringAsync().Result);
      return $"Bearer {result.access_token}";
   }
}
private struct TokenResponse
{
  public string access_token { get; set; }
  public long expires_in { get; set; }
  public string token_type { get; set; }
  }
}