JWT Authentication in .
NET Core 8 Web API
Step-by-step implementation with code examples
1. Create Web API Project
Use the following command:
dotnet new webapi -n JwtAuthDemo
2. Add Required NuGet Packages
Install the following packages:
- Microsoft.AspNetCore.Authentication.JwtBearer
3. Configure JWT in Program.cs
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourIssuer",
ValidAudience = "yourAudience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
4. Generate JWT Token (AuthController.cs)
[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("your_secret_key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
JWT Authentication in .NET Core 8 Web API
Step-by-step implementation with code examples
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();
}
5. Protect Endpoints with [Authorize]
[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
return Ok("This is a protected endpoint!");
}
6. LoginModel.cs
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}