How JWT Works
A JWT is a signed, base64-encoded JSON payload. The server signs it with a secret key. Clients send it in the Authorization: Bearer header on every request.
Token Generation
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Email, user.Email!),
new Claim(ClaimTypes.Role, "Admin")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
var token = new JwtSecurityToken(
issuer: "myapp", audience: "myapp",
claims: claims, expires: DateTime.UtcNow.AddHours(1),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
Validation Setup
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o => o.TokenValidationParameters = new()
{
ValidateIssuer = true, ValidIssuer = "myapp",
ValidateAudience = true, ValidAudience = "myapp",
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
});
âš ï¸
Use a JWT key of at least 256 bits (32 characters). Short keys are vulnerable to brute-force attacks. Store it in environment variables, never in appsettings.json.
Role-Based Authorization
[Authorize(Roles = "Admin,Editor")]
[HttpPost("posts")]
public async Task<IActionResult> CreatePost([FromBody] CreatePostDto dto) { ... }