How to implement JWT Authentication in ASP.NET Core
Today we will discuss about how securing API endpoints is one of the most critical phases of building a modern backend application. In this guide, we will break down exactly how JWT (JSON Web Token) authentication works, map out its core components — the header, payload, and signature — and walk through a seamless implementation in ASP.NET Core to safeguard your web APIs.
JWT Web Token Components
- Header
- Payload
- Signature
Step 1: Install the Required Package
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer — version 10.0.0
Get Mustafa Sirki’s stories in your inbox
Join Medium for free to get updates from this writer.
Step 2: Configure JWT settings in appsettings.json
{
"Jwt": {
"Key": "MySuperSecretBackUpKeyThatIsLongEnough123!",
"Issuer": "https://localhost:7001",
"Audience": "https://localhost:7001"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}Step 3: Register Service in Program.cs
// 1. Get JWT settings from configuration
var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]!);
// 2. 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 = jwtSettings["Issuer"],
ValidAudience = jwtSettings["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
// 3. Enable Authentication and Authorization Middleware
app.UseAuthentication(); // Add UseAuthentication before UseAuthorization
app.UseAuthorization();Step 4: Create an Auth Controller to Generate Tokens
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginModel request)
{
var user = _context.Users.SingleOrDefault(u =>
u.Username == request.Username &&
u.Password == request.Password);
if (user == null)
{
return Unauthorized(new { message = "Invalid username or password" });
}
var token = await GenerateJwtTokenAsync(user);
return Ok(new { token });
}
private async Task<string> GenerateJwtTokenAsync(LoginModel user)
{
var jwtSettings = _configuration.GetSection("Jwt");
var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]!);
var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
// Define claims (user context metadata included inside the encrypted token)
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Role, "Admin") // Optional role mapping
};
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
}5. Secure Controllers
By using [Authorize] attribute we can protect our API endpoints.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Authorize]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
[HttpGet]
public IActionResult GetData()
{
return Ok(new { Message = "Getting secured data." });
}
}Step 6: Test an API endpoint
While using API client (like Postman or curl) add an Authorization header formatted as:
• Key: Authorization
• Value: Bearer <token value>
Summary
We go through the concepts of Authentication and Authorization, and implemented a basic JWT-based authentication using ASP.NET Core Web API.






