Path: redb-identity/src/redb.Identity.Client/Backchannel/BackchannelTokenProvider.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Client/Backchannel/BackchannelTokenProvider.cs
----
using System.Text.Json;
using Microsoft.Extensions.Options;
using redb.Identity.Client.Internal;
namespace redb.Identity.Client.Backchannel;
///
/// Caches a client_credentials access token for the backchannel client.
/// Isolated from the global registration so a
/// Web BFF can keep its user-context provider while this one serves machine-context
/// requests. The token comes from the token_endpoint of the discovery document at
/// .
///
internal sealed class BackchannelTokenProvider : IDisposable
{
private readonly HttpClient _http;
private readonly IOptions _opts;
private readonly AuthorityDiscovery _discovery;
private readonly SemaphoreSlim _lock = new(1, 1);
private string? _cachedToken;
private DateTimeOffset _expiresAt = DateTimeOffset.MinValue;
public BackchannelTokenProvider(HttpClient http, IOptions opts)
{
_http = http;
_opts = opts;
_discovery = new AuthorityDiscovery(http, opts.Value.Authority, BackchannelServiceCollectionExtensions.AuthorityOption);
}
public async Task GetAccessTokenAsync(CancellationToken ct = default)
{
if (_cachedToken is not null && DateTimeOffset.UtcNow < _expiresAt - TimeSpan.FromMinutes(1))
return _cachedToken;
await _lock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_cachedToken is not null && DateTimeOffset.UtcNow < _expiresAt - TimeSpan.FromMinutes(1))
return _cachedToken;
var opts = _opts.Value;
if (string.IsNullOrEmpty(opts.ClientId) || string.IsNullOrEmpty(opts.ClientSecret))
throw new InvalidOperationException(
"BackchannelTokenProvider requires BackchannelIdentityClientOptions.ClientId and ClientSecret.");
var tokenEndpoint = await _discovery.GetEndpointAsync("token_endpoint", ct).ConfigureAwait(false);
var form = new FormUrlEncodedContent(new[]
{
new KeyValuePair("grant_type", "client_credentials"),
new KeyValuePair("client_id", opts.ClientId),
new KeyValuePair("client_secret", opts.ClientSecret),
new KeyValuePair("scope", string.Join(' ', opts.Scopes)),
});
using var resp = await _http.PostAsync(tokenEndpoint, form, ct).ConfigureAwait(false);
resp.EnsureSuccessStatusCode();
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
_cachedToken = doc.RootElement.GetProperty("access_token").GetString()!;
var expiresIn = doc.RootElement.TryGetProperty("expires_in", out var ei) ? ei.GetInt32() : 3600;
_expiresAt = DateTimeOffset.UtcNow.AddSeconds(expiresIn);
return _cachedToken;
}
finally
{
_lock.Release();
}
}
public void Dispose() => _lock.Dispose();
}