C# · Track 1 · Tutorial 2 of 3

Get a token and keep it fresh

Sign your code in to BrizoConsol, keep it signed in as the token runs out, and handle the two answers that simply mean try again.

You will needThe project from Set up your C# project.
By the endA client that signs in, renews itself, and waits when BrizoConsol is busy - and a script that shows what your credential may do.

1Understand the two tokens

Your code doesn't send the client secret with every call. It signs in once and gets two tokens back: an access token, sent with every call and good for 60 minutes, and a refresh token, good for 30 days, which buys the next pair.

The exchange: credential in, two tokens out
Signing in: your client ID and secret go in once; an access token and a refresh token come back.

2Add the HTTP call

Add this to the Brizo class in Brizo.cs. It makes one call and gives back the status, the headers and the answer. It asks for JSON on every call, so even a refusal comes back as JSON.

Brizo.cs

    static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(TimeoutSeconds) };

    // One HTTP call: answers the status, the response headers and the decoded JSON body.
    public static async Task<Answer> Send(string method, string path, object? body = null, Dictionary<string, string>? headers = null)
    {
        using var request = new HttpRequestMessage(new HttpMethod(method), BaseUrl + path);
        request.Headers.Accept.ParseAdd("application/json");
        foreach (var (name, value) in headers ?? new())
        {
            request.Headers.TryAddWithoutValidation(name, value);
        }
        if (body is not null || method == "POST")
        {
            var json = body is null ? "" : JsonSerializer.Serialize(body);
            request.Content = new StringContent(json, Encoding.UTF8, "application/json");
        }

        HttpResponseMessage response;
        try
        {
            response = await Http.SendAsync(request);
        }
        catch (Exception e) when (e is HttpRequestException or TaskCanceledException)
        {
            throw new Exception($"Could not reach BrizoConsol: {e.Message}");
        }

        var text = await response.Content.ReadAsStringAsync();
        JsonNode? decoded = null;
        try
        {
            decoded = text == "" ? null : JsonNode.Parse(text);
        }
        catch (JsonException)
        {
            // not JSON: a proxy or gateway answered instead of BrizoConsol
        }

        var responseHeaders = new Dictionary<string, string>();
        foreach (var header in response.Headers.Concat(response.Content.Headers))
        {
            responseHeaders[header.Key.ToLowerInvariant()] = string.Join(", ", header.Value);
        }

        return new Answer((int)response.StatusCode, responseHeaders, decoded);
    }

3Add signing in and renewing

Add these two methods. Brizo.GetToken() signs in. Brizo.RefreshToken() spends the refresh token for a new pair - and if that refresh token was already used or has expired, it signs in again.

Brizo.cs

    static JsonNode? tokens;

    public static async Task<JsonNode> GetToken()
    {
        var answer = await Send("POST", "/tokens", new { client_id = ClientId, client_secret = ClientSecret });
        if (answer.Status != 201)
        {
            throw new Exception($"Sign-in refused ({answer.Status}): {answer.Body?["message"]}");
        }
        tokens = answer.Body!;

        return tokens;
    }

    public static async Task RefreshToken()
    {
        var answer = await Send("POST", "/tokens/refresh", new { refresh_token = tokens!["refresh_token"]!.ToString() });
        if (answer.Status == 201)
        {
            tokens = answer.Body!;
            return;
        }
        await GetToken(); // the refresh token was already used or has expired: sign in again
    }
Renewing: a 401 spends the refresh token for a new pair
How the client keeps signed in: a 401 spends the refresh token, and the call is sent again.

4Add the call every script uses

Every call after signing in goes through Brizo.Call(). It sends the access token, and handles the two answers that mean send it again:

  • 401 - the access token has expired. It renews once and sends the call again.
  • 429 - the company is busy with another write, or your group has used its requests for the minute. Nothing was written, so it waits as long as BrizoConsol asks and sends again.

Brizo.cs

    // Every call after sign-in goes through here. It sends the access token, and handles the two answers that mean
    // "send it again": 401 (the token expired) and 429 (the company is busy, or the minute's requests are used up).
    public static async Task<Answer> Call(string method, string path, object? body = null, Dictionary<string, string>? headers = null)
    {
        if (tokens is null)
        {
            await GetToken();
        }

        var refreshed = false;
        for (var attempt = 1; attempt <= 5; attempt++)
        {
            var withToken = new Dictionary<string, string>(headers ?? new()) { ["Authorization"] = $"Bearer {tokens!["access_token"]}" };
            var answer = await Send(method, path, body, withToken);

            if (answer.Status == 401 && !refreshed)
            {
                await RefreshToken();
                refreshed = true;
                continue;
            }

            if (answer.Status == 429)
            {
                var wait = int.TryParse(answer.Headers.GetValueOrDefault("retry-after"), out var seconds) ? seconds : 5;
                await Task.Delay(TimeSpan.FromSeconds(wait));
                continue; // nothing was written for this call
            }

            return answer;
        }

        throw new Exception($"{method} {path} is still answering 429 after five attempts.");
    }

5Sign in

Create Token.cs and run it:

Token.cs

// Token.cs - signs in with your credential and shows what the token may do.
public static class Token
{
    public static async Task Run(string[] args)
    {
        var tokens = await Brizo.GetToken();

        Console.WriteLine($"Signed in. The access token lasts {tokens["expires_in"]} seconds.");
        Console.WriteLine("It may:");
        foreach (var ability in tokens["abilities"]!.AsArray())
        {
            Console.WriteLine($"  {ability}");
        }
    }
}
dotnet run -- Token

Check

Signed in. The access token lasts 3600 seconds.
It may:
  read
  write
  organisation:149
  scope:accounts.write
  …

organisation: lists each company the credential can reach, and scope: each box you ticked. If sign-in is refused, the message says why: The client id and secret do not match means a typing error in a setting.

Want more detail? See the documentation