How to Secure an ASP.NET Core Web API with JWT Authentication etd_admin, April 15, 2025April 15, 2025 When building modern web applications, securing your APIs is a crucial step—especially when you’re exposing data to clients like mobile apps or front-end JavaScript. One of the most popular ways to handle authentication and authorization in ASP.NET Core is by using JWT (JSON Web Token). In this article, we’ll explore how to secure an ASP.NET Core Web API with JWT Authentication step-by-step. What is JWT? WT stands for JSON Web Token, a compact, URL-safe way to represent claims between two parties. It typically contains: A header (algorithm + token type), A payload (user data or claims), And a signature to verify it hasn’t been tampered with. JWTs are ideal for stateless authentication in APIs. Install Required NuGet Packages First, make sure you have the following packages installed in your ASP.NET Core project: dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer Add Authentication Services in Program.cs or Startup.cs Here’s how to configure JWT in your Program.cs if you’re using .NET 6 or later: using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; var builder = WebApplication.CreateBuilder(args); // Add JWT Authentication 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 = "yourIssuer", ValidAudience = "yourAudience", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSuperSecretKey")) }; }); builder.Services.AddAuthorization(); builder.Services.AddControllers(); var app = builder.Build(); app.UseAuthentication(); // Must come before UseAuthorization app.UseAuthorization(); app.MapControllers(); app.Run(); This configuration tells ASP.NET Core to use JWT Bearer Authentication with your custom issuer, audience, and secret key. Create a Token Generator Endpoint You’ll usually have a login endpoint that generates a JWT when the user logs in successfully. Here’s an example controller action: [HttpPost("login")] public IActionResult Login([FromBody] LoginModel user) { if (user.Username == "admin" && user.Password == "password") { var claims = new[] { new Claim(ClaimTypes.Name, user.Username), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSuperSecretKey")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "yourIssuer", audience: "yourAudience", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); } return Unauthorized(); } The above code issues a JWT token upon successful login. Protect Your API Endpoints To secure an ASP.NET Core Web API with JWT Authentication, decorate your controller or action methods with the [Authorize] attribute: [Authorize] [ApiController] [Route("api/[controller]")] public class ProtectedController : ControllerBase { [HttpGet("data")] public IActionResult GetData() { return Ok("This is protected data!"); } } Now, this endpoint can only be accessed with a valid JWT in the Authorization header. Call the API with a JWT After receiving the token from the login endpoint, include it in the Authorization header when calling protected endpoints: GET /api/protected/data Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6... .NET .NETAuthenticationJWT