JWT Nedir?
JSON Web Token, taraflar arasında güvenli bilgi transferi için kullanılan kompakt, imzalı token standardıdır. Header.Payload.Signature formatındadır.
NuGet Paketleri
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.JwtProgram.cs Yapılandırması
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt => {
opt.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = config["Jwt:Issuer"],
ValidAudience = config["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(config["Jwt:Key"]))
};
});Token Üretme
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddHours(24),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);Controller'da Yetkilendirme
[Authorize(Roles = "Admin")]
[HttpDelete("{id}")]
public IActionResult Sil(int id) { ... }