In modern web applications, security is critical—especially when dealing with user data, financial transactions, or any form of sensitive operations. JSON Web Tokens (JWT) provide a stateless and scalable solution for authentication, while role-based authorization ensures users can only access what they're permitted to.
In this article, we’ll walk through how to implement JWT-based authentication and role-based authorization in an ASP.NET Core Web API.
🔧 Prerequisites
Before we begin, make sure you have:
-
Basic knowledge of ASP.NET Core and C#
🛠 Step 1. Create a New ASP.NET Core Web API Project
dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo
📦 Step 2. Install Required NuGet Packages
Install the following NuGet package for JWT support:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
🧩 Step 3. Configure JWT Authentication in Program.cs
Add the following JWT configuration to Program.cs:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add Authentication services
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your-app",
ValidAudience = "your-app",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSuperSecretKey123"))
};
});
// Add Authorization
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
app.UseAuthentication(); // Must come before UseAuthorization
app.UseAuthorization();
app.MapControllers();
app.Run();
🛡 Replace "YourSuperSecretKey123" with a secure key and store it in a secure place, such as Azure Key Vault or environment variables.
🔐 Step 4. Generate JWT Tokens
Create a service or endpoint to generate JWT tokens. Example:
Join the conversation! Your thoughts help the community grow.