Creating a JWT (JSON Web Token) in a .NET Core Web API often entails utilizing the System.Utilisation of the IdentityModel.Tokens.Jwt NuGet package and the configuration of requisite services and settings.
Nuget Package
Microsoft.AspNetCore.Authentication.JwtBearer
Configuration
configure JWT generating options such secret key, issuer, audience, and expiration time in appsettings.json or appsettings.Development.json.
// appsettings.json
{
"Jwt": {
"Key": "CecretKeyHere", // Replace with a strong, unique key
"Issuer": "yourdomain.com", // The entity that issues the token (your API).
"Audience": "yourclientapp.com", // The entity that will consume the token (your client application).
"ExpirationInMinutes": 60 // How long the token will be valid.
}
}
Register Services in Program.cs (or Startup.cs for earlier.NET versions):
- Get JWT set up Bearer authentication allows you to define the criteria for validating incoming JWTs.
- If you want authorization based on roles or claims, you can add authorization policies as an optional component.
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Configure JWT authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
};
});
// Add authorization policies (optional)
builder.Services.AddAuthorization();var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}app.UseHttpsRedirection();
app.UseAuthentication(); // Enable authentication middleware
app.UseAuthorization(); // Enable authorization middlewareapp.MapControllers();
app.Run();