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

推荐订阅源

美团技术团队
P
Privacy International News Feed
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
N
Netflix TechBlog - Medium
S
Security Affairs
Spread Privacy
Spread Privacy
罗磊的独立博客
腾讯CDC
MyScale Blog
MyScale Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 热门话题
The Cloudflare Blog
L
LangChain Blog
博客园_首页
H
Hacker News: Front Page
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
SecWiki News
SecWiki News
A
Arctic Wolf
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
T
Tailwind CSS Blog
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
D
Docker

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
Add Refresh Tokens to Your Hono OIDC Server (with Token Rotation)
ShyGyver · 2026-05-06 · via DEV Community

The previous articles in this series built a working OIDC Authorization Code Flow server, fixed the hardcoded issuer, discussed persistent signing keys, and added a consent screen. Now it's time to tackle the refresh token grant.

Access tokens are short-lived by design (~30 minutes - 90 minutes). Once they expire, the client needs a new one. Without refresh tokens, that means sending the user back through the login and consent flow every hour. That makes a TERRIBLE experience for long-lived sessions like a mobile app or a background service. Can you imagine having to log in (user + password) every hour just to open your email app?

The refresh token grant solves this.

After the user authenticates and grants consent, the server issues a long-lived refresh token alongside the short-lived access token. The client stores the refresh token securely and exchanges it for a new access token whenever the old one expires. No user interaction required.

The offline_access scope controls whether a refresh token is issued. Clients that need to operate when the user is not actively present request it explicitly, which also ensures the user sees it on the consent screen before agreeing.

FYI: I didn't come up with the name offline_access. It is in the OpenID Connect specification.


TL;DR

The full runnable example is available at Github (apps/oidc-refresh-app).


What changes

Three areas of the server need updating:

Area Change
Client config Add "refresh_token" to authorized grants and "offline_access" to authorized scopes
Storage Save the refresh tokens and their metadata (client, user, scope, expiration)
Flow builder Register the new scope, extend getClient, update generateAccessToken, add generateAccessTokenFromRefreshToken

The authorization and consent endpoints are untouched. Refresh tokens are entirely a token-endpoint concern.


Step 1: Update the client configuration

The client needs two additions: the refresh_token grant type and the offline_access scope.

// Before
const CLIENT = {
  id: "example-client",
  secret: "example-secret",
  grants: ["authorization_code"],
  redirectUris: [],
  scopes: ["openid", "profile", "email", "content:read", "content:write"],
};

Enter fullscreen mode Exit fullscreen mode

// After
const CLIENT: {
  id: string;
  secret: string;
  grants: string[];
  redirectUris: string[];
  scopes: string[];
} = {
  id: "example-client",
  secret: "example-secret",
  grants: ["authorization_code", "refresh_token"],
  redirectUris: [],
  scopes: ["openid", "offline_access", "profile", "email", "content:read", "content:write"],
};

Enter fullscreen mode Exit fullscreen mode

The grants array is checked inside getClient to ensure the client is actually allowed to use the refresh token grant. The scopes array is what the consent screen will offer to the user. Without "offline_access" in scopes, the client cannot request it.


Step 2: Add refresh token storage

Add an in-memory map to hold issued refresh tokens:

// in-memory refresh token storage, mapping refresh tokens to client, user, scope, and expiration
const refreshTokenStorage: Record<
  string,
  {
    clientId: string;
    userId: string;
    scope: string[];
    expiresAt: number;
  }
> = {};

Enter fullscreen mode Exit fullscreen mode

Each entry key is the refresh token value. scope records what scopes the token was issued for, so a narrowed scope can be enforced on renewal. expiresAt is checked on every use to reject stale tokens.

In production, replace this with a persistent store (Redis, PostgreSQL, etc.) so refresh tokens survive restarts and can be revoked centrally.


Step 3: Register offline_access in the flow builder

Add the new scope to .setScopes() so it appears in the discovery document:

// Before
.setScopes({
  openid: "OpenID Connect scope",
  profile: "Access to your profile information",
  email: "Access to your email address",
  "content:read": "Access to read content",
  "content:write": "Access to write content",
})

Enter fullscreen mode Exit fullscreen mode

// After
.setScopes({
  openid: "OpenID Connect scope",
  offline_access: "Request refresh token for offline access",
  profile: "Access to your profile information",
  email: "Access to your email address",
  "content:read": "Access to read content",
  "content:write": "Access to write content",
})

Enter fullscreen mode Exit fullscreen mode


Step 4: Update getClient to handle the refresh token grant

getClient is called for every POST to /token. Previously it only handled authorization_code. Now it needs a second branch for refresh_token.

