WebApiTools.Authentication.Bearer
1.1.2
See the version list below for details.
dotnet add package WebApiTools.Authentication.Bearer --version 1.1.2
NuGet\Install-Package WebApiTools.Authentication.Bearer -Version 1.1.2
<PackageReference Include="WebApiTools.Authentication.Bearer" Version="1.1.2" />
<PackageVersion Include="WebApiTools.Authentication.Bearer" Version="1.1.2" />
<PackageReference Include="WebApiTools.Authentication.Bearer" />
paket add WebApiTools.Authentication.Bearer --version 1.1.2
#r "nuget: WebApiTools.Authentication.Bearer, 1.1.2"
#:package WebApiTools.Authentication.Bearer@1.1.2
#addin nuget:?package=WebApiTools.Authentication.Bearer&version=1.1.2
#tool nuget:?package=WebApiTools.Authentication.Bearer&version=1.1.2
WebApiTools.Authentication.Bearer
This library provides extensions to easily configure JWT Bearer Authentication in your ASP.NET Core applications.
Installation
dotnet add package WebApiTools.Authentication.Bearer
1. Quick Setup (Simplest)
If your configuration file contains a JwtOptions section, you can add authentication in one line:
var builder = WebApplication.CreateBuilder(args);
builder.AddJwtAuthentication();
var app = builder.Build();
app.UseCors();
app.UseJwtAuthentication();
app.UseHttpsRedirection();
2. Using Configuration Section Explicitly
If you want to be explicit about where the configuration comes from:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddJwtAuthentication(builder.Configuration);
var app = builder.Build();
app.UseCors();
app.UseJwtAuthentication();
app.UseHttpsRedirection();
3. Full Customization (Manual Options Binding)
If you prefer to configure JwtOptions programmatically:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddJwtAuthentication(options =>
{
options.Issuer = "MyIssuer";
options.Audience = "MyAudience";
options.SecretKey = "SuperSecretKey123456";
options.ExpirationInDays = 7;
options.ValidateIssuer = true;
options.ValidateAudience = true;
options.ValidateLifetime = true;
options.ValidateIssuerSigningKey = true;
});
var app = builder.Build();
app.UseCors();
app.UseJwtAuthentication();
app.UseHttpsRedirection();
4. Advanced Usage with Custom Events
You can now handle JWT Bearer events for advanced scenarios:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddJwtAuthentication(options =>
{
options.Issuer = "MyIssuer";
options.Audience = "MyAudience";
options.SecretKey = "SuperSecretKey123456";
options.ExpirationInDays = 7;
}, new JwtEvents // all are optionals, so only one can be used
{
OnMessageReceived = async (context) =>
{
// Custom token extraction logic
var token = context.Request.Headers["X-Custom-Token"].FirstOrDefault();
if (!string.IsNullOrEmpty(token))
{
context.Token = token;
}
await Task.CompletedTask;
},
OnAuthenticationFailed = async (context) =>
{
// Custom error handling
Console.WriteLine($"Authentication failed: {context.Exception.Message}");
await Task.CompletedTask;
},
OnTokenValidated = async (context) =>
{
// Add custom claims or validation
var claimsIdentity = context.Principal.Identity as ClaimsIdentity;
claimsIdentity?.AddClaim(new Claim("CustomClaim", "CustomValue"));
await Task.CompletedTask;
},
OnChallenge = async (context) =>
{
// Custom challenge response
context.Response.Headers.Append("X-Custom-Challenge", "Bearer error=\"invalid_token\"");
await Task.CompletedTask;
},
OnForbidden = async (context) =>
{
// Custom forbidden response
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Custom forbidden message");
await Task.CompletedTask;
}
});
var app = builder.Build();
app.UseCors();
app.UseJwtAuthentication();
app.UseHttpsRedirection();
JwtOptions Configuration
JwtOptions allows you to configure:
- Issuer: The expected token issuer.
- Audience: The expected token audience.
- SecretKey: The symmetric security key used for signing tokens.
- ExpirationInDays: Default token expiration.
- ValidateIssuer: Whether to validate the issuer.
- ValidateAudience: Whether to validate the audience.
- ValidateLifetime: Whether to check token expiration.
- ValidateIssuerSigningKey: Whether to validate the signing key.
JwtEvents Configuration
JwtEvents allows you to handle JWT Bearer authentication events:
- OnMessageReceived: Invoked when a token has been received.
- OnAuthenticationFailed: Invoked if authentication fails.
- OnTokenValidated: Invoked after the token has been validated.
- OnChallenge: Invoked before a challenge is sent.
- OnForbidden: Invoked if authorization fails and results in a forbidden response.
Available Extension Methods
// From IConfiguration
builder.Services.AddJwtAuthentication(IConfiguration configuration);
// With manual options configuration
builder.Services.AddJwtAuthentication(Action<JwtOptions> configuration);
// With custom events
builder.Services.AddJwtAuthentication(Action<JwtOptions> configuration, JwtEvents events);
Best Practices
- Always store
SecretKeysecurely (use environment variables or secrets manager). - Place
app.UseJwtAuthentication(); before mapping endpoints. - Use the simplest overload unless you need advanced customization.
- For production, use strong secret keys and consider key rotation.
- Use custom events for logging, custom token validation, or specialized error handling.
Example appsettings.json
{
"JwtOptions": {
"Issuer": "MyApp",
"Audience": "MyAppUsers",
"SecretKey": "YourSuperSecretKeyHereAtLeast32CharactersLong",
"ExpirationInDays": 7,
"ValidateIssuer": true,
"ValidateAudience": true,
"ValidateLifetime": true,
"ValidateIssuerSigningKey": true
}
}
Dependencies
- Microsoft.AspNetCore.Authentication.JwtBearer
- Microsoft.IdentityModel.Tokens
- System.IdentityModel.Tokens.Jwt
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.0)
-
net9.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 9.0.11)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Add JwtEvents class and use in extension to personalize authorization events.