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

  • โœ… Stateless (No session needed)

  • โœ… Secure

  • โœ… Fast

  • โœ… Used in Mobile + Web APIs

  • โœ… Industry standard

๐Ÿ—๏ธ Step 1: Create Web API Project

Bash
dotnet new webapi -n JwtAuthDemo

๐Ÿ“ฆ Step 2: Install Required Package

Bash
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

โš™๏ธ Step 3: Configure JWT in Program.cs

C#
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

C#
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)

C#
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

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

๐Ÿ“ก How to Use in Postman

  • Call /login โ†’ get token

  • Copy token

  • Go to Headers

  • Add:

Code
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