Compare commits

..

No commits in common. "main" and "8.1.1" have entirely different histories.
main ... 8.1.1

9 changed files with 25 additions and 78 deletions

View File

@ -35,4 +35,4 @@ jobs:
- name: Publish to NuGet.org
run: |
dotnet nuget push ./artifacts/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push ./artifacts/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}

View File

@ -2,28 +2,14 @@
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<IsAotCompatible>true</IsAotCompatible>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Authors>Mathias Beaulieu-Duncan</Authors>
<Company>Open Harbor</Company>
<PackageIcon>icon.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageIconUrl>https://gravatar.com/avatar/9cecda5822fc5d4d2e61ec03da571b3d?size=256</PackageIconUrl>
<RepositoryUrl>https://git.openharbor.io/Open-Harbor/dotnet-jwt-token-manager</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<DebugType>portable</DebugType>
<DebugSymbols>true</DebugSymbols>
<IncludeSymbols>true</IncludeSymbols>
<IncludeSource>true</IncludeSource>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup>
<None Include="..\icon.png" Pack="true" PackagePath="" CopyToOutputDirectory="Always" />
<None Include="..\README.md" Pack="true" PackagePath="" CopyToOutputDirectory="Always" />
</ItemGroup>
</Project>

View File

@ -1,12 +0,0 @@
using System.Text.Json.Serialization;
namespace OpenHarbor.JwtTokenManager;
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower,
PropertyNameCaseInsensitive = true
)]
[JsonSerializable(typeof(JwtTokenResponse))]
public partial class JwtTokenManagerJsonContext : JsonSerializerContext
{
}

View File

@ -6,6 +6,5 @@ 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,6 +1,6 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using OpenHarbor.JwtTokenManager.Abstractions;
@ -14,6 +14,12 @@ public class JwtTokenManagerService(JwtTokenManagerOptions options, IHttpClientF
private readonly TimeSpan _cacheExpirationOffset = TimeSpan.FromSeconds(cacheOptions.ExpirationOffset);
private readonly string _scopes = string.Join(" ", options.Scopes);
private static readonly JsonSerializerOptions SnakeCaseOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
PropertyNameCaseInsensitive = true
};
public async Task<JwtTokenManagerResult> GetTokenAsync(CancellationToken cancellationToken = default)
{
if (memoryCache != null)
@ -24,41 +30,26 @@ public class JwtTokenManagerService(JwtTokenManagerOptions options, IHttpClientF
return cachedToken;
}
}
var formContentKeyValues = new List<KeyValuePair<string, string>>()
{
new ("grant_type", "client_credentials"),
new ("scopes", string.Join(" ", _scopes))
};
if (false == 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 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 request = new HttpRequestMessage(HttpMethod.Post, options.TokenEndpoint)
{
Content = formContent
};
if (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);
response.EnsureSuccessStatusCode();
var tokenResponse = await response.Content.ReadFromJsonAsync(JwtTokenManagerJsonContext.Default.JwtTokenResponse, cancellationToken);
var tokenResponse = await response.Content.ReadFromJsonAsync<JwtTokenResponse>(SnakeCaseOptions, cancellationToken);
if (tokenResponse == null)
{

View File

@ -2,32 +2,16 @@
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<IsAotCompatible>true</IsAotCompatible>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Authors>Mathias Beaulieu-Duncan</Authors>
<Company>Open Harbor</Company>
<PackageIcon>icon.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageIconUrl>https://gravatar.com/avatar/9cecda5822fc5d4d2e61ec03da571b3d?size=256</PackageIconUrl>
<RepositoryUrl>https://git.openharbor.io/Open-Harbor/dotnet-jwt-token-manager</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<DebugType>portable</DebugType>
<DebugSymbols>true</DebugSymbols>
<IncludeSymbols>true</IncludeSymbols>
<IncludeSource>true</IncludeSource>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<EnableJsonSourceGeneration>true</EnableJsonSourceGeneration>
</PropertyGroup>
<ItemGroup>
<None Include="..\icon.png" Pack="true" PackagePath="" CopyToOutputDirectory="Always" />
<None Include="..\README.md" Pack="true" PackagePath="" CopyToOutputDirectory="Always" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />

View File

@ -1,4 +1,3 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@ -10,7 +9,6 @@ namespace OpenHarbor.JwtTokenManager;
public static class ServiceCollectionExtensions
{
[RequiresDynamicCode("Not AoT safe signature. Will add one in the future.")]
public static IServiceCollection AddJwtTokenManager(
this IServiceCollection services,
IConfiguration configuration,
@ -21,7 +19,8 @@ public static class ServiceCollectionExtensions
throw new ArgumentNullException(nameof(configuration));
if (string.IsNullOrWhiteSpace(sectionName))
throw new ArgumentException("Section name must be provided.", nameof(sectionName));
// Configure JwtTokenManagerOptions from the section
services.Configure<JwtTokenManagerOptions>(configuration.GetSection(sectionName));
// Apply the builder options
@ -31,7 +30,7 @@ public static class ServiceCollectionExtensions
// Register the service
services.AddSingleton<IJwtTokenManagerService>(provider =>
{
var optionsMonitor = provider.GetRequiredService<IOptionsMonitor<JwtTokenManagerOptions>>();
var optionsMonitor = provider.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<JwtTokenManagerOptions>>();
var options = optionsMonitor.Get(Options.DefaultName);
// Apply additional configuration

BIN
icon.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

View File

@ -4,10 +4,10 @@
> Install nuget package to your awesome project.
| Package Name | NuGet | NuGet Install |
|-----------------------------------------| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |----------------------------------------------------------------------------:|
| OpenHarbor.JwtTokenManager | [![NuGet](https://img.shields.io/nuget/v/OpenHarbor.JwtTokenManager.svg?style=flat-square&label=nuget)](https://www.nuget.org/packages/OpenHarbor.JwtTokenManager/) | ```PM> Install-Package OpenHarbor.JwtTokenManager``` |
| OpenHarbor.JwtTokenManager.Abstractions | [![NuGet](https://img.shields.io/nuget/v/OpenHarbor.JwtTokenManager.Abstractions.svg?style=flat-square&label=nuget)](https://www.nuget.org/packages/OpenHarbor.JwtTokenManager.Abstractions/) | ```PM> Install-Package OpenHarbor.JwtTokenManager.Abstractions``` |
| Full Version | NuGet | NuGet Install |
|-----------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |----------------------------------------------------------------------------:|
| OpenHarbor.JwtTokenManager | <a href="https://www.nuget.org/packages/OpenHarbor.JwtTokenManager" target="_blank">[![NuGet](https://img.shields.io/nuget/v/OpenHarbor.JwtTokenManager.svg?style=flat-square&label=nuget)](https://www.nuget.org/packages/OpenHarbor.JwtTokenManager/)</a> | ```PM> Install-Package OpenHarbor.JwtTokenManager``` |
| OpenHarbor.JwtTokenManager.Abstractions | <a href="https://www.nuget.org/packages/OpenHarbor.JwtTokenManager.Abstractions" target="_blank">[![NuGet](https://img.shields.io/nuget/v/OpenHarbor.JwtTokenManager.Abstractions.svg?style=flat-square&label=nuget)](https://www.nuget.org/packages/OpenHarbor.JwtTokenManager.Abstractions/)</a> | ```PM> Install-Package OpenHarbor.JwtTokenManager.Abstractions``` |
# How to use