Refreshing OIDC Tokens in C# .Net

by Markus
~1 minute
Refreshing OIDC Tokens in C# .Net

Refreshing a JWT code snippet.

Prepare request body.

string bodyString =
    $"grant_type=refresh_token" +
    $"&client_id=[myClientId]" +
    // not required in public applications
    // $"&client_secret=[myClientSecret]" +
    $"&refresh_token=[myRefreshToken]";

var requestBody = new StringContent(
    bodyString,
    Encoding.UTF8,
    "application/x-www-form-urlencoded");

Call api to get a new jwt. Reuse HttpClient, since it should not be reinstanciated many times. Use System.Text.Json to desiralize input json.

using HttpClient client = new();
HttpResponseMessage httpResponseMessage = await client.PostAsync([myTokenUrl], requestBody);

if (httpResponseMessage.IsSuccessStatusCode)
{
    var response = httpResponseMessage.Content.ReadAsStringAsync().Result;
    return JsonSerializer.Deserialize<TokenInfo>(response);
}

The token information should have the following format:

public class TokenInfo
{
    [JsonPropertyName("access_token")]
    public string AccessToken { get; set; }
    [JsonPropertyName("expires_in")]
    public ulong ExpiresIn { get; set; }
    [JsonPropertyName("refresh_expires_in")]
    public ulong RefreshExpiresIn { get; set; }
    [JsonPropertyName("refresh_token")]
    public string RefreshToken { get; set; }
    [JsonPropertyName("token_type")]
    public string TokenType { get; set; }
    [JsonPropertyName("id_token")]
    public string IdToken { get; set; }
    [JsonPropertyName("not-before-policy")]
    public ulong NotBeforePolicy { get; set; }
    [JsonPropertyName("session_state")]
    public string SessionState { get; set; }
    [JsonPropertyName("scope")]
    public string Scope { get; set; }
}

That's about it.