How to Secure ASP.NET Core Web API with JWT Tokens?

JWT (JSON Web Token) authentication in ASP.NET Core allows developers to secure APIs by issuing tokens to authenticated users. Clients use these tokens to access protected endpoints without resending credentials.

Key Features:

  • Stateless authentication for Web APIs
  • Supports token expiration and claims-based authorization
  • Easy integration with ASP.NET Core Identity
  • Works with controllers, middleware, and services
  • Enhances security and scalability

Example – Configuring JWT Authentication in Program.cs:

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 = "https://localhost",
        ValidAudience = "https://localhost",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey123!"))
    };
});

Controller with [Authorize] attribute:

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok(new { Message = "Protected data" });
}

Securing ASP.NET Core Web API with JWT ensures only authenticated users can access sensitive endpoints, improving API security and trustworthiness.

Citations:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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