added credentials in header support

This commit is contained in:
DavidGudEnough 2025-03-17 09:46:54 -04:00
parent 20518b8f6a
commit 3bdd97ceac
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 ClientId { get; set; }
public required string ClientSecret { get; set; } public required string ClientSecret { get; set; }
public IEnumerable<string> Scopes { get; set; } = Array.Empty<string>(); 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.Headers;
using System.Net.Http.Json; using System.Net.Http.Json;
using System.Text;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using OpenHarbor.JwtTokenManager.Abstractions; using OpenHarbor.JwtTokenManager.Abstractions;
@ -23,19 +24,33 @@ public class JwtTokenManagerService(JwtTokenManagerOptions options, IHttpClientF
return cachedToken; return cachedToken;
} }
} }
var formContent = new FormUrlEncodedContent([ var formContentKeyValues = new List<KeyValuePair<string, string>>()
new KeyValuePair<string, string>("grant_type", "client_credentials"), {
new KeyValuePair<string, string>("client_id", options.ClientId), new ("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_secret", options.ClientSecret), new ("scopes", string.Join(" ", _scopes))
new KeyValuePair<string, string>("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) var request = new HttpRequestMessage(HttpMethod.Post, options.TokenEndpoint)
{ {
Content = formContent 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")); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.SendAsync(request, cancellationToken); var response = await _httpClient.SendAsync(request, cancellationToken);