.NET Development

JWT Authentication in ASP.NET Core: A Complete Guide

Abid Inamdar February 04, 2026 8 min read 446 views

How JWT Works

A JWT is a signed, base64-encoded JSON payload. The server signs it with a secret key. Clients send it in the Authorization: Bearer header on every request.

Security lock on digital background
Security lock on digital background

Token Generation

var claims = new[]
{
    new Claim(ClaimTypes.NameIdentifier, user.Id),
    new Claim(ClaimTypes.Email, user.Email!),
    new Claim(ClaimTypes.Role, "Admin")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
var token = new JwtSecurityToken(
    issuer: "myapp", audience: "myapp",
    claims: claims, expires: DateTime.UtcNow.AddHours(1),
    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

Validation Setup

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o => o.TokenValidationParameters = new()
    {
        ValidateIssuer = true, ValidIssuer = "myapp",
        ValidateAudience = true, ValidAudience = "myapp",
        ValidateLifetime = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
    });
⚠️

Use a JWT key of at least 256 bits (32 characters). Short keys are vulnerable to brute-force attacks. Store it in environment variables, never in appsettings.json.

Role-Based Authorization

[Authorize(Roles = "Admin,Editor")]
[HttpPost("posts")]
public async Task<IActionResult> CreatePost([FromBody] CreatePostDto dto) { ... }
Share: Twitter/X LinkedIn

Related Posts

Comments (0)

Leave a Comment
Comments are moderated.