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

推荐订阅源

Simon Willison's Weblog
Simon Willison's Weblog
T
Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Engineering at Meta
Engineering at Meta
T
Tenable Blog
C
Cisco Blogs
T
The Blog of Author Tim Ferriss
NISL@THU
NISL@THU
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
P
Privacy & Cybersecurity Law Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
Secure Thoughts
N
News and Events Feed by Topic
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
Microsoft Azure Blog
Microsoft Azure Blog
月光博客
月光博客
H
Hacker News: Front Page
I
InfoQ
L
LangChain Blog
Security Latest
Security Latest
The Cloudflare Blog
Forbes - Security
Forbes - Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Stack Overflow Blog
Stack Overflow Blog
TaoSecurity Blog
TaoSecurity Blog
量子位
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
Visual Studio Blog
Scott Helme
Scott Helme
爱范儿
爱范儿
A
Arctic Wolf
F
Full Disclosure
酷 壳 – CoolShell
酷 壳 – CoolShell
Schneier on Security
Schneier on Security
N
News and Events Feed by Topic
C
CXSECURITY Database RSS Feed - CXSecurity.com
L
LINUX DO - 最新话题
V2EX - 技术
V2EX - 技术
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
The Hacker News
The Hacker News
Hugging Face - Blog
Hugging Face - Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
Know Your Adversary
Know Your Adversary
Application and Cybersecurity Blog
Application and Cybersecurity Blog

Clerk Blog

