๐Ÿ” JWT Authentication in ASP.NET Core โ€“ Step-by-Step Beginner Guide

๐Ÿ“Œ Introduction

Security is one of the most important parts of modern web applications.
When building APIs using ASP.NET Core, we need a secure way to authenticate users.

One of the most popular methods is:

โœ… JWT (JSON Web Token) Authentication

In this article, you will learn:

  • What is JWT?

  • Why we use JWT?

  • How JWT works

  • Step-by-step implementation in ASP.NET Core

  • How to test using Postman

  • Output example

This guide is written in simple language for beginners.

๐Ÿง  What is JWT?

JWT stands for:

JWT (JSON Web Token)

It is a secure way to transmit information between client and server as a JSON object.

JWT contains 3 parts:

Header.Payload.Signature

Example Token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

๐ŸŽฏ Why Use JWT?

  • โœ” Stateless authentication

  • โœ” Secure API access

  • โœ” Used in modern web & mobile apps

  • โœ” No need to store session on server

  • โœ” Fast and scalable

๐Ÿ›  Step 1 โ€“ Create ASP.NET Core Web API Project

  • Open Visual Studio

  • Click Create New Project

  • Select ASP.NET Core Web API

  • Choose .NET 8

Project Name:

JWTAuthDemo

Click Create.

๐Ÿ“ฆ Step 2 โ€“ Install Required Package

Open NuGet Package Manager and install:

Microsoft.AspNetCore.Authentication.JwtBearer

โš™ Step 3 โ€“ Add JWT Settings in appsettings.json

Open:

appsettings.json

Add:

"Jwt": {
  "Key": "ThisIsMySecretKey123456",
  "Issuer": "JWTAuthDemo",
  "Audience": "JWTAuthDemoUsers"
}

๐Ÿ”ง Step 4 โ€“ Configure JWT in Program.cs

Open Program.cs and add:

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 =>
{
    var key = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]);
    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(key)
    };
});

builder.Services.AddControllers();
builder.Services.AddAuthorization();

var app = builder.Build();

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

app.MapControllers();

app.Run();

๐Ÿ‘ค Step 5 โ€“ Create Login Model

Create a folder named Models โ†’ Add class:

public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

๐ŸŽฎ Step 6 โ€“ Create Auth Controller

Create new controller:

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

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

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

    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel model)
    {
        if (model.Username == "admin" && model.Password == "123")
        {
            var token = GenerateToken(model.Username);
            return Ok(new { token });
        }

        return Unauthorized();
    }

    private 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(30),
            signingCredentials: creds);

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

๐Ÿ”’ Step 7 โ€“ Protect API with [Authorize]

Create a new controller:

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

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    [Authorize]
    [HttpGet]
    public IActionResult Get()
    {
        return Ok("Access Granted - Secure API");
    }
}

๐Ÿงช Step 8 โ€“ Test Using Postman

๐Ÿ”น 1. Login API

POST:

https://localhost:port/api/auth/login

Body (JSON):

{
  "username": "admin",
  "password": "123"
}

โœ… Output:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

๐Ÿ”น 2. Access Secure API

GET:

https://localhost:port/api/test

Add Header:

Authorization: Bearer YOUR_TOKEN_HERE

โœ… Output:

Access Granted - Secure API

๐Ÿ” How JWT Works

  • User logs in

  • Server verifies credentials

  • Server generates JWT token

  • Client stores token

  • Client sends token in Authorization header

  • Server validates token

  • Access granted

๐Ÿ Conclusion

In this article, we learned:

  • โœ” What JWT is

  • โœ” Why JWT is important

  • โœ” How to configure JWT in ASP.NET Core

  • โœ” How to generate token

  • โœ” How to protect APIs

JWT Authentication is widely used in modern web development and is an important concept for interviews and real-world applications.