IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Routing in ASP.NET Core | Model-Binding-NET-Core | |
JWT Authentication in ASP.NET Core |
To implement JWT (JSON Web Token) authentication in an ASP.NET Core Web API, youโll need to configure both the authentication mechanism and token issuance logic.
| Part | Description |
|---|---|
| Header | Specifies token type (JWT) and signing algorithm (HS256, RS256, etc.) |
| Payload | Contains claims like sub, email, role, exp, etc. |
| Signature | Ensures integrity using secret key or RSA/ECDSA public/private key pair |
JWT claims are name/value pairs embedded in the token's payload. They assert facts about the token subject (usually the user), such as identity, permissions, or token metadata.
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
| Type | Description | Examples |
|---|---|---|
| Registered | Standardized by IANA for interoperability | iss, sub, aud, exp, iat |
| Public | Custom claims with collision-resistant names (often namespaced) | https://gktoall.com/roles |
| Private | Custom claims shared between parties, not standardized | isPremiumUser, tenantId |
| Claim | Meaning |
|---|---|
iss |
Issuer โ who issued the token |
sub |
Subject โ whom the token refers to (usually user ID) |
aud |
Audience โ who the token is intended for |
exp |
Expiration โ when the token expires (Unix timestamp) |
nbf |
Not Before โ token is invalid before this time |
iat |
Issued At โ when the token was created |
jti |
JWT ID โ unique identifier to prevent replay attacks |
{
"iss": "https://auth.gktoall.com",
"sub": "user123",
"aud": "https://api.gktoall.com",
"exp": 1735689600,
"iat": 1735686000,
"role": "educator",
"tenantId": "gktoall",
"isPremiumUser": true
}
https://gktoall.com/claims/role)TokenValidationParameters)[Authorize(Roles = "admin")])jti for token revocation and replay protectionMicrosoft.AspNetCore.Authentication.JwtBearer System.IdentityModel.Tokens.Jwt Microsoft.IdentityModel.Tokens
Program.cs or Startup.cs
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("yourSuperSecretKey"))
};
});
public string GenerateJwtToken(string username, string role)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, role)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yourSuperSecretKey"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "yourIssuer",
audience: "yourAudience",
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
[Authorize]
[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
return Ok("This is protected data");
}
TokenValidationParameters. | Routing in ASP.NET Core | Model-Binding-NET-Core | |