📌 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:

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?

🛠 Step 1 – Create ASP.NET Core Web API Project

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

🏁 Conclusion

In this article, we learned:

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