Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
Asp.Net Core

ASP.NET Core JWT Authentication: Access Tokens, Refresh Tokens, and Security Deep Dive

- 19.08.26 | 19.08.26 - ErcanOPAK

JWT authentication is everywhere, but most implementations are insecure or incomplete. Here’s how to build a production-ready JWT system with refresh tokens.

1. Complete JWT Implementation:

// appsettings.json
{
  "JwtSettings": {
    "Secret": "your-256-bit-secret-key-minimum-32-characters",
    "Issuer": "myapp.com",
    "Audience": "myapp-api",
    "AccessTokenExpirationMinutes": 15,
    "RefreshTokenExpirationDays": 7
  }
}

// JwtSettings.cs
public class JwtSettings
{
    public string Secret { get; set; }
    public string Issuer { get; set; }
    public string Audience { get; set; }
    public int AccessTokenExpirationMinutes { get; set; }
    public int RefreshTokenExpirationDays { get; set; }
}

// JwtService.cs
public class JwtService
{
    private readonly JwtSettings _settings;
    
    public JwtService(IOptions<JwtSettings> settings)
    {
        _settings = settings.Value;
    }
    
    public string GenerateAccessToken(string userId, string email, IEnumerable<string> roles)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Secret));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
        
        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Sub, userId),
            new Claim(JwtRegisteredClaimNames.Email, email),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(JwtRegisteredClaimNames.Iat, 
                new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString(),
                ClaimValueTypes.Integer64)
        };
        
        // Add roles
        foreach (var role in roles)
        {
            claims.Add(new Claim(ClaimTypes.Role, role));
        }
        
        var token = new JwtSecurityToken(
            issuer: _settings.Issuer,
            audience: _settings.Audience,
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(_settings.AccessTokenExpirationMinutes),
            signingCredentials: credentials
        );
        
        return new JwtSecurityTokenHandler().WriteToken(token);
    }
    
    public string GenerateRefreshToken()
    {
        // Cryptographically secure random bytes
        var randomNumber = new byte[64];
        using var rng = RandomNumberGenerator.Create();
        rng.GetBytes(randomNumber);
        return Convert.ToBase64String(randomNumber);
    }
    
    public ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
    {
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = false,  // We want expired token
            ValidateIssuerSigningKey = true,
            ValidIssuer = _settings.Issuer,
            ValidAudience = _settings.Audience,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Secret))
        };
        
        var tokenHandler = new JwtSecurityTokenHandler();
        var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);
        if (securityToken is not JwtSecurityToken jwtToken || 
            !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
        {
            throw new SecurityTokenException("Invalid token");
        }
        
        return principal;
    }
}

2. User Login and Refresh Token:

// AuthController.cs
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly JwtService _jwtService;
    private readonly IUserService _userService;
    private readonly IRefreshTokenService _refreshTokenService;
    
    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginRequest request)
    {
        var user = await _userService.AuthenticateAsync(request.Email, request.Password);
        if (user == null)
        {
            return Unauthorized("Invalid email or password");
        }
        
        var accessToken = _jwtService.GenerateAccessToken(
            user.Id, 
            user.Email, 
            user.Roles
        );
        
        var refreshToken = new RefreshToken
        {
            Token = _jwtService.GenerateRefreshToken(),
            UserId = user.Id,
            ExpiryDate = DateTime.UtcNow.AddDays(7),
            IsRevoked = false,
            CreatedAt = DateTime.UtcNow
        };
        
        await _refreshTokenService.SaveRefreshTokenAsync(refreshToken);
        
        return Ok(new AuthResponse
        {
            AccessToken = accessToken,
            RefreshToken = refreshToken.Token,
            ExpiresIn = 900,  // 15 minutes in seconds
            User = new UserDto
            {
                Id = user.Id,
                Email = user.Email,
                Name = user.Name
            }
        });
    }
    
    [HttpPost("refresh")]
    public async Task<IActionResult> Refresh(RefreshRequest request)
    {
        try
        {
            // Get user ID from expired token
            var principal = _jwtService.GetPrincipalFromExpiredToken(request.AccessToken);
            var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            
            if (string.IsNullOrEmpty(userId))
            {
                return Unauthorized();
            }
            
            // Validate refresh token
            var storedRefreshToken = await _refreshTokenService
                .GetRefreshTokenAsync(request.RefreshToken, userId);
            
            if (storedRefreshToken == null || 
                storedRefreshToken.IsRevoked || 
                storedRefreshToken.ExpiryDate < DateTime.UtcNow)
            {
                return Unauthorized("Invalid or expired refresh token");
            }
            
            // Generate new tokens
            var user = await _userService.GetUserByIdAsync(userId);
            var newAccessToken = _jwtService.GenerateAccessToken(
                user.Id, 
                user.Email, 
                user.Roles
            );
            
            var newRefreshToken = _jwtService.GenerateRefreshToken();
            
            // Replace refresh token
            storedRefreshToken.Token = newRefreshToken;
            storedRefreshToken.ExpiryDate = DateTime.UtcNow.AddDays(7);
            storedRefreshToken.CreatedAt = DateTime.UtcNow;
            
            await _refreshTokenService.UpdateRefreshTokenAsync(storedRefreshToken);
            
            return Ok(new AuthResponse
            {
                AccessToken = newAccessToken,
                RefreshToken = newRefreshToken,
                ExpiresIn = 900
            });
        }
        catch (SecurityTokenException)
        {
            return Unauthorized("Invalid token");
        }
    }
    
    [HttpPost("logout")]
    [Authorize]
    public async Task<IActionResult> Logout(LogoutRequest request)
    {
        var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (string.IsNullOrEmpty(userId))
        {
            return BadRequest();
        }
        
        await _refreshTokenService.RevokeRefreshTokenAsync(request.RefreshToken, userId);
        return Ok();
    }
}

