Authentication & Authorization with JWT
🔒 Adding Authentication & Authorization with JWT
Security is essential. ASP.NET Core makes it straightforward to secure your APIs using JWT (JSON Web Tokens).
🔐 JWT Flow Overview
Client --> /login --> [Token Issued] --> Client Stores Token
Client --> /api/products --> [Authorization: Bearer
🛠️ Configure JWT Authentication
In Program.cs
:
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourdomain.com",
ValidAudience = "yourdomain.com",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("supersecretkey123"))
};
});
app.UseAuthentication();
Decorate endpoints with `[Authorize]` and expose public ones with `[AllowAnonymous]`.