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

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
U
Unit 42
H
Help Net Security
博客园_首页
雷峰网
雷峰网
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - 【当耐特】
Recent Announcements
Recent Announcements
Recorded Future
Recorded Future
aimingoo的专栏
aimingoo的专栏
爱范儿
爱范儿
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
S
Security @ Cisco Blogs
M
MIT News - Artificial intelligence
Cyberwarzone
Cyberwarzone
Cisco Talos Blog
Cisco Talos Blog
Spread Privacy
Spread Privacy
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
K
Kaspersky official blog
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
C
CERT Recently Published Vulnerability Notes
V
Vulnerabilities – Threatpost
WordPress大学
WordPress大学
C
Cisco Blogs
G
Google Developers Blog
N
News and Events Feed by Topic
P
Palo Alto Networks Blog
Apple Machine Learning Research
Apple Machine Learning Research
Schneier on Security
Schneier on Security
博客园 - 聂微东
Security Latest
Security Latest
Security Archives - TechRepublic
Security Archives - TechRepublic
O
OpenAI News
云风的 BLOG
云风的 BLOG
IT之家
IT之家
PCI Perspectives
PCI Perspectives
Microsoft Security Blog
Microsoft Security Blog
NISL@THU
NISL@THU
小众软件
小众软件
Scott Helme
Scott Helme
大猫的无限游戏
大猫的无限游戏
L
LINUX DO - 最新话题
Microsoft Azure Blog
Microsoft Azure Blog
Simon Willison's Weblog
Simon Willison's Weblog
N
News and Events Feed by Topic
F
Fortinet All Blogs
The Last Watchdog
The Last Watchdog

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
Google OAuth 2.0 PKCE flow in a React/Next.js app — no backend, no client secret
Deeshan Shar · 2026-05-05 · via DEV Community

If you've tried to add Google OAuth to a SPA or a Next.js app, you've probably run into the same friction: Google's documentation is comprehensive but dense, most tutorials are incomplete, and the parts that matter most — like exactly why you need PKCE, or what access_type=offline actually does — are buried.

This is the walkthrough I wish had existed when I built the auth layer for OvertimeIQ.

By the end you'll understand:

  • Why PKCE exists and why it's the correct flow for SPAs
  • How to implement the full code exchange from scratch (no OAuth libraries)
  • How to get a refresh_token (most tutorials quietly skip this)
  • How to do silent token refresh mid-session without any UI
  • How to feed the Google id_token into Supabase for a second independent auth session

Why PKCE, and why not the alternatives

The implicit flow (the original OAuth approach for SPAs) returned the access token directly in the URL fragment after redirect. This has a known problem: browser history, referrer headers, and intermediate servers can all see that token. It's deprecated by the OAuth Security BCP. Don't use it.

Authorization code flow without PKCE requires a client secret — a value that must stay secret. In a server application, this is fine. In a SPA, there is no place to put a secret. It ships in your JavaScript bundle, which any user can read. This makes the "secret" worthless.

PKCE (Proof Key for Code Exchange) was designed specifically for this scenario. Instead of a static secret, you generate a fresh random value for every authorization request, derive a challenge from it, and prove you hold the original value when you exchange the code. There's nothing static to leak.


The PKCE flow, step by step

Here's what actually happens:

Browser                                    Google
  |                                           |
  |-- (1) Generate code_verifier -----------> |
  |-- (2) Derive code_challenge               |
  |-- (3) Redirect to Google auth URL ------> |
  |                   <-- (4) User consents --|
  |<-- (5) Redirect with code --------------- |
  |-- (6) Exchange code + verifier ---------> |
  |<-- (7) Receive tokens ------------------- |

Enter fullscreen mode Exit fullscreen mode

The code_verifier is a random string you generate in the browser and store in sessionStorage. The code_challenge is base64url(SHA256(verifier)) — a hash you can send to Google without revealing the original. When you exchange the code in Step 6, you send the original verifier. Google hashes it and verifies it matches what you sent in Step 3. An intercepted authorization code is useless without the verifier.


Implementation

Step 1: Generate the code verifier and challenge

// lib/auth.js

function generateRandomString(length) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
  const array = new Uint8Array(length)
  crypto.getRandomValues(array)
  return Array.from(array).map(byte => chars[byte % chars.length]).join('')
}

export function generateVerifier() {
  return generateRandomString(64) // Must be 43–128 chars
}

export async function generateChallenge(verifier) {
  const encoder = new TextEncoder()
  const data = encoder.encode(verifier)
  const digest = await crypto.subtle.digest('SHA-256', data)

  // base64url encode (different from regular base64 — no +, /, or = chars)
  return btoa(String.fromCharCode(...new Uint8Array(digest)))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '')
}

Enter fullscreen mode Exit fullscreen mode

Step 2: Build the authorization URL