.getClient(async (tokenRequest) => {
  // existing authorization_code branch unchanged
  if (
    tokenRequest.grantType === "authorization_code" &&
    tokenRequest.clientId === CLIENT.id &&
    tokenRequest.code
  ) {
    // ... same as before
  }

  // handle the refresh token grant type
  if (
    tokenRequest.grantType === "refresh_token" &&
    tokenRequest.clientId === CLIENT.id &&
    CLIENT.grants.includes("refresh_token")
  ) {
    const refreshTokenData = refreshTokenStorage[tokenRequest.refreshToken];

    // validate the refresh token and its association with the client
    if (!refreshTokenData)
      throw new HTTPException(400, {
        res: new Response(
          JSON.stringify({ error: "invalid_grant", error_description: "Invalid refresh token" }),
          { headers: { "Content-Type": "application/json" } }
        ),
      });

    if (refreshTokenData.clientId !== tokenRequest.clientId)
      throw new HTTPException(400, {
        res: new Response(
          JSON.stringify({
            error: "invalid_grant",
            error_description: "Invalid client for refresh token",
          }),
          { headers: { "Content-Type": "application/json" } }
        ),
      });

    // for security, remove the used refresh token to prevent reuse (rotate on each use)
    delete refreshTokenStorage[tokenRequest.refreshToken];

    // check if the refresh token has expired
    if (refreshTokenData.expiresAt < Date.now()) {
      throw new HTTPException(400, {
        res: new Response(
          JSON.stringify({
            error: "invalid_grant",
            error_description: "Refresh token has expired",
          }),
          { headers: { "Content-Type": "application/json" } }
        ),
      });
    }

    // narrow the scope if the client requests a subset
    const requestedScope = Array.isArray(tokenRequest.scope) ? tokenRequest.scope : [];
    const accessScope = requestedScope.length
      ? refreshTokenData.scope.filter((s) => requestedScope.includes(s))
      : refreshTokenData.scope;

    return {
      id: CLIENT.id,
      grants: CLIENT.grants,
      redirectUris: CLIENT.redirectUris,
      scopes: CLIENT.scopes,
      metadata: {
        accessScope,
        userId: refreshTokenData.userId,
        username: USER.username,
        userEmail: USER.email,
        userFullName: USER.fullName,
      },
    };
  }
})

Enter fullscreen mode Exit fullscreen mode

A few things worth noting:

  • Rotation on every use: delete refreshTokenStorage[tokenRequest.refreshToken] runs before the expiry check. This is intentional. A used token is always removed, whether it is valid or not.
  • Scope narrowing: a client may request a subset of the original scopes on renewal (e.g., drop content:write for a read-only operation). If the client sends no scope parameter, the full original scope is preserved.
  • Error format: throwing an HTTPException with a JSON body lets us return the exact invalid_grant error code the OAuth 2 spec requires, without relying on the flow's default error handling. This feels very manual, but it works.

Step 5: Issue a refresh token in generateAccessToken

generateAccessToken is called the first time tokens are issued (right after the authorization code exchange). Update it to conditionally generate and store a refresh token when offline_access is in the granted scope:

.generateAccessToken(async (grantContext) => {
  // ... sign accessToken and idToken as before ...

  // generate the refresh token if the "offline_access" scope was requested,
  // and store it in the refresh token storage with an expiration time
  const refreshToken = (() => {
    if (accessScope.includes("offline_access")) {
      return crypto.randomUUID();
    }
    return undefined;
  })();

  if (refreshToken) {
    refreshTokenStorage[refreshToken] = {
      clientId: grantContext.client.id,
      userId: `${grantContext.client.metadata?.userId}`,
      scope: accessScope,
      expiresAt: Date.now() + 30 * 24 * 3600 * 1000, // 30 days
    };
  }

  // return the refresh token in the token response
  return {
    accessToken,
    scope: accessScope,
    idToken,
    refreshToken, // undefined if offline_access was not requested
  };
})

Enter fullscreen mode Exit fullscreen mode

refreshToken is undefined when offline_access was not in the requested scope. The flow omits undefined fields from the token response, so clients that didn't ask for a refresh token simply won't receive one.


Step 6: Add generateAccessTokenFromRefreshToken

This new callback mirrors generateAccessToken but is called when the grant type is refresh_token. The grantContext is populated from the metadata returned by getClient in Step 4 (the same pattern used for the authorization code grant).