3. Refresh Token Database Schema:

// RefreshToken Entity
public class RefreshToken
{
    public int Id { get; set; }
    public string Token { get; set; }
    public string UserId { get; set; }
    public DateTime ExpiryDate { get; set; }
    public bool IsRevoked { get; set; }
    public DateTime CreatedAt { get; set; }
    public string CreatedByIp { get; set; }  // Security
    public DateTime? RevokedAt { get; set; }
    public string RevokedByIp { get; set; }
    
    [ForeignKey("UserId")]
    public virtual ApplicationUser User { get; set; }
}

// EF Migration
CREATE TABLE RefreshTokens (
    Id INT PRIMARY KEY IDENTITY(1,1),
    Token NVARCHAR(MAX) NOT NULL,
    UserId NVARCHAR(450) NOT NULL,
    ExpiryDate DATETIME2 NOT NULL,
    IsRevoked BIT NOT NULL DEFAULT 0,
    CreatedAt DATETIME2 NOT NULL,
    CreatedByIp NVARCHAR(50),
    RevokedAt DATETIME2,
    RevokedByIp NVARCHAR(50),
    CONSTRAINT FK_RefreshTokens_Users FOREIGN KEY (UserId) REFERENCES Users(Id)
);

CREATE INDEX IX_RefreshTokens_UserId ON RefreshTokens(UserId);
CREATE UNIQUE INDEX IX_RefreshTokens_Token ON RefreshTokens(Token);

4. JWT Middleware Configuration:

// Program.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 = builder.Configuration["JwtSettings:Issuer"],
        ValidAudience = builder.Configuration["JwtSettings:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:Secret"])
        ),
        ClockSkew = TimeSpan.Zero,  // No tolerance
        RoleClaimType = ClaimTypes.Role
    };
    
    // ✅ Security: Validate JWT ID to prevent replay attacks
    options.TokenValidationParameters.ValidateTokenReplay = true;
    
    // ✅ Security: Block tokens that are too old
    options.TokenValidationParameters.RequireExpirationTime = true;
    
    options.Events = new JwtBearerEvents
    {
        OnAuthenticationFailed = context =>
        {
            if (context.Exception is SecurityTokenExpiredException)
            {
                context.Response.Headers.Add("Token-Expired", "true");
            }
            return Task.CompletedTask;
        },
        OnChallenge = context =>
        {
            context.HandleResponse();
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";
            
            var result = JsonSerializer.Serialize(new
            {
                message = context.ErrorDescription ?? "You are not authorized",
                status = 401
            });
            
            return context.Response.WriteAsync(result);
        }
    };
});

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => 
        policy.RequireRole("Admin"));
    
    options.AddPolicy("UserOrAdmin", policy => 
        policy.RequireRole("User", "Admin"));
});

// Usage:
[Authorize]
[Authorize(Roles = "Admin")]
[Authorize(Policy = "AdminOnly")]

5. Security Best Practices:

// ✅ Store tokens securely (HttpOnly cookies)
public class CookieService
{
    public void SetJwtCookie(HttpContext context, string accessToken, string refreshToken)
    {
        var cookieOptions = new CookieOptions
        {
            HttpOnly = true,  // ✅ JavaScript cannot access
            Secure = true,    // ✅ HTTPS only
            SameSite = SameSiteMode.Strict,
            Expires = DateTime.UtcNow.AddMinutes(15)
        };
        
        context.Response.Cookies.Append("access_token", accessToken, cookieOptions);
        context.Response.Cookies.Append("refresh_token", refreshToken, cookieOptions);
    }
}

// ✅ Validate refresh token on every request
public class RefreshTokenValidator
{
    private readonly IRefreshTokenService _refreshTokenService;
    
    public async Task ValidateRefreshTokenAsync(string token, string userId)
    {
        var storedToken = await _refreshTokenService.GetRefreshTokenAsync(token, userId);
        
        if (storedToken == null || 
            storedToken.IsRevoked || 
            storedToken.ExpiryDate < DateTime.UtcNow || storedToken.UserId != userId) { throw new SecurityTokenException("Invalid refresh token"); } // ✅ Rotate token on use storedToken.IsRevoked = true; await _refreshTokenService.UpdateRefreshTokenAsync(storedToken); } } // ✅ Blacklist expired/revoked tokens public class TokenBlacklistService { private readonly IMemoryCache _cache; public void BlacklistToken(string jti) { _cache.Set($"blacklist:{ jti }", true, TimeSpan.FromHours(1)); } public bool IsTokenBlacklisted(string jti) { return _cache.TryGetValue($"blacklist:{jti}", out _); } } // ✅ Rate limiting for authentication endpoints builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("Auth", opt =>
    {
        opt.PermitLimit = 5;
        opt.Window = TimeSpan.FromMinutes(1);
        opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        opt.QueueLimit = 2;
    });
});

[HttpPost("login")]
[EnableRateLimiting("Auth")]
public async Task Login(LoginRequest request)
{
    // ...
}

6.Client – Side Implementation:

 
// Token management in JavaScript class AuthService
{
  constructor() {
    this.accessToken = null;
    this.refreshToken = null;
    this.refreshTimeout = null;
    this.baseURL = '/api/auth';
  }

  async login(email, password) {
    const response = await
    fetch(`${ this.baseURL}/ login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email,
        password
      })
    });

    if (!response.ok)
      throw new Error('Login failed');

    const data = await response.json();
    this.setTokens(data.accessToken, data.refreshToken);
    this.scheduleTokenRefresh(data.expiresIn);
    return data;
  }
  async refresh() {
    try {
      const response = await fetch(`${ this.baseURL}/ refresh`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          accessToken: this.accessToken,
          refreshToken: this.refreshToken
        })
      });
      if (!response.ok) throw new Error('Refresh failed');
      const data = await response.json();
      this.setTokens(data.accessToken, data.refreshToken);
      this.scheduleTokenRefresh(data.expiresIn);
      return data.accessToken;
    } catch (error) {
      this.clearTokens();
      window.location.href = '/login';
      throw error;
    }
  }
  setTokens(accessToken, refreshToken) {
    this.accessToken = accessToken;
    this.refreshToken = refreshToken;
    localStorage.setItem('accessToken', accessToken);
    localStorage.setItem('refreshToken', refreshToken);
  }
  scheduleTokenRefresh(expiresIn) { 
     // Refresh 1 minute before expiry 
     const refreshTime = (expiresIn - 60) * 1000; 
     clearTimeout(this.refreshTimeout); 
     this.refreshTimeout = setTimeout(() => this.refresh(), refreshTime); 
  } 

  async fetchWithAuth(url, options = { }) { 
  let response = await fetch(url, { ...options, headers: { ...options.headers, 'Authorization': `Bearer ${this.accessToken}` } 
  }); 

  // Token expired - try refresh once 
  if (response.status === 401 && this.refreshToken) { 
  await this.refresh(); 
  response = await fetch(url, { ...options, headers: { ...options.headers, 'Authorization': `Bearer ${ this.accessToken}` } }); 
  } 
  return response; 
  } 
}

7.Security Audit Checklist:

 ✅ JWT Security Checklist: 
- [ ] Use strong HMAC - SHA256 or RSA256 
- [ ] Secret key: minimum 32 characters 
- [ ] Short - lived access tokens(15 minutes) 
- [ ] Refresh tokens stored in database 
- [ ] Refresh token rotation enabled 
- [ ] Validate issuer and audience 
- [ ] Validate token expiration 
- [ ] HttpOnly, Secure, SameSite cookies 
- [ ] Rate limiting on auth endpoints 
- [ ] Log failed login attempts 
- [ ] Account lockout after X attempts 
- [ ] CORS properly configured 
- [ ] HTTPS enabled everywhere 
- [ ] Store refresh tokens securely (hashed) 
- [ ] Implement logout(revoke refresh token) 
- [ ] Blacklist mechanism for revoked tokens 
- [ ] Device fingerprinting(for extra security) 
- [ ] Validate claims(user ID, roles, etc.) 
- [ ] No sensitive data in token payload

Related posts:

.NET Core: Add Health Checks to Monitor Application Status

.NET Core: Add Health Checks to Monitor Application Status

ASP.NET Core: Fix a gRPC Call Returning Unimplemented for a Method That Exists Because the Proto Pac...

ASP.NET Core: Fix a gRPC Call Returning Unimplemented for a Method That Exists Because the Proto Pac...

ASP.NET Core: Why Your API Returns 401 Even Though the Token Looks Valid

ASP.NET Core: Why Your API Returns 401 Even Though the Token Looks Valid

Views: 14
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

C# Exception Handling: Best Practices and Anti-Patterns Deep Dive
SQL Server Execution Plan Analysis: Find and Fix Slow Queries Like a Pro

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,080 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 999 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 998 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 874 views
  5. 05How to select distinct rows in a datatable in C# 869 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 673 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 632 views
  8. 08Average of all values in a column that are not zero in SQL 586 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 563 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com