🔹 Title:
How to Implement JWT Authentication in ASP.NET Core Web API?
🔹 Technology:
C#, ASP.NET Core, Web API, JWT
🔹 Description:
I am a beginner in ASP.NET Core and currently learning how to build secure Web APIs. I want to implement JWT (JSON Web Token) based authentication in my project.
I would like to understand the complete flow of authentication, including token generation, validation, and securing API endpoints.
🔹 What I Tried:
I created a basic API project and tried adding authentication services, but I am confused about how to properly configure JWT and use it in controllers.
🔹 Code:
builder.Services.AddAuthentication();
🔹 Error / Issue:
No specific error, but I am unable to understand how to generate and validate JWT tokens properly.
🔹 Expected Result:
I want to successfully implement JWT authentication so that only authorized users can access protected API endpoints.
🔹 Environment:
- .NET 6 / .NET 7
- Visual Studio
🔹 Additional Info:
Any step-by-step guidance or simple example would be very helpful.


Cynthia SathuragiriRank #937 · 2.2K reputationPosted Apr 10, 2026, 2:10 AM EDT
To implement JWT authentication in ASP.NET Core Web API, you need to configure three main things:
JWT authentication setup
Token generation
Securing endpoints
1. Install Required Package
First, install the JWT Bearer package:
2. Configure JWT in Program.cs
Simply calling
AddAuthentication()is not enough. You must configure JWT properly:using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; var builder = WebApplication.CreateBuilder(args); 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("YourSecretKey12345")) }; }); builder.Services.AddAuthorization(); var app = builder.Build(); app.UseAuthentication(); // must come before UseAuthorization app.UseAuthorization(); app.MapControllers(); app.Run();3. Generate JWT Token
Create a helper/service to generate the token:
using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using System.Text; public class JwtService { public string GenerateToken(string username) { var claims = new[] { new Claim(ClaimTypes.Name, username) }; var key = new SymmetricSecurityKey( Encoding.UTF8.GetBytes("YourSecretKey12345")); 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 new JwtSecurityTokenHandler().WriteToken(token); } }4. Create Login API
This API validates user credentials and returns a token:
[ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { private readonly JwtService _jwtService = new JwtService(); [HttpPost("login")] public IActionResult Login(string username, string password) { // Replace with real DB validation if (username == "admin" && password == "password") { var token = _jwtService.GenerateToken(username); return Ok(new { token }); } return Unauthorized(); } }5. Protect API Endpoints
Use
[Authorize]attribute:[ApiController] [Route("api/[controller]")] public class TestController : ControllerBase { [HttpGet] [Authorize] public IActionResult Get() { return Ok("This is a protected API"); } }Client calls
/api/auth/login? receives JWT tokenClient sends token in header:
ASP.NET Core middleware:
Validates token signature using secret key
Checks expiry, issuer, audience
Sets
HttpContext.User[Authorize]allows or denies accessStore JWT settings in
appsettings.json:"Jwt": { "Key": "YourSecretKey12345", "Issuer": "yourIssuer", "Audience": "yourAudience" }This is the complete flow to implement JWT authentication in ASP.NET Core Web API.
Prasad RaveendranRank #320 · 7.8K reputationPosted Apr 11, 2026, 10:46 AM EDT
Since you are beginner, i always encourage to understand the concept and the key usage, what are good practices to store the secret keys and all.
Give a try on PASETO which is an alternative for JWT