JWT (JSON Web Token) authentication in ASP.NET Core API is a secure and efficient way to handle user authentication and authorization. Here's a step-by-step article on setting up JWT authentication in an ASP.NET Core Web API.
Install Required NuGet Packages

Configure JWT Authentication
Update Program.cs to configure JWT authentication in the service section and middleware section.
builder.Services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(opt =>
{ // for development only
opt.RequireHttpsMetadata = false;
opt.SaveToken = true;
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration["JWT:SecretKey"])),
ValidateIssuer = true,
ValidIssuer = builder.Configuration["JWT:Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["JWT:Audience"]
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
// Use authentication and authorization
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
This configuration sets up the application to authenticate incoming requests using the JWT tokens and validate them based on certain parameters.
Generate the JWT Tokens
public string GenerateJwtToken(string userName, string name, string role)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["JWT:SecretKey"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, userName),
new Claim(ClaimTypes.GivenName, name),
new Claim(ClaimTypes.Role, role)
}),
IssuedAt = DateTime.UtcNow,
Issuer = _configuration["JWT:Issuer"],
Audience = _configuration["JWT:Audience"],
Expires = DateTime.UtcNow.AddMinutes(30), // can change exprires time
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var userToken = tokenHandler.WriteToken(token);
return userToken;
}
Authenticate Users And Issue The JWT Tokens
[HttpPost("login")]
public IActionResult Login(LoginModel model)
{
// Authenticate user
var user = _userService.Authenticate(model.Username, model.Password);
if (user == null)
return Unauthorized();
// Generate JWT token
var token = _authenticationService.GenerateJwtToken(
user.userName,
user.Name,
user.Role
);
return Ok(new { token });
}

Join the conversation! Your thoughts help the community grow.