Going to production with Clerk Deploy Clerk Init: The fastest way to start a new project Introducing Clerk CLI Middleware-based route protection bypass Postmortem: Clerk System Outage (March 10, 2026) Clerk for the AI era Add API Key support to your SaaS in minutes Postmortem: Clerk System Outage (February 19, 2026) Using Clerk in a React Native app Postmortem: DNS Provider Outage (February 10, 2026) How do I implement passkeys in Next.js? Clerk ranked #4 fastest-growing software vendor on Ramp’s December 2025 list How do I handle JWT verification in Next.js? Committing to Agent Identity: Clerk raises $50m Series C from Menlo and Anthropic’s Anthology Fund What is the best way to handle authentication in Next.js App Router? Postmortem: Database Incident (September 14–18, 2025) How do I add authentication to a Next.js app? Introducing Free Trials in Clerk Billing Postmortem: August 28, 2025 - elevated API latency and errors Introducing Mosaic: Bring Your Brand to Every Authentication Flow Multi-tenant authentication: What you need to know (and how Clerk helps) What are the risks and challenges of multi-tenancy? Resilience in Practice: Regional Failover at Clerk Build a Cross-Platform B2B App with Clerk, Expo, and Supabase Highlights from the MiduDev/Clerk Hackathon Add multi-tenancy to an app built with Clerk, Lovable, and Supabase How to build an AI coding rules app with Clerk, Lovable, and Supabase How to Build Multi-Tenant Authentication with Clerk Choosing the right SaaS architecture: Multi-Tenant vs. Single-Tenant Postmortem: June 26, 2025 service outage How to Design a Multi-Tenant SaaS Architecture What is multi-tenancy and why it matters for B2B SaaS How OAuth Works Synchronize user data from Clerk to Supabase Add subscriptions to your SaaS with Clerk Billing Getting started with Clerk Billing Multi-tenant analytics with Tinybird and Clerk How Huntr Migrated 250K Users to Clerk: A Scalable Auth Solution for Startups How to take Clerk to Production How to take your Clerk application to production A practical guide to testing Clerk Next.js applications Implementing multi-tenancy into a Supabase app with Clerk How Clerk integrates with a Next.js application using Supabase How Clerk integrates with Supabase Build a blog with tRPC, Prisma, Next.js and Clerk How to enrich PostHog events with Clerk user data How to build a secure project management platform with Next.js, Clerk, and Neon Validate your SaaS idea while building an audience Postmortem: February 6, 2025 service outage Implement Role-Based Access Control in Next.js 15 Build a Next.js sign-up form with React Hook Form Build a Next.js login page template How to implement Google authentication in Next.js 15 What is middleware in Next.js? How to customize Next.js metadata How to set environment variables in Node.js Building a React Login Page Template How to implement per-user OAuth scopes with Clerk Using Clerk SSO to access Google Calendar and other service data Streamline enterprise customer onboarding with SAML and Clerk Clerk launches EASIE SSO and eliminates SSO fees How to secure Liveblocks Rooms with Clerk in Next.js Securing Node.js Express APIs with Clerk and React Combining the benefits of session tokens and JWTs Build a task manager with Next.js, Supabase, and Clerk Comparing Clerk Webhooks vs Backend API Automate Neon schema changes with Drizzle and GitHub Actions A guide to reading authenticated user data from Clerk Role based access control with Clerk Organizations Mitigating OAuth’s recently discovered Open Response Type vulnerability Per-user B2B monetization with Stripe and Clerk Organizations Build a team-based task manager with Next.js, Neon, and Clerk Building a Hybrid Sign-Up/Subscribe Form with Stripe Elements Welcoming Colin from Zod as our inaugural Open Source Fellow Build a modern authenticated chat application with Next.js, Ably, and Clerk Build a waitlist with Clerk user metadata How to use Clerk with PostHog Identify in Next.js How to secure API Gateway using JWT and Lambda Authorizers with Clerk What are passkeys and how do they work? Comparing Authentication in React.js vs. Next.js How to Add an Onboarding Flow for your Application with Clerk Create Your Own Custom User Menu with Radix - Part 2 Introducing Webhook Workflows with Inngest & Svix Clerk raises $30M Series B from CRV and Stripe Clerk in 2023: A Year in Review Build a Movie Emoji Quiz App with Remix, Fauna, and Clerk Ultimate Guide to Magic Link Authentication Create Your Own Custom User Menu with Radix Introducing has(), protect(), and <Protect> Updated Pricing: 10,000 MAUs Free, and a new “Pro Plan” Next.js Authentication with Clerk: Streamlined SSR Handling Clerk Webhooks: Data Sync with Convex Exploring Clerk Metadata with Stripe Webhooks The Ultimate Guide to Next.js Authentication Empower Your Support Team With User Impersonation Clerk Webhooks: Getting Started A Complete Guide to Session Management in Next.js The Advanced Guide to Passwordless Authentication in Next.js How We Roll – Chapter 10: Roundup How We Roll – Chapter 9: Infrastructure
Adding Clerk auth to your CLI
Railly Hugo · 2026-06-04 · via Clerk Blog

CLI auth usually goes wrong in one of two ways: users paste API keys into config files, or developers invent long-lived tokens that never quite expire.

The better pattern is the one developers already recognize from tools like Vercel, Stripe, Supabase, and GitHub: open the browser, sign in, return to the terminal, and keep the session in the OS keychain. Under the hood, that usually means OAuth 2.0 Authorization Code with Proof Key for Code Exchange (PKCE) and a one-shot localhost callback.

Until now, Clerk's docs haven't laid this pattern out in one place. Last summer, developer Erik Steiger spent three days reverse-engineering the flow to wire Clerk into a Rust CLI. His writeup is excellent, and it exposed a real docs gap.

This post puts the flow in one place with Clerk OAuth primitives you can use today and a small TypeScript implementation you can copy, adapt, or vendor.

Two paths, both valid

When a CLI needs to authenticate a human user through a browser, you have two standard choices:

The right choice depends on where the CLI runs. gh picked device flow because GitHub cares about CI parity; vercel picked localhost callback because their audience is desktop-first.