// generate access token from refresh token, reusing the same claims structure
// and signing method as the initial access token
.generateAccessTokenFromRefreshToken(async (grantContext) => {
  const accessScope = Array.isArray(grantContext.client.metadata?.accessScope)
    ? grantContext.client.metadata.accessScope
    : [];

  const registeredClaims = {
    exp: Math.floor(Date.now() / 1000) + grantContext.accessTokenLifetime,
    iat: Math.floor(Date.now() / 1000),
    nbf: Math.floor(Date.now() / 1000),
    iss: grantContext.origin,
    aud: grantContext.client.id,
    jti: crypto.randomUUID(),
    sub: `${grantContext.client.metadata?.userId}`,
  };

  const { token: accessToken } = await jwksAuthority.sign({
    scope: accessScope.join(" "),
    ...registeredClaims,
  });

  const { token: idToken } = await jwksAuthority.sign({
    username: `${grantContext.client.metadata?.username}`,
    name: accessScope.includes("profile")
      ? `${grantContext.client.metadata?.userFullName}`
      : undefined,
    email: accessScope.includes("email")
      ? `${grantContext.client.metadata?.userEmail}`
      : undefined,
    ...registeredClaims,
  });

  // rotate: issue a new refresh token to replace the one consumed in getClient
  const refreshToken = (() => {
    if (accessScope.includes("offline_access")) {
      return crypto.randomUUID();
    }
    return undefined;
  })();

  if (refreshToken) {
    refreshTokenStorage[refreshToken] = {
      clientId: grantContext.client.id,
      userId: `${grantContext.client.metadata?.userId}`,
      scope: accessScope,
      expiresAt: Date.now() + 30 * 24 * 3600 * 1000, // 30 days
    };
  }

  return {
    accessToken,
    scope: accessScope,
    idToken,
    refreshToken,
  };
})

Enter fullscreen mode Exit fullscreen mode

The token-signing logic is identical to generateAccessToken. The only difference is that grantContext.client.metadata was populated from the refresh token data (no nonce because OIDC nonces are one-time values tied to the original authorization request).


How the full flow works

Here is the complete sequence for a client that requests offline_access:

  1. The client redirects the browser to GET /authorize?scope=openid+offline_access+....
  2. The user logs in, sees offline_access on the consent page, and clicks Allow.
  3. The server issues an authorization code and redirects back to the client.
  4. The client POSTs the code to /token → receives access_token, id_token, and refresh_token.
  5. The client stores the refresh token securely.
  6. When the access token expires, the client POSTs to /token with grant_type=refresh_token and the stored refresh_token.
  7. getClient validates the token, rotates it (deletes the old one), and returns the client metadata.
  8. generateAccessTokenFromRefreshToken signs a new access token and a new refresh token.
  9. The client replaces both stored tokens and continues.

OpenID Connect with refresh token grant


Security considerations

  • Token rotation is already implemented: every refresh removes the old token before issuing a new one. If an attacker intercepts and uses a token first, the legitimate client's next attempt will fail with invalid_grant, alerting it that the token may have been stolen.
  • Expiry: refresh tokens are stored with a 30-day TTL. After that, the user must authenticate again.
  • Scope restriction: clients cannot request more scopes on renewal than were originally granted.
  • In production, store refresh tokens in a database with an index on both the token value and (clientId, userId) so you can revoke all tokens for a user (or a specific client) in one query.

What's next

Well, I think I said enough for authorization code flow. Of course, there are many improvements and additional features you could add on top of this basic implementation:

  • Persist clients, users, codes, refresh tokens, and session cookies in a database instead of in-memory objects
  • Add a registration endpoint (POST /register) per RFC 7591
  • etc...

@saurbit/oauth2 also supports other grant types like client_credentials and device_authorization. If you're building a machine-to-machine API, the client credentials grant allows a service to authenticate without a user context. The device authorization grant is perfect for headless clients like smart TVs or CLI apps that can't display a browser for login.

We could go on and on, but I think the core concepts are clear now. You can build on top of this foundation to create a fully featured authorization server that meets your specific needs.

The series won't stop here though. With time, I might add more articles, less focused on the basics (which is why I had to talk about the basics in the first place).

@saurbit/oauth2 can be used with many frameworks and is not tightly coupled to Hono. @saurbit/hono-oauth2 provides a convenient adapter for Hono, but the core logic lives in @saurbit/oauth2 and can be reused across different environments. If you're using Express, Fastify, Oak, or any other JavaScript framework, you can still use the same flow builder and callbacks to implement your authorization server logic. The main difference will be how you integrate the flow into your HTTP routes and middleware. @saurbit/oauth2 expects Web standard API objects so as long as your framework can provide those (or you can adapt them), you can use the same core logic.

Rambling note

I always wanted to touch on the topic of OpenID Connect and OAuth 2.0 servers in JavaScript, and gave up many times because it felt overwhelming. The specs are long and complex, and there are many edge cases and security considerations to cover. I only hope I was able to present the material in a clear and (kind of) approachable way, without oversimplifying the important details. If you have any questions or suggestions for future articles, feel free to reach out! And thank you for reading this far. I hope it was helpful and not too boring.