JWT Authentication And Refresh Tokens In ASP.NET Core
```Authentication is one of the most important aspects of modern web applications and APIs. JWT (JSON Web Token) authentication has become the standard approach for securing ASP.NET Core APIs because it is lightweight, scalable, and works well in distributed systems and microservices architectures.
What Is JWT?
JWT stands for JSON Web Token. It is a compact and self-contained token used to securely transmit user information between parties.
A JWT contains three parts:
- Header
- Payload
- Signature
xxxxx.yyyyy.zzzzz
Why Use JWT Authentication?
- Stateless authentication
- Scalable architecture
- Works with APIs
- Supports mobile applications
- Supports microservices
- Easy integration with cloud environments
JWT Authentication Flow
- User submits username and password
- Server validates credentials
- Server generates JWT token
- Token returned to client
- Client sends token in Authorization header
- API validates token
- Request is authorized
Installing JWT Package
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Configure JWT Authentication
builder.Services
.AddAuthentication(
JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
});
Configure Authentication Middleware
app.UseAuthentication(); app.UseAuthorization();
Authentication must be registered before authorization.
Creating JWT Tokens
var tokenHandler =
new JwtSecurityTokenHandler();
var key =
Encoding.UTF8.GetBytes(secretKey);
var tokenDescriptor =
new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(
new[]
{
new Claim(
ClaimTypes.Name,
username)
}),
Expires =
DateTime.UtcNow.AddMinutes(30),
SigningCredentials =
new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature)
};
var token =
tokenHandler.CreateToken(
tokenDescriptor);
Adding Claims
Claims store user information inside the token.
new Claim(
ClaimTypes.Name,
user.UserName),
new Claim(
ClaimTypes.Role,
"Admin")
Role-Based Authorization
[Authorize(Roles = "Admin")]
public IActionResult Dashboard()
{
return View();
}
What Is A Refresh Token?
Access tokens usually have a short lifetime. Refresh tokens allow users to obtain a new access token without logging in again.
This improves both security and user experience.
Refresh Token Flow
- User logs in
- Server generates Access Token
- Server generates Refresh Token
- Access Token expires
- Client sends Refresh Token
- Server issues new Access Token
Refresh Token Table Example
CREATE TABLE RefreshTokens
(
Id INT IDENTITY(1,1),
UserId INT,
Token NVARCHAR(MAX),
ExpiryDate DATETIME
)
Generating Refresh Tokens
var refreshToken =
Guid.NewGuid().ToString();
Refresh tokens should be stored securely in the database.
Token Validation
When a request arrives, ASP.NET Core automatically validates:
- Issuer
- Audience
- Expiration
- Signature
- Signing key
Security Best Practices
- Use HTTPS only
- Store secrets securely
- Use short-lived access tokens
- Rotate refresh tokens
- Validate all claims
- Store refresh tokens in database
- Implement token revocation
JWT In Microservices
JWT is widely used in microservices because services can validate tokens without calling a centralized authentication server for every request.
Azure Integration
JWT authentication can be integrated with:
- Azure Active Directory
- Azure AD B2C
- Microsoft Entra ID
- Azure API Management
Production Support Scenario
A production application was randomly logging users out. Investigation showed that token expiration was configured for only five minutes. Increasing expiration time and implementing refresh tokens resolved the issue.
Common Interview Questions
- What is JWT?
- How does JWT authentication work?
- What are Claims?
- What is the difference between Authentication and Authorization?
- Why use Refresh Tokens?
- How do you secure JWT tokens?
- How does token validation work?
- How would you implement logout with JWT?
Common Mistakes
- Storing secrets in source code
- Using long-lived access tokens
- Not validating token expiration
- Not implementing refresh tokens
- Ignoring token revocation
Best Practices
- Use HTTPS everywhere
- Store secrets in Key Vault
- Use Refresh Tokens
- Use role-based authorization
- Log authentication events
- Monitor failed login attempts
Conclusion
JWT Authentication is the preferred authentication mechanism for modern ASP.NET Core APIs. When combined with Refresh Tokens, it provides a secure, scalable, and user-friendly authentication system suitable for enterprise applications, cloud deployments, and microservices architectures.