ASP.NET Core  

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

Introduction

JWT authentication in ASP.NET Core 8 is a widely used approach for securing REST APIs and modern web applications. In enterprise backend systems, SaaS platforms, fintech applications, and cloud-native microservices, JSON Web Tokens (JWT) provide stateless, scalable, and secure authentication. ASP.NET Core 8 offers built-in middleware support that makes implementing JWT authentication clean and production-ready.

In this step-by-step guide, we will implement JWT authentication in ASP.NET Core 8, covering project setup, token generation, authentication configuration, authorization policies, and best practices for production environments.

Step 1: Create a New ASP.NET Core 8 Web API Project

First, create a new ASP.NET Core 8 Web API project using the .NET CLI:

dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo

This creates a production-ready Web API template with minimal configuration.

Remove default weather controller if not required and keep the project clean for authentication implementation.

Step 2: Install Required JWT NuGet Packages

To enable JWT authentication in ASP.NET Core 8, install the following package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

This package provides middleware for validating JWT tokens in ASP.NET Core applications.

Step 3: Configure JWT Settings in appsettings.json

Add JWT configuration values inside appsettings.json:

"Jwt": {
  "Key": "ThisIsASecureKeyForJwtAuthentication",
  "Issuer": "YourAppIssuer",
  "Audience": "YourAppAudience",
  "DurationInMinutes": 60
}

In production environments, never store secrets directly in appsettings.json. Use environment variables or secure secret management tools.

Step 4: Configure JWT Authentication in Program.cs

Open Program.cs and configure JWT authentication middleware.

Add required namespaces:

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

Configure authentication services:

var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]);

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 = jwtSettings["Issuer"],
        ValidAudience = jwtSettings["Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(key)
    };
});

builder.Services.AddAuthorization();

Then enable middleware:

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

This ensures all incoming requests are validated before accessing protected endpoints.

Step 5: Create a Token Generation Service

Create a service responsible for generating JWT tokens.

Example implementation:

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

public class JwtService
{
    private readonly IConfiguration _configuration;

    public JwtService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public string GenerateToken(string username)
    {
        var jwtSettings = _configuration.GetSection("Jwt");
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Key"]));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

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

        var token = new JwtSecurityToken(
            issuer: jwtSettings["Issuer"],
            audience: jwtSettings["Audience"],
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(jwtSettings["DurationInMinutes"])),
            signingCredentials: credentials);

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

Register the service in Program.cs:

builder.Services.AddScoped<JwtService>();

Step 6: Create an Authentication Controller

Create a controller to authenticate users and return JWT tokens.

Example:

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

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

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

        return Unauthorized();
    }
}

In real-world enterprise applications, validate credentials against a database instead of hardcoding.

Step 7: Protect API Endpoints Using Authorize Attribute

Add the [Authorize] attribute to protect controllers or specific endpoints:

[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
    return Ok("This is protected data.");
}

Only requests with valid JWT tokens in the Authorization header will access this endpoint.

Authorization header format:

Authorization: Bearer {your_token}

Step 8: Implement Role-Based Authorization (Optional)

For production-ready ASP.NET Core applications, implement role-based authorization.

Add role claims during token generation and apply role-based policies:

[Authorize(Roles = "Admin")]

Role-based access control improves security in enterprise backend APIs.

Production Best Practices for JWT in ASP.NET Core 8

To secure high-traffic production APIs:

  • Use strong secret keys

  • Store secrets securely using environment variables or Azure Key Vault

  • Set short expiration times

  • Implement refresh tokens

  • Enable HTTPS enforcement

  • Log authentication failures

Security and scalability are critical in cloud-native ASP.NET Core backend systems.

Summary

Implementing JWT authentication in ASP.NET Core 8 involves configuring authentication middleware, defining secure token validation parameters, generating JWT tokens with appropriate claims, protecting endpoints using authorization attributes, and applying production security best practices. By following a structured step-by-step implementation approach and securing secrets properly, developers can build scalable, stateless, and secure REST APIs suitable for enterprise applications, SaaS platforms, and high-performance cloud deployments.