To get access tokens from an OAUTH2 identity server you can make a standard POST request using HttpClient, the easiest way of sending the required credentials is by serializing a dictionary object of values into URL encoded content.

public class Token
{
	public Token()
	{
		Issued = DateTime.Now;
	}

	[JsonProperty("access_token")]
	public string AccessToken { get; set; }

	[JsonProperty("token_type")]
	public string TokenType { get; set; }

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

	[JsonProperty("refresh_token")]
	public string RefreshToken { get; set; }

	[JsonProperty("as:client_id")]
	public string ClientId { get; set; }

	[JsonProperty("userName")]
	public string UserName { get; set; }

	[JsonProperty("as:region")]
	public string Region { get; set; }

	[JsonProperty(".issued")]
	public DateTime Issued { get; set; }

	[JsonProperty(".expires")]
	public DateTime Expires
	{
		get { return Issued.AddMilliseconds(ExpiresIn); }
	}

	[JsonProperty("bearer")]
	public string Bearer { get; set; }
}
public static async Task<Token> GetToken(Uri authenticationUrl, Dictionary<string, string> authenticationCredentials)
{
	HttpClient client = new HttpClient();

	FormUrlEncodedContent content = new FormUrlEncodedContent(authenticationCredentials);

	HttpResponseMessage response = await client.PostAsync(authenticationUrl, content);

	if (response.StatusCode != System.Net.HttpStatusCode.OK)
	{
		string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
		throw new ApplicationException(message);
	}

	string responseString = await response.Content.ReadAsStringAsync();

	Token token = JsonConvert.DeserializeObject<Token>(responseString);

	return token;
}

appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "Authentication": {
    "URL": "AUTHENTICATION_URL",
    "Credentials": {
      "grant_type": "client_credentials",
      "scope": "SCOPE",
      "client_id": "CLIENT_ID",
      "client_secret": "CLIENT_SECRET"
    }
  }
}
public IActionResult Index()
{
	Dictionary<string, string> authenticationCredentials = _config.GetSection("Authentication:Credentials").GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value);

	Token token = Common.GetToken(new Uri(_config["Authentication:URL"]), authenticationCredentials).Result;

	CookieOptions cookieOptions = new CookieOptions()
	{
		Expires = token.Expires
	};

	return View();
}

1 Comment

Harry Saltzman · 17 March 2022 at 2:15 pm

Clean, beautiful and working at first try:
Thx!

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *