How to Do OAuth Login on Claude Code: A Step-by-Step Guide
In this article
- What is OAuth login and why implement it with Claude Code?
- How to implement OAuth login step by step using Claude Code
- Common OAuth patterns Claude Code handles well
- Security checklist to review after Claude Code scaffolds your OAuth flow
- How to monitor your Claude Code usage while building auth flows
- Key takeaways
- Sources
The fastest way to implement OAuth login with Claude Code is to describe your provider (Google, GitHub, etc.), your stack, and ask Claude Code to scaffold the full flow: authorization URL, redirect handler, token exchange, and session storage. Claude Code handles boilerplate-heavy OAuth flows well, keeping you in flow instead of tab-switching through provider docs. If you're mid-session and near a usage limit, Usagebar shows your Claude Code usage in the macOS menu bar so a 5-hour lockout doesn't catch you off guard during a critical auth refactor.
- OAuth 2.0 flows involve at minimum 4 steps: authorization redirect, callback handling, token exchange, and session persistence
- Claude Code can generate provider-specific boilerplate (PKCE, scopes, state param) in a single prompt when given enough context
- Delegating auth to Claude Code is fastest when you specify framework, provider, and storage layer upfront
What is OAuth login and why implement it with Claude Code?
OAuth 2.0 is the standard authorization framework that lets users log in to your app via a third-party provider (Google, GitHub, Discord, etc.) without handing you their password. The protocol involves several moving parts: constructing an authorization URL, handling a redirect callback, exchanging a temporary code for access and refresh tokens, and storing those tokens securely.
This is exactly the kind of repetitive, spec-driven plumbing that Claude Code handles efficiently. Instead of context-switching between RFC 6749, provider dashboards, and your own codebase, you can describe the integration once and let Claude Code produce a working scaffold that you review and adjust.
How to implement OAuth login step by step using Claude Code
Step 1: set up your OAuth application with the provider
Before writing any code, register your application with the OAuth provider. Each provider has a dashboard for this:
- Google: Google Cloud Console, Credentials
- GitHub: Settings → Developer Settings → OAuth Apps
- Discord: Discord Developer Portal
You'll receive a client_id and client_secret. Set your redirect URI to something like http://localhost:3000/auth/callback for local development. Store both values as environment variables, never hardcoded.
Step 2: prompt Claude Code with your full context
Open Claude Code in your project root and give it a complete, specific prompt. Vague prompts produce generic scaffolds that need heavy editing. A good prompt looks like:
"Add GitHub OAuth login to this Next.js 14 app using the App Router. Use the
next-authlibrary. The callback route should be at/api/auth/[...nextauth]. Store the session in a JWT. I haveGITHUB_CLIENT_IDandGITHUB_CLIENT_SECRETin.env.local."
The more context you give (framework version, library preference, session storage, env var names), the less you'll need to iterate.
Step 3: review the authorization URL construction
Claude Code will generate code that constructs the authorization URL. Review this step carefully. A correct URL includes:
response_type=code(for the Authorization Code flow)client_idfrom your env vars- A
redirect_urimatching exactly what you registered with the provider - A
stateparameter (random, stored in session) to prevent CSRF attacks - Required
scopevalues (e.g.read:user user:emailfor GitHub)
For public clients (SPAs, mobile), Claude Code should also add PKCE: a code_challenge and code_challenge_method=S256. If it doesn't, explicitly ask: "Add PKCE to this flow."
Step 4: handle the callback and token exchange
After the user authorizes, the provider redirects to your callback URL with a code and state parameter. Claude Code will scaffold a handler that:
- Validates the
stateparameter against what was stored in session - POSTs to the provider's token endpoint with
code,client_id,client_secret, andredirect_uri - Receives
access_token,refresh_token, andexpires_in - Fetches the user profile from the provider's userinfo endpoint
- Creates or updates the user record in your database
Token exchange must happen server-side. Never expose your client_secret to the browser. If Claude Code generates a client-side token exchange, flag it immediately: "Move the token exchange to a server route."
Step 5: store tokens and establish a session
How you persist the session depends on your stack:
- Next.js + NextAuth: JWT or database sessions, configured via
session.strategy - Express:
express-sessionwith a secure store (Redis, PostgreSQL) - SvelteKit: Hooks and cookies with
httpOnlyandsameSite=strict
Tell Claude Code your preferred approach. If you want refresh token rotation, say so explicitly: "Handle refresh token rotation and store the new token on each refresh."
Step 6: add a logout route
Logout is often skipped in initial scaffolds. A complete OAuth logout should:
- Clear the server-side session or invalidate the JWT
- Optionally revoke the access token with the provider's revocation endpoint (supported by Google and GitHub)
- Redirect to the home page or a logged-out state
Ask Claude Code: "Add a logout route that clears the session and optionally revokes the GitHub token."
Step 7: test the full flow locally
Run your dev server and walk through the flow manually. Use Claude Code's slash commands like /run to execute tests directly. Common issues to check:
- Redirect URI mismatch (provider rejects callback)
- State parameter not persisting across the redirect (session not configured)
- CORS errors on the token exchange endpoint (should not happen if server-side)
- Missing environment variables at runtime
Common OAuth patterns Claude Code handles well
| Pattern | Prompt tip | Key concern |
|---|---|---|
| Authorization Code + PKCE | Specify "public client" or "SPA" | No client_secret in browser |
| Multiple providers | List all providers upfront | Unified user identity / account linking |
| Refresh token rotation | "Rotate refresh tokens on each use" | Store new token, invalidate old |
| Role-based access after login | "Attach role from DB to session" | Don't trust provider claims for roles |
| Mobile (React Native) | Specify "Expo AuthSession" or deep link scheme | Custom URI scheme for redirect |
Security checklist to review after Claude Code scaffolds your OAuth flow
Claude Code generates correct code in most cases, but always review these security-critical points before shipping:
- State parameter: generated with
crypto.randomBytesor equivalent, validated on callback - PKCE: present for any public client (no server secret)
- Secrets in env vars: no hardcoded
client_secretanywhere in the codebase - Redirect URI validation: provider enforces exact match; your code doesn't dynamically construct it from user input
- Token storage: access tokens in
httpOnlycookies or server-side session, notlocalStorage - HTTPS in production: OAuth providers require HTTPS for production redirect URIs
You can ask Claude Code to audit its own output: "Review this OAuth implementation for OWASP security issues." This often catches subtle problems like open redirects or missing CSRF protection.
How to monitor your Claude Code usage while building auth flows
OAuth implementations are iterative. You'll make several rounds of prompts: initial scaffold, PKCE additions, refresh token handling, security review. Each exchange consumes tokens, and Claude Code usage resets on a 5-hour rolling window. Running out of quota mid-refactor means a forced pause exactly when you're most context-loaded.
Usagebar lives in your macOS menu bar and shows your Claude Code usage in real time, with alerts at 50%, 75%, and 90% so you know when to wrap up a session rather than getting cut off. Credentials are stored in macOS Keychain, and you can check your current usage limits without opening a browser tab. There's also a free tier for students, and a pay-what-you-want model for everyone else.
You can also check usage directly in Claude Code with the /usage command, or by visiting claude.ai/settings/usage.
Get Usagebar and stay in flow through the full OAuth implementation without surprise lockouts.
Key takeaways
- Give Claude Code your full context upfront: provider, framework version, library, session storage strategy
- Always specify PKCE for public clients; Claude Code may not add it by default
- Token exchange must happen server-side, never in the browser
- Validate the
stateparameter on every callback to prevent CSRF - Ask Claude Code to audit its own output for OWASP issues before shipping
- Monitor your Claude Code usage during iterative auth work to avoid mid-session lockouts
Sources
Never Get Locked Out Mid-Task Again
Never hit your usage limits unexpectedly. Usagebar lives in your menu bar and shows your 5-hour and weekly limits at a glance.
Get Usagebar$9 — one-time, lifetime updates