JWT-Authentication-ASP-NET

How to Secure Your ASP.NET Core 8 Web API with JWT Authentication Token

This post will help you to secure your ASP.NET Core 8 Web API using JWT (JSON Web Token) authentication token. A step-by-step guide to implement token-based security and protect your endpoints in a real-world-ready way.

What is JWT Authentication Token or JSON Web Token?

JWT (pronounced jot) is a compact and self-contained way to represent claims between two parties. It’s widely used for API authentication.

A JWT authentication token:

  • Is a long string (The structure is: header.payload.signature. Each of these parts is Base64url encoded)
  • Gets generated on login
  • Must be sent with each API request to access protected routes

A JWT token looks like:

eyJhbGciOiJIUzI1NiItInR5cCI6IkpXVCJ9

Why Authentication is Needed in APIs

By default, your ASP.NET Core Web API is open to the world. That means anyone can call your endpoints unless you explicitly restrict access.

If you’re building an application with features like user login, admin access, or any private data, you must implement authentication. That’s where JWT comes in.

Now we will learn how to Add JWT Auth in ASP.NET Core 8 Web API

Step 1: Install Required Packages

Open your .NET Project in editor run the command in terminal

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 2: Update appsettings.json

"Jwt": {
"Key": "ThisIsASecretKeyForJWT",
"Issuer": "debugboat.com",
"Audience": "debugboat.com",
"DurationInMinutes": 60
}

This is for local environment but you are going to commit your code to the source control, use Secret Manager or environment variables in production.

Step 3: Configure JWT in Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        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(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

builder.Services.AddAuthorization();

var app = builder.Build();

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

Step 4: Create a Token Generator (Login Endpoint)

Here’s a basic controller code to generate JWT tokens:

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

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

    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginRequest request)
    {
        // Simulate user check (hardcoded for demo)
        if (request.Username == "admin" && request.Password == "password")
        {
            var token = GenerateToken();
            return Ok(new { token });
        }
        return Unauthorized();
    }

    private string GenerateToken()
    {
        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"],
            expires: DateTime.Now.AddMinutes(60),
            signingCredentials: creds);

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

Code for the model class(LoginRequest.cs):

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

Step 5: Secure Your Endpoints with [Authorize]

Add the following code in the controller class:

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

Step 6: Test Your JWT-Secured API with Swagger

  • Go to /swagger
  • Click Authorize (button)
  • Enter: Bearer
  • Call any [Authorize] endpoint

You’ll get the protected response. You’ll get 401 Unauthorized without the token.

Summary

Using JWT authentication in ASP.NET Core 8 is a powerful way to secure your APIs and build real-world-ready backend systems. In the next post on, we’ll explore Role-based Authorization.

Thanks for reading the blog. Stay tuned and feel free to ask questions or share feedback in the comments!

Leave a Comment

Your email address will not be published. Required fields are marked *