🔐 JWT Authentication in ASP.NET Core Web API

JWT Authentication in ASP.NET Core

📌 Introduction

Security is one of the most important parts of any application. Today, most modern apps use token-based authentication instead of session-based login.

👉 One of the most popular methods is JWT (JSON Web Token) in ASP.NET Core.

🤔 What is JWT?

JWT (JSON Web Token) is a secure token that is generated after login and used to access protected APIs.

👉 Instead of storing user session on server, JWT stores data in token.

🧠 Simple Flow (Easy Understanding)

  • User Login

  • Server verifies user

  • Server generates JWT token

  • Client stores token

  • Client sends token in every request

  • Server validates token

🔥 Why JWT is Trending?

  • ✅ Stateless (No session needed)

  • ✅ Secure

  • ✅ Fast

  • ✅ Used in Mobile + Web APIs

  • ✅ Industry standard

🏗️ Step 1: Create Web API Project

dotnet new webapi -n JwtAuthDemo

📦 Step 2: Install Required Package

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

⚙️ Step 3: Configure JWT in Program.cs

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

var builder = WebApplication.CreateBuilder(args);

var key = "ThisIsMySecretKey12345";

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
    };
});

builder.Services.AddAuthorization();

var app = builder.Build();

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

app.MapGet("/", () => "JWT API Running");

app.Run();

🔑 Step 4: Create Token Generator

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

public class JwtService
{
    private string key = "ThisIsMySecretKey12345";

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

        var keyBytes = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
        var creds = new SigningCredentials(keyBytes, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds
        );

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

🔐 Step 5: Login API (Generate Token)

app.MapPost("/login", (string username, string password) =>
{
    if (username == "admin" && password == "123")
    {
        var jwt = new JwtService();
        var token = jwt.GenerateToken(username);

        return Results.Ok(token);
    }

    return Results.Unauthorized();
});

🔒 Step 6: Secure API

app.MapGet("/secure", () =>
{
    return "This is protected data";
}).RequireAuthorization();

📡 How to Use in Postman

  • Call /login → get token

  • Copy token

  • Go to Headers

  • Add:

Authorization: Bearer YOUR_TOKEN
  • Call /secure

🧠 Easy Understanding

  • Token = Identity Card 🪪

  • Without token ❌ access denied

  • With token ✅ access allowed

🔗 Real-Life Use Cases

  • Mobile apps login

  • Banking APIs

  • E-commerce systems

  • Microservices authentication

🏁 Conclusion

JWT authentication in ASP.NET Core is:

  • 🔐 Secure

  • ⚡ Fast

  • 🌍 Widely used