Clerk's backend already supports everything the localhost-callback flow needs: OAuth Applications with PKCE (S256), authorize + token + userinfo + revoke endpoints, and loopback redirect behavior for 127.0.0.1 callbacks per RFC 8252 §7.3. So that's where we start. (We'll come back to device flow at the end.)

The five moving parts

  1. Generate PKCE + state. code_verifier is generated from 32 random bytes, giving 256 bits of entropy and encoding to a 43-character base64url string; code_challenge = base64url(sha256(verifier)); state is a separate Cross-Site Request Forgery (CSRF) token. A dozen lines of node:crypto.
  2. Spin up the listener. A one-request HTTP server on 127.0.0.1:0 (random port). Use 127.0.0.1 over localhost so the backend doesn't have to resolve DNS weirdness, and over 0.0.0.0 so other hosts on the network can't reach the listener.
  3. Open the browser to {issuer}/oauth/authorize?response_type=code&client_id=…&redirect_uri=http://127.0.0.1:{port}/callback&code_challenge=…&state=…&code_challenge_method=S256. When the callback arrives, validate that state matches the original value before exchanging the code.
  4. Exchange the code with a POST to /oauth/token with grant_type=authorization_code + the code_verifier. You get back access_token, refresh_token, expires_in.
  5. Store the token set in the OS keychain (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux). Fall back to a chmod 600 JSON file if the keychain isn't available.

Setup (one-time)

Before the CLI can start the flow, register an OAuth Application in your Clerk dev instance. The CLI only needs two config values at runtime: the issuer URL and the OAuth application's client_id.

You can create the OAuth application three ways:

  • Clerk Dashboard — In the OAuth Applications page, create an application. Set the redirect URI to http://127.0.0.1/callback, enable public client + PKCE, and request the scopes you need.

  • curl against the Backend API with the instance's secret key, if you prefer scripting setup.

  • The Clerk CLI if you already have it installed:

    terminal

None of these setup paths are required at runtime.

Small enough to audit

The example implementation lives at clerk/cli-auth-example. It's designed to be copied, adapted, or vendored into your own CLI. It is intentionally small and inspectable.

Directory layout:

These are the traps worth handling if you copy the code:

The auth server must respond to the browser before resolving its promise. If the CLI "moves on" to the token exchange before the browser finishes rendering the success page, the user sees a hang. Respond first, then fire your callbacks inside res.end().

Don't hard-code a fixed callback port. Bind to 127.0.0.1:0 and let the OS pick. Register your redirect URI as http://127.0.0.1/callback; at runtime, send the actual http://127.0.0.1:{port}/callback redirect URI. Clerk accepts loopback callbacks with dynamic local ports for this CLI pattern. Fixed ports cause collisions.

Your keychain layer needs a file fallback. Not every environment has a keychain. CI runners, Docker containers, SSH sessions over tmux. @napi-rs/keyring can throw on init. Wrap every get/set/delete in a try/catch that falls back to a chmod 600 JSON file, and log a warning so users know where their credentials actually live.

What this post doesn't cover

Device flow. RFC 8628. Best for CI, headless servers, and environments where the CLI can't open a browser. Outside the scope of this post.

Token refresh semantics. The example refreshes when the access token is within 30s of expiry. That's fine for interactive CLIs but naive for long-running workers. A production implementation should offer configurable skew and retry behavior.

Token revocation on logout. The example clears local credentials. A production SDK should also revoke the refresh token server-side when possible.

Machine-to-machine tokens. Different primitive (machine tokens), different use case (service-to-service, not user auth). Covered separately in the docs.

The next path should be shorter

Adding user auth to a CLI shouldn't be a three-day spike. The building blocks are already in Clerk: OAuth Applications, PKCE, token verification, refresh grants, and machine-to-machine auth.

If your CLI runs on a user's machine, start with localhost callback + PKCE. If it needs headless or CI parity, use device flow when available. Either way, don't make users paste credentials into config files.

The example lives at clerk/cli-auth-example. Fork it, copy it, or just lift the pattern into your own codebase. Credit to Erik Steiger for writing up the gap. The next developer's path should be a lot shorter.

Thoughts, questions? Reach out on X or in the Clerk Discord.