export async function buildAuthURL() {
  const verifier = generateVerifier()
  const challenge = await generateChallenge(verifier)

  // Store verifier for later — must survive the redirect
  sessionStorage.setItem('pkce_verifier', verifier)

  const params = new URLSearchParams({
    client_id: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
    redirect_uri: `${window.location.origin}/auth/callback`,
    response_type: 'code',
    scope: 'openid email profile https://www.googleapis.com/auth/drive.file',
    code_challenge: challenge,
    code_challenge_method: 'S256',
    access_type: 'offline',    // ← Required to receive a refresh_token
    prompt: 'consent',         // ← Required to actually receive the refresh_token (see below)
    login_hint: invitedEmail,  // ← Optional: pre-fills the email field
  })

  return `https://accounts.google.com/o/oauth2/v2/auth?${params}`
}

Enter fullscreen mode Exit fullscreen mode

Critical: access_type=offline and prompt=consent

This is where most tutorials go wrong. access_type=offline tells Google you want a refresh token. But Google won't issue a new refresh token if the user has already authorized your app previously — it caches the consent. prompt=consent forces the consent screen to appear every time, which guarantees a fresh refresh token on every login.

If you omit either parameter, you'll get an access token (valid for ~1 hour) and nothing else. Your app will break when the token expires.

The downside: users see the Google consent screen on every login, even if they've used the app before. For most use cases, this is acceptable. For OvertimeIQ specifically, Drive access is central enough to the product that re-confirming consent feels appropriate rather than annoying.

Step 3: Handle the callback

After the user consents, Google redirects to /auth/callback?code=AUTHORIZATION_CODE. You exchange this code for tokens server-side. Even in a mostly client-side app, do this step on the server — the code exchange reveals your client ID and your verifier, and you want to receive the tokens in a server response, not a URL fragment.

In a Next.js app:

// app/auth/callback/route.js

import { NextResponse } from 'next/server'

export async function GET(request) {
  const { searchParams } = new URL(request.url)
  const code = searchParams.get('code')
  const error = searchParams.get('error')

  if (error || !code) {
    return NextResponse.redirect(new URL('/auth-error', request.url))
  }

  // Get the verifier from the cookie (set during the redirect step)
  // We'll cover how to pass this from browser to server below
  const verifier = request.cookies.get('pkce_verifier')?.value

  if (!verifier) {
    return NextResponse.redirect(new URL('/auth-error', request.url))
  }

  const tokens = await exchangeCode(code, verifier, request)

  // Clean up the verifier cookie
  const response = NextResponse.redirect(new URL('/log', request.url))
  response.cookies.delete('pkce_verifier')

  // Store the access_token in a session cookie (short-lived)
  response.cookies.set('g_access_token', tokens.access_token, {
    httpOnly: true,
    secure: true,
    maxAge: 3600
  })

  // The refresh_token and id_token need further handling — see below
  return response
}

async function exchangeCode(code, verifier, request) {
  const response = await fetch('https://oauth2.googleapis.com/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      code,
      client_id: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
      client_secret: process.env.GOOGLE_CLIENT_SECRET, // Used server-side only
      redirect_uri: `${new URL(request.url).origin}/auth/callback`,
      grant_type: 'authorization_code',
      code_verifier: verifier,
    })
  })

  if (!response.ok) throw new Error('Token exchange failed')
  return response.json()
  // Returns: { access_token, refresh_token, id_token, expires_in, token_type }
}

Enter fullscreen mode Exit fullscreen mode

Passing the verifier from browser to server callback: The verifier is generated in the browser, but the callback happens on the server. The cleanest approach is to store the verifier in a cookie before the redirect:

// In your sign-in button handler
export async function startSignIn() {
  const verifier = generateVerifier()
  const challenge = await generateChallenge(verifier)

  // Set as a cookie so the server callback can read it
  document.cookie = `pkce_verifier=${verifier}; path=/; secure; samesite=lax; max-age=300`

  const authUrl = await buildAuthURL(verifier, challenge)
  window.location.href = authUrl
}

Enter fullscreen mode Exit fullscreen mode


The three tokens and what to do with each

After a successful exchange, you have three tokens:

access_token — Use this for all API calls (Google Drive, Google user info). Valid for ~1 hour. Store in sessionStorage or memory — never in localStorage (it's short-lived, and localStorage survives browser restarts). In an SSR app, an httpOnly cookie is the cleanest option.

refresh_token — Use this to get new access tokens when the current one expires. This is long-lived (until the user revokes access). For OvertimeIQ, I store it in the SQLite database on the user's Google Drive — it's as private as the rest of their data, and it never leaves their device or Drive storage.

id_token — A JWT containing the user's Google identity (sub, email, name, picture). Use this to bootstrap a Supabase session (see below), then discard it. It doesn't need to be persisted.


Feeding the id_token to Supabase

If you're using Supabase alongside Google OAuth (as OvertimeIQ does), you can use the Google id_token to create a Supabase session without running a separate OAuth flow:

import { createClient } from '@supabase/supabase-js'

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
)

// After token exchange — pass the id_token to Supabase
const { data, error } = await supabase.auth.signInWithIdToken({
  provider: 'google',
  token: googleIdToken,
})

Enter fullscreen mode Exit fullscreen mode

This creates a Supabase session for the user. From this point, you have two independent auth lifecycles:

  • Google OAuth manages Drive access (via access_token + refresh_token)
  • Supabase Auth manages app identity (user profile, subscription state, invite status) The two never need to communicate again after the initial bootstrap. If the Supabase session expires, the user re-logs in through the same Google flow that refreshes both.

Silent token refresh

The access token expires in one hour. You need to refresh it transparently, without interrupting the user.

// lib/auth.js

export async function refreshAccessToken() {
  // Read the refresh token from SQLite settings
  const refreshToken = db.getOne(
    'SELECT google_refresh_token FROM settings WHERE id = 1'
  )?.google_refresh_token

  if (!refreshToken) {
    // No refresh token — user needs to sign in again
    redirectToSignIn()
    return null
  }

  const response = await fetch('https://oauth2.googleapis.com/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      refresh_token: refreshToken,
      client_id: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
      grant_type: 'refresh_token',
    })
  })

  if (!response.ok) {
    // Refresh token revoked — show reconnect banner, don't break the app
    showReconnectBanner()
    return null
  }

  const { access_token } = await response.json()

  // Store in memory (or sessionStorage) for Drive calls
  setAccessToken(access_token)

  return access_token
}

Enter fullscreen mode Exit fullscreen mode

Schedule this to run ~55 minutes after login (5 minutes before the 1-hour expiry), and also intercept any Drive API 401 response as a signal to refresh immediately:

async function driveApiCall(url, options) {
  let accessToken = getAccessToken()

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

  if (response.status === 401) {
    // Token expired — try to refresh
    accessToken = await refreshAccessToken()
    if (!accessToken) return null // Couldn't refresh, user needs to reconnect

    // Retry the original request with the new token
    response = await fetch(url, {
      ...options,
      headers: { ...options.headers, Authorization: `Bearer ${accessToken}` }
    })
  }

  return response
}

Enter fullscreen mode Exit fullscreen mode

If the refresh fails (user revoked access, network offline), show a persistent "Reconnect to Drive" banner. The app should remain fully usable — all data is in localStorage/SQLite, all features that don't need Drive continue to work. The banner gives the user a path back without breaking their workflow.


The login_hint trick

If you know in advance which email the user should be signing in with — for example, an invite system where you've emailed a specific address — you can pre-fill the Google consent screen:

const params = new URLSearchParams({
  // ... other params
  login_hint: 'invited-user@gmail.com'
})

Enter fullscreen mode Exit fullscreen mode

This doesn't lock the user into that email — Google still lets them choose a different account — but it surfaces the correct account first. For an invite-only app, this significantly reduces the chance of a user signing in with the wrong Google account and then wondering why their invite doesn't work.


Common mistakes

Missing access_type=offline: You'll get an access token, no refresh token. Your app breaks after 1 hour.

Missing prompt=consent: You'll get a refresh token on the first login but not on subsequent logins (Google caches the consent). If a user signs out and signs back in, they lose the ability to silently refresh tokens.

Storing the access token in localStorage: It's short-lived, so there's minimal security benefit to persisting it across sessions. sessionStorage or memory is fine. If you need it to survive page refreshes, store the refresh token instead and get a fresh access token on load.

Validating the id_token client-side: You can decode a JWT without verification (base64 decode the payload), but you shouldn't trust it for access control without verifying the signature. Use Supabase's signInWithIdToken or Google's tokeninfo endpoint for validation.

Using the client secret in frontend code: The PKCE flow doesn't require a client secret. If you're adding one to your client-side code, you're either using the wrong flow or exposing something you shouldn't.


The scope choice

I'm using https://www.googleapis.com/auth/drive.file — the scope that grants access only to files created by this specific app. It cannot read or modify any other files in the user's Drive.

For most personal data applications, this is the right choice. It's the minimal permission footprint, it's easier to explain to users ("this app can only access files it created"), and it passes Google's app verification requirements more easily than broader scopes.

The alternative — https://www.googleapis.com/auth/drive — gives full Drive access. Don't use it unless you genuinely need it. Most apps don't.


This is part of an ongoing series on building OvertimeIQ — a personal overtime tracker where your data lives on your own Google Drive. The previous article in the series covers the SQLite-in-browser setup and Google Drive sync in detail. The first article covers the overall architecture.