oidc authorization flow in csharp

To perform OIDC Authorization flow in C#, we can use the IdentityModel package which provides several handy utilities.

Here is an example code snippet:

main.cs
using IdentityModel.Client;
using System;
using System.Net.Http;

var discoveryResponse = await HttpClient.GetDiscoveryDocumentAsync("{issuer_url}");

if (discoveryResponse.IsError)
{
    Console.WriteLine(discoveryResponse.Error);
    return;
}

var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "{client_id}", "{client_secret}");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("{api_scope}");

if (tokenResponse.IsError)
{
    Console.WriteLine(tokenResponse.Error);
    return;
}

var httpClient = new HttpClient();
httpClient.SetBearerToken(tokenResponse.AccessToken);

var apiResponse = await httpClient.GetAsync("{api_url}");

if (!apiResponse.IsSuccessStatusCode)
{
    Console.WriteLine(apiResponse.StatusCode);
    return;
}

var content = await apiResponse.Content.ReadAsStringAsync();
Console.WriteLine(content);
862 chars
35 lines

This code snippet follows the Client Credentials flow, but other flows like Authorization Code or Implicit can also be implemented similarly.

The discoveryResponse.TokenEndpoint is the token endpoint URL returned by the OIDC discovery document.

The TokenClient class sends a token request to the token endpoint and receives an access token.

The httpClient.SetBearerToken method sets the token in the Authorization header of subsequent HTTP requests.

Finally, the httpClient.GetAsync method sends an HTTP GET request to the API endpoint, and the response is inspected for success.

Make sure to replace the {} placeholders with actual values specific to your use case.

gistlibby LogSnag