JWT Authentication in ASP.NET Core
|
|
Implementing JWT Authentication in ASP.NET Core Web API
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.
๐ Overview: Why JWT for Web APIs?
- Stateless and scalable: No server-side session storage.
- Compact and self-contained: Includes user claims and metadata.
- Ideal for RESTful APIs: Works across mobile, web, and IoT clients.
๐งฉ Core Components of JWT
| 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 |
What Are JWT Claims?
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.
Example Claim Payload
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
๐ฆ Types of JWT Claims
| 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 |
๐ Common Registered Claims
| 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 |
๐งช Example Payload with Mixed Claims
{
"iss": "https://auth.gktoall.com",
"sub": "user123",
"aud": "https://api.gktoall.com",
"exp": 1735689600,
"iat": 1735686000,
"role": "educator",
"tenantId": "gktoall",
"isPremiumUser": true
}
๐งญ Best Practices for Claims
- โ
Namespace custom claims to avoid collisions (e.g.,
https://gktoall.com/claims/role)
- ๐ Avoid sensitive data in claims unless encrypted
- ๐งผ Validate claims rigorously in middleware (
TokenValidationParameters)
- ๐งช Use claims for authorization (e.g.,
[Authorize(Roles = "admin")])
- ๐ Include
jti for token revocation and replay protection
๐ ๏ธ Step-by-Step Implementation in ASP.NET
1. Install Required NuGet Packages
Microsoft.AspNetCore.Authentication.JwtBearer
System.IdentityModel.Tokens.Jwt
Microsoft.IdentityModel.Tokens
2. Configure JWT in 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"))
};
});
3. Generate JWT Token on Login
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);
}
4. Protect API Endpoints with [Authorize]
[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
return Ok("This is protected data");
}
โ
Best Practices
- ๐ Use HTTPS to prevent token interception.
- โณ Set short expiration and implement refresh tokens.
- ๐งช Validate tokens rigorously using
TokenValidationParameters.
- ๐งผ Revoke tokens on logout or password change.
- ๐งญ Use role-based or policy-based authorization for fine-grained access control.