C# example: Getting a bearer token

OAuth is hard, so here is a quick example of how to exchange your server credentials for a bearer token in order to access the API.

📘

This example is in C# using a specific library

However, there are plenty of certified libraries compatible with many popular programming languages. You can find a list here: https://openid.net/developers/certified/

1. Get your ClientId and ClientSecret

Please contact you customer success manager to obtain your server credentials

2. Install OAuth client library

For this example, we will be using IdentityModel.OidcClient2

Install-Package IdentityModel.OidcClient

3. Generate token

Thanks to the maintainers of this library, it is relatively simple to generate a bearer token. Please note: bearer tokens expire, so you will need to repeat this process once your token expires. Our token lifespans are currently 1 hour.

public static async Task  Main(string[] args)
{
    const string identityUrl = "https://app.altruisticidentity.com";
    const string clientId = "fetch-from-config";
    const string clientSecret = "fetch-from-config";
    const string credentialsScope = "platformapiaccess";

    TokenResponse tokenResponse;
    using (var httpClient = new HttpClient())
    {
        httpClient.BaseAddress = new Uri(identityUrl);

        var disco = await httpClient.GetDiscoveryDocumentAsync();

        tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
        {
            Address = disco.TokenEndpoint,
            ClientId = clientId,
            ClientSecret = clientSecret,
            Scope = credentialsScope
        });
    }

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

4. Make an API call

We are huge fans of Flurl, so for this part we will be installing the nuget package:

Install-Package Flurl.Http

We can then use the access token we have generated, add it to the HTTP header and call the API

public static async Task<dynamic> GetMembers(
    Guid platformId,
    string accessToken)
{
    return await $"https://api.joyful.org/platforms/{platformId}/members/"
        .WithOAuthBearerToken(accessToken)
        .GetJsonAsync();
}