added credentials in header support
All checks were successful
Publish NuGets / build (release) Successful in 25s

This commit is contained in:
DavidGudEnough 2025-03-17 09:46:54 -04:00
parent 20518b8f6a
commit 61f7c0f05e
Signed by: david.nguyen
GPG Key ID: 0B95DC36355BEB37
2 changed files with 23 additions and 7 deletions

View File

@ -6,5 +6,6 @@ public class JwtTokenManagerOptions
public required string ClientId { get; set; }
public required string ClientSecret { get; set; }
public IEnumerable<string> Scopes { get; set; } = Array.Empty<string>();
public bool IsCredentialsInHeader { get; set; } = false;
}

View File

@ -1,5 +1,6 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using OpenHarbor.JwtTokenManager.Abstractions;
@ -23,19 +24,33 @@ public class JwtTokenManagerService(JwtTokenManagerOptions options, IHttpClientF
return cachedToken;
}
}
var formContent = new FormUrlEncodedContent([
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", options.ClientId),
new KeyValuePair<string, string>("client_secret", options.ClientSecret),
new KeyValuePair<string, string>("scopes", string.Join(" ", _scopes))
]);
var formContentKeyValues = new List<KeyValuePair<string, string>>()
{
new ("grant_type", "client_credentials"),
new ("scopes", string.Join(" ", _scopes))
};
if (options.IsCredentialsInHeader)
{
formContentKeyValues.AddRange([
new KeyValuePair<string, string>("client_id", options.ClientId),
new KeyValuePair<string, string>("client_secret", options.ClientSecret)
]);
}
var formContent = new FormUrlEncodedContent(formContentKeyValues);
var request = new HttpRequestMessage(HttpMethod.Post, options.TokenEndpoint)
{
Content = formContent
};
if (false == options.IsCredentialsInHeader)
{
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{options.ClientId}:{options.ClientSecret}"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials);
}
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.SendAsync(request, cancellationToken);