RA.Utilities.Authentication.JwtBearer
This library provides extension methods to streamline the setup of JWT Bearer authentication by leveraging the standard IConfiguration system.
It allows you to configure JwtBearerOptions directly from your appsettings.json file, reducing boilerplate code in your Program.cs or Startup.cs.
✨ The main benefits are:
- Simplified Setup: A single extension method call to configure JWT Bearer authentication.
- Configuration-driven: Easily manage JWT validation parameters through
appsettings.jsonwithout changing code. - Customizable: Supports custom configuration for
ClockSkewand theIssuerSigningKey.
🛠️ Installation
dotnet add package RA.Utilities.Authentication.JwtBearer
Or through the NuGet Package Manager console:
Install-Package RA.Utilities.Authentication.JwtBearer
Or through the NuGet Package Manager in Visual Studio.
🔗 Dependencies
🚀 Usage
In your Program.cs (for minimal APIs) or Startup.cs, use the AddJwtBearerAuthentication extension method to configure authentication and authorization services.
Program.cs (ASP.NET Core 6+)
using RA.Utilities.Authentication.JwtBearer.Extensions;
var builder = WebApplication.CreateBuilder(args);
// 1. Add and configure JWT Bearer authentication using settings from IConfiguration.
// This single call also adds the necessary authorization services.
builder.Services.AddJwtBearerAuthentication(builder.Configuration);
var app = builder.Build();
// 2. Add the authentication and authorization middleware.
app.UseAuth(); // This is a convenience method for app.UseAuthentication() and app.UseAuthorization().
app.MapGet("/", () => "Hello World!");
app.Run();
🛠️ Configuration
This library reads JWT Bearer options from the Authentication:Schemes:Bearer section of your configuration file (e.g., appsettings.json).
Here is an example appsettings.json configuration:
{
"Authentication": {
"Schemes": {
"Bearer": {
"Authority": "https://your-identity-provider.com/",
"Audience": "your-api-audience",
"TokenValidationParameters": {
"ValidateIssuer": true,
"ValidateAudience": true,
"ValidateLifetime": true,
"ValidateIssuerSigningKey": true,
"ClockSkewInSeconds": 30,
"IssuerSigningKeyString": "your-super-secret-key-that-is-long-enough-for-the-algorithm"
}
}
}
}
}
When using an identity provider (Authority), you typically don't need to specify ValidIssuer, ValidAudience, or IssuerSigningKey as these are discovered from the metadata endpoint.
The example above shows settings for both scenarios (using an authority or validating a self-issued token).
The library automatically binds these settings to JwtBearerOptions.
It also provides special handling for:
ClockSkewInSeconds: Converts this integer value into aTimeSpanforTokenValidationParameters.ClockSkew.IssuerSigningKeyString: Converts this string into aSymmetricSecurityKeyforTokenValidationParameters.IssuerSigningKey.