Skip to content

Instantly share code, notes, and snippets.

@ThomasPe
Last active August 20, 2024 13:59
Show Gist options
  • Select an option

  • Save ThomasPe/9eeef0ee179a2d252a5bcf1fc277186a to your computer and use it in GitHub Desktop.

Select an option

Save ThomasPe/9eeef0ee179a2d252a5bcf1fc277186a to your computer and use it in GitHub Desktop.
Client Credentials Flow with Refit
using Refit;
namespace Devsym.License;
[Headers("Authorization: Bearer")]
public interface ILicenseAPI
{
[Get("/licenses/{customerId}")]
Task<LicenseResponse> GetLicense(string customerId);
}
using Microsoft.Extensions.Options;
using Microsoft.Identity.Client;
namespace Devsym.License;
public class LicenseAuthProvider
{
private readonly LicenseOptions _options;
private readonly IConfidentialClientApplication _app;
public LicenseAuthProvider(IOptions<LicenseOptions> options)
{
_options = options.Value;
//X509Certificate2 certificate = new(_options.CertificatePath);
_app = ConfidentialClientApplicationBuilder.Create(_options.ClientId)
//.WithCertificate(certificate)
.WithClientSecret(_options.ClientSecret)
.Build();
}
public async Task<string> GetToken(CancellationToken ct)
{
AuthenticationResult authResult = await _app.AcquireTokenForClient(scopes: [_options.Scope])
.WithTenantId(_options.TenantId)
.ExecuteAsync(ct);
return authResult.AccessToken;
}
namespace Devsym.License;
public class LicenseOptions
{
public const string License = "License";
public required string Endpoint { get; set; }
public required string ClientId { get; set; }
public required string ClientSecret { get; set; }
public required string TenantId { get; set; }
public required string Scope { get; set; }
public required string CertificatePath { get; set; }
}
// get license options, create LicenseAuthProvider and configure Refit
IOptions<LicenseOptions> licenseOptions = Options.Create<LicenseOptions>();
LicenseAuthProvider licenseAuthProvider = new(licenseOptions);
RefitSettings refitSettings = new()
{
AuthorizationHeaderValueGetter = (message, cancellationToken) => licenseAuthProvider.GetToken(cancellationToken)
};
builder.Services.AddRefitClient<ILicenseAPI>(refitSettings)
.ConfigureHttpClient(c => c.BaseAddress = new Uri(licenseOptions.Endpoint));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment