ASP.NET Core  

How to Implement JWT Authentication in ASP.NET Core Step by Step

Introduction

JWT (JSON Web Token) authentication is one of the most popular and secure ways to protect APIs in ASP.NET Core. It allows you to build scalable, stateless authentication systems where the server does not need to store session data.

In this guide, you will learn how to implement JWT authentication in ASP.NET Core step by step using simple language, real examples, and best practices. This article is useful for beginners as well as developers building secure web APIs.

What is JWT Authentication?

JWT (JSON Web Token) is a compact, URL-safe token that is used to securely transmit information between client and server.

A JWT token contains three parts:

  • Header → Contains algorithm and token type

  • Payload → Contains user data (claims)

  • Signature → Used to verify the token

Example structure:

Header.Payload.Signature

JWT is widely used in ASP.NET Core Web API authentication because:

  • It is stateless (no server storage required)

  • It is secure (signed tokens)

  • It works well with mobile and SPA applications

Prerequisites

Before implementing JWT authentication in ASP.NET Core, make sure you have:

  • .NET SDK installed

  • Basic knowledge of ASP.NET Core Web API

  • Visual Studio or VS Code

Step 1: Create ASP.NET Core Web API Project

Create a new ASP.NET Core Web API project using CLI:

dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo

Or use Visual Studio:

  • Select "ASP.NET Core Web API"

  • Choose .NET version

  • Create project

Step 2: Install Required NuGet Packages

Install JWT authentication package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

This package helps validate and handle JWT tokens.

Step 3: Add JWT Settings in appsettings.json

Add configuration for JWT:

"Jwt": {
  "Key": "ThisIsASecretKeyForJwtToken12345",
  "Issuer": "YourApp",
  "Audience": "YourAppUsers",
  "DurationInMinutes": 60
}

Explanation:

  • Key → Secret key used for signing token

  • Issuer → Who generates token

  • Audience → Who uses token

  • Duration → Token expiry time

Step 4: Create JWT Service

Create a service to generate tokens.

Create folder: Services

Create file: JwtService.cs

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

public class JwtService
{
    private readonly IConfiguration _config;

    public JwtService(IConfiguration config)
    {
        _config = config;
    }

    public string GenerateToken(string username)
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, username)
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: _config["Jwt:Issuer"],
            audience: _config["Jwt:Audience"],
            claims: claims,
            expires: DateTime.Now.AddMinutes(Convert.ToDouble(_config["Jwt:DurationInMinutes"])),
            signingCredentials: creds
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

Step 5: Configure JWT Authentication in Program.cs

Add authentication middleware.

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

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 = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

builder.Services.AddAuthorization();
builder.Services.AddScoped<JwtService>();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

Step 6: Create Login API to Generate Token

Create a controller: AuthController.cs

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly JwtService _jwtService;

    public AuthController(JwtService jwtService)
    {
        _jwtService = jwtService;
    }

    [HttpPost("login")]
    public IActionResult Login(string username, string password)
    {
        if (username == "admin" && password == "password")
        {
            var token = _jwtService.GenerateToken(username);
            return Ok(new { Token = token });
        }

        return Unauthorized();
    }
}

Step 7: Protect API Using [Authorize]

Create a secure controller.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class SecureController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public IActionResult GetData()
    {
        return Ok("This is a protected API");
    }
}

Step 8: Test JWT Authentication

  1. Call login API:

POST /api/auth/login

Body:

{
  "username": "admin",
  "password": "password"
}
  1. Copy the token from response

  2. Call protected API with header:

Authorization: Bearer YOUR_TOKEN

If token is valid, API will return data.

How JWT Authentication Works (Flow)

  • User sends login request

  • Server validates credentials

  • Server generates JWT token

  • Client stores token (localStorage or secure storage)

  • Client sends token with each request

  • Server validates token

  • Access is granted or denied

Best Practices for JWT in ASP.NET Core

  • Use strong secret keys

  • Keep token expiry short

  • Use HTTPS always

  • Store tokens securely (avoid localStorage for sensitive apps)

  • Use refresh tokens for long sessions

Common Mistakes to Avoid

  • Hardcoding secret keys in code

  • Not validating token properly

  • Long expiry tokens

  • Missing HTTPS

When to Use JWT Authentication

JWT is best for:

  • Web APIs

  • Mobile applications

  • Microservices architecture

  • Single Page Applications (SPA)

Summary

JWT authentication in ASP.NET Core is a powerful and scalable way to secure APIs. By following a step-by-step approach—creating a token service, configuring authentication middleware, and protecting endpoints—you can build secure applications easily. Always follow best practices like secure key management, short expiry, and HTTPS to ensure your application remains safe and reliable.