惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
CXSECURITY Database RSS Feed - CXSecurity.com
L
LINUX DO - 热门话题
S
Secure Thoughts
TaoSecurity Blog
TaoSecurity Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Threat Research - Cisco Blogs
AI
AI
B
Blog RSS Feed
S
Schneier on Security
雷峰网
雷峰网
Schneier on Security
Schneier on Security
Help Net Security
Help Net Security
Cloudbric
Cloudbric
L
LINUX DO - 最新话题
罗磊的独立博客
有赞技术团队
有赞技术团队
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Apple Machine Learning Research
Apple Machine Learning Research
P
Proofpoint News Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
The Hacker News
The Hacker News
博客园 - Franky
Attack and Defense Labs
Attack and Defense Labs
The Cloudflare Blog
Webroot Blog
Webroot Blog
Last Week in AI
Last Week in AI
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 叶小钗
美团技术团队
L
Lohrmann on Cybersecurity
T
The Blog of Author Tim Ferriss
The Last Watchdog
The Last Watchdog
T
Troy Hunt's Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Vercel News
Vercel News
Know Your Adversary
Know Your Adversary
O
OpenAI News
博客园 - 【当耐特】
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
Cybersecurity and Infrastructure Security Agency CISA
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
PCI Perspectives
PCI Perspectives
H
Heimdal Security Blog
I
InfoQ
GbyAI
GbyAI
T
Threatpost
C
Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
JWT Authentication Confused Me. Then I Built It From Scratch
Abdul Imran Faridh · 2026-06-24 · via DEV Community

Originally published at imrantech.hashnode.dev

The Honest Starting Point

When my tech lead told me to implement JWT for our HRMS portal with refresh token rotation for our HRMS portal, I nodded confidently and immediately opened Google. I had a rough idea of what JWT was. A token. You send it with every request. The server validates it. Simple enough right? Wrong. The moment I started actually building it, questions hit me one after another. Where do I store the refresh token? How short should the access token be? What happens when the refresh token expires? How do I actually revoke a token? After building it from scratch and getting it working in production, I want to walk you through the complete implementation — every file, every decision, and why I made it.

What Are We Actually Building?

Before code, let me explain the flow simply:

`User logs in

Server returns TWO tokens:

→ Access Token (short-lived — expires in minutes)

→ Refresh Token (long-lived — expires in days)

Client uses Access Token for every API request

Access Token expires?

→ Client sends Refresh Token to get a NEW Access Token

→ No need to login again!

Refresh Token expires?

→ User must login again`

Why two tokens? Because if your access token gets stolen, it expires quickly anyway. The refresh token lives in your database and can be revoked instantly if needed.

Project Structure

Here's how I structured the authentication across my project layers:

HRMS/

├── Controllers/

│ └── AuthController.cs ← API endpoints

├── HRMS.DAL/

│├── AuthService.cs ← Business logic

│ └── Interfaces/

│└── IAuthService.cs ← Contract

└── HRMS.EF/

├── Models/

│ ├── User.cs

│ └── RefreshToken.cs ← Stores refresh tokens in DB

└── DTOs/

└── AuthResponseDto.cs

Step 1 — The RefreshToken Model

First I created a database table to store refresh tokens:

// HRMS.EF/Models/RefreshToken.cs.

public class RefreshToken {

public int Id { get; set; }

public string Token { get; set; }

public DateTime Expires { get; set; }

public bool IsRevoked { get; set; }

public int UserId { get; set; } }

Three important fields here:

  • Expires — when does this refresh token die?
  • IsRevoked — did we manually invalidate it? (logout, security breach)
  • UserId — which user does this token belong to?

Step 2 — The Auth Response DTO

//HRMS.EF/DTOs/AuthResponseDto.cs

public class AuthResponseDto {

public string AccessToken { get; set; }

public string RefreshToken { get; set; }

}

Simple. Login returns both tokens together.

Step 3 — The AuthService

This is where the real logic lives.

//HRMS.DAL/AuthService.cs

public class AuthService : IAuthService {

private readonly AppDbContext _context;

private readonly IConfiguration _config;

public AuthService(AppDbContext context, IConfiguration config)
{
    _context = context;
    _config = config;
}

public async Task<string> Register(RegisterDto dto)
{
    var exists = await _context.Users
        .AnyAsync(x => x.Email == dto.Email);
    if (exists) return "User exists";

    var user = new User
    {
        Email = dto.Email,
        PasswordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password),
        Role = "Employee"
    };

    _context.Users.Add(user);
    await _context.SaveChangesAsync();

    return "Registered";
}

public async Task<object> Login(LoginDto dto)
{
    var user = await _context.Users
        .FirstOrDefaultAsync(x => x.Email == dto.Email);

    if (user == null) return "Invalid";

    if (!BCrypt.Net.BCrypt.Verify(dto.Password, user.PasswordHash))
        return "Invalid";

    // Generate both tokens
    var accessToken = GenerateToken(user);
    var refreshToken = GenerateRefreshToken();

    // Save refresh token to database
    var entity = new RefreshToken
    {
        Token = refreshToken,
        Expires = DateTime.Now.AddDays(7),
        IsRevoked = false,
        UserId = user.Id
    };

    _context.RefreshTokens.Add(entity);
    await _context.SaveChangesAsync();

    return new
    {
        accessToken,
        refreshToken
    };
}

private string GenerateToken(User user)
{
    var claims = new[]
    {
        new Claim("UserId", user.Id.ToString()),
        new Claim(ClaimTypes.Role, user.Role)
    };

    var key = new SymmetricSecurityKey(
        Encoding.UTF8.GetBytes(_config["Jwt:Key"])
    );

    var creds = new SigningCredentials(
        key, SecurityAlgorithms.HmacSha256
    );

    var token = new JwtSecurityToken(
        claims: claims,
        expires: DateTime.Now.AddMinutes(15),
        signingCredentials: creds
    );

    return new JwtSecurityTokenHandler().WriteToken(token);
}

private string GenerateRefreshToken()
{
    return Guid.NewGuid().ToString();
}

}

A few things worth noting:

BCrypt for passwords — never store plain passwords. BCrypt.HashPassword() on register, BCrypt.Verify() on login.

Access token expiry — I set this to 15 minutes in production. During development I actually set it to 25 seconds to test the refresh flow quickly without waiting! If your token expires almost immediately while testing — that's why. 😄

Refresh token — I'm using Guid.NewGuid().ToString() which generates a unique random string. Simple and works perfectly for this use case.

Step 4 — The AuthController

//HRMS/Controllers/AuthController.cs

[ApiController]

[Route("api/auth")]

public class AuthController : ControllerBase {

private readonly IAuthService _service;

private readonly AppDbContext _context;

private readonly IConfiguration _config;

public AuthController(
    IAuthService service,
    AppDbContext context,
    IConfiguration config)
{
    _service = service;
    _context = context;
    _config = config;
}

[HttpPost("register")]
public async Task<IActionResult> Register(RegisterDto dto)
{
    return Ok(await _service.Register(dto));
}

[HttpPost("login")]
public async Task<IActionResult> Login(LoginDto dto)
{
    return Ok(await _service.Login(dto));
}

[HttpPost("refresh")]
public async Task<IActionResult> Refresh(string refreshToken)
{
    // Find the token in database
    var token = await _context.RefreshTokens
        .FirstOrDefaultAsync(x => x.Token == refreshToken);

    // Three checks before issuing new access token
    if (token == null || token.IsRevoked || token.Expires < DateTime.Now)
        return Unauthorized("Invalid refresh token");

    var user = await _context.Users.FindAsync(token.UserId);

    var newAccessToken = GenerateToken(user);

    return Ok(new { accessToken = newAccessToken });
}

private string GenerateToken(User user)
{
    var claims = new[]
    {
        new Claim("UserId", user.Id.ToString()),
        new Claim(ClaimTypes.Role, user.Role)
    };

    var key = new SymmetricSecurityKey(
        Encoding.UTF8.GetBytes(_config["Jwt:Key"])
    );

    var creds = new SigningCredentials(
        key, SecurityAlgorithms.HmacSha256
    );

    var token = new JwtSecurityToken(
        claims: claims,
        expires: DateTime.Now.AddMinutes(15),
        signingCredentials: creds
    );

    return new JwtSecurityTokenHandler().WriteToken(token);
}

}

The Refresh endpoint does three critical checks:

if (token == null || token.IsRevoked || token.Expires < DateTime.Now) return Unauthorized("Invalid refresh token");

  • token == null — doesn't exist in DB (fake token?)
  • token.IsRevoked — we manually revoked it (user logged out)
  • token.Expires < DateTime.Now — it's expired

All three must pass before we issue a new access token. This is the security layer.

Step 5 — Program.cs Configuration

//JWT Bearer setup

builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "Bearer";

options.DefaultChallengeScheme = "Bearer";

})

.AddJwtBearer("Bearer", options =>

{

options.TokenValidationParameters = new TokenValidationParameters

{

ValidateIssuer = false,

ValidateAudience = false,

ValidateLifetime = true,

ValidateIssuerSigningKey = true,

RoleClaimType = System.Security.Claims.ClaimTypes.Role,

ClockSkew = TimeSpan.Zero, // ← Important!

IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))

};

});

//Swagger with Bearer support

builder.Services.AddSwaggerGen(options =>

{

options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme

{

Name = "Authorization",

Type = SecuritySchemeType.Http,

Scheme = "bearer",

BearerFormat = "JWT",

In = ParameterLocation.Header,

Description = "Enter your JWT token only (without 'Bearer' prefix)."

});

options.AddSecurityRequirement(new OpenApiSecurityRequirement

{

{

new OpenApiSecurityScheme

{

Reference = new OpenApiReference

{

Type = ReferenceType.SecurityScheme,

Id = "Bearer"

}

},

new string[] {}

}

});

});

//Middleware order matters!

app.UseAuthentication();

app.UseAuthorization();

The most important line here:

ClockSkew = TimeSpan.Zero

By default ASP.NET Core adds a 5-minute buffer to token expiry. So a token set to expire at 3:00 PM actually expires at 3:05 PM. That drives me crazy when testing. Setting ClockSkew = TimeSpan.Zero makes tokens expire exactly when you set them — no surprises.

Step 6 — appsettings.json

{

"Jwt":

{

"Key": "YourSuperSecretKeyHereMustBe32CharsMin!"

},

"ConnectionStrings":

{

"Default": "Server=...;Database=HRMS;..."

}

}

Important: Never commit your real JWT key to GitHub! Add appsettings.json to .gitignore or use environment variables in production.

The Before vs After Story

When I first implemented login, it looked like this:

// OLD — Simple JWT, no refresh token

public async Task<string> Login(LoginDto dto)

{

var user = await _context.Users .FirstOrDefaultAsync(x => x.Email dto.Email);

if (user null) return "Invalid";

if (!BCrypt.Net.BCrypt.Verify(dto.Password, user.PasswordHash))

return "Invalid";

return GenerateToken(user); // Just returns access token

}

The problem: When the access token expired, users got logged out and had to log in again. For an HRMS portal where HR managers are working all day — that's really annoying.

The refresh token approach fixes this silently in the background. The Angular frontend detects a 401 response, automatically calls /api/auth/refresh, gets a new access token, and retries the original request — all without the user ever knowing their token expired.

Complete Flow Summary:

POST /api/auth/login

→ Returns: { accessToken, refreshToken }

Every API request:

→ Header: Authorization: Bearer {accessToken}

Access token expires (401 response):

→ POST /api/auth/refresh?refreshToken={refreshToken}

→ Returns: { accessToken } (new one)

User logs out:

→ Set IsRevoked = true on refresh token in DB

→ Both tokens now dead

Key Takeaways:

Always use two tokens — short access token for security, long refresh token for user experience.

Store refresh tokens in DB — this is what allows you to revoke them instantly. If you store them only on the client side, you can never invalidate them.

Set ClockSkew to Zero — unless you enjoy debugging token expiry issues at weird times.

BCrypt for passwords — never plain text, never MD5, never SHA1. BCrypt only.

Check three things on refresh — token exists, not revoked, not expired. Skip any one of these and you have a security hole.

Conclusion

JWT with refresh tokens sounds complicated until you break it down step by step. The actual code isn't that large — it's just understanding why each piece exists.

The access token is your fast key. The refresh token is your backup key stored in a safe. Short-lived tokens keep you secure. Long-lived refresh tokens keep your users happy.

If this helped you, subscribe for 3 practical .NET articles every week — all from real production code just like this! 🚀