← All Posts

How to Do OAuth2 Login Flow on Claude Code

Claude Code can scaffold and implement a complete OAuth2 login flow for your application in a single session. Give it your target provider (Google, GitHub, Auth0, etc.), your stack, and a clear prompt, and it will generate the authorization URL builder, callback handler, token exchange logic, and session persistence in one coherent pass. This guide is for developers who want to stop copy-pasting OAuth boilerplate and let Claude Code do the heavy lifting. The trade-off: Claude Code consumes meaningful usage on token-heavy tasks like this, so you will want to keep an eye on your limits before kicking off a long auth implementation session.

  • OAuth2 flows typically involve 4-6 distinct steps (authorization request, redirect, token exchange, token storage, refresh handling), making them ideal for Claude Code's multi-step generation.
  • Claude Code can handle the full flow for major providers: Google, GitHub, Discord, Auth0, Okta, and custom OIDC servers.
  • Usage-heavy tasks like scaffolding auth can consume a significant portion of your Claude Code usage limits — monitor your balance to avoid a mid-task lockout.

What is OAuth2 and why use Claude Code to implement it?

OAuth2 is the industry-standard protocol for delegated authorization. Instead of handling passwords directly, your app redirects users to an authorization server (Google, GitHub, etc.), which issues a short-lived access token after the user consents. The flow has several moving parts: generating a secure state parameter, building the authorization URL, handling the redirect callback, exchanging the authorization code for tokens, and storing/refreshing those tokens safely.

Writing this from scratch is tedious and error-prone. Claude Code can generate all of it correctly the first time, adapting to your stack and provider. It also catches common security mistakes like missing PKCE support or insecure token storage before you ship them.

If you are also building JWT-based session handling on top of OAuth2, see the guide on how to do JWT authentication on Claude Code for the next step.

How to implement an OAuth2 login flow step by step

Step 1: open Claude Code and describe your stack

Start a new Claude Code session in your project directory. Be specific upfront to avoid multiple back-and-forth rounds (each round costs usage tokens):

I'm building a Next.js 14 app with a Node.js API. I need a complete OAuth2 login flow
using GitHub as the provider. Use the authorization code flow with PKCE. Store the
access token in an HttpOnly cookie. Include the /auth/login route, the /auth/callback
route, and a token refresh helper.

The more context you give in the first prompt, the less back-and-forth you will need.

Step 2: provide your environment variables structure

Claude Code will ask for (or infer) the environment variables it needs. Paste your .env.example or tell it the variable names you intend to use:

GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
OAUTH_REDIRECT_URI=http://localhost:3000/auth/callback
SESSION_SECRET=

Claude Code will use these names consistently throughout the generated code. If you need help setting up environment variables with Claude Code, there is a dedicated guide for that too.

Step 3: review the authorization URL builder

Claude Code will generate a function that constructs the provider's authorization URL with the required parameters: client_id, redirect_uri, response_type=code, scope, state, and (if PKCE) code_challenge and code_challenge_method. Review that:

  • The state parameter is cryptographically random (not a static string).
  • For PKCE flows, the code_verifier is stored server-side or in a secure session, not in localStorage.
  • Scopes match what your app actually needs (principle of least privilege).

Step 4: implement the callback handler

The callback route is where most OAuth bugs live. Claude Code will generate a handler that:

  • Validates the returned state against the stored value (CSRF protection).
  • Exchanges the code for an access token via a server-side POST to the provider's token endpoint.
  • Parses the token response and extracts access_token, expires_in, and refresh_token.
  • Sets an HttpOnly, Secure, SameSite cookie (or stores in your session store).

Ask Claude Code to add explicit error handling for error and error_description parameters that providers return on failure — this is easy to miss but critical for debugging.

Step 5: add a token refresh helper

Access tokens expire. Claude Code can generate a refresh helper that checks token expiry before each API call and silently refreshes using the refresh_token if needed. Prompt it with:

Add a withAuth() middleware that checks if the access token is expired and automatically
refreshes it using the refresh_token before passing the request to the handler.

Step 6: test the flow end to end

Ask Claude Code to write integration tests that mock the provider's token endpoint. Claude Code pairs well with tools like Jest for unit testing — you can ask it to generate the full test suite in the same session.

For local testing, use ngrok or a similar tunnel to give GitHub/Google a valid redirect URI pointing to localhost.

Common OAuth2 providers: what to tell Claude Code

ProviderAuthorization URLPKCE supportNotes
GitHubgithub.com/login/oauth/authorizeNo (server-side only)Use user:email scope for email access
Googleaccounts.google.com/o/oauth2/v2/authYesAdd access_type=offline for refresh tokens
Auth0your-tenant.auth0.com/authorizeYesSupports OIDC; ask for openid profile email scope
Discorddiscord.com/api/oauth2/authorizeNoUse identify email scope for user info

Tell Claude Code the exact provider and whether you need a refresh token — this changes the required scopes and authorization URL parameters significantly.

How Claude Code usage limits affect long auth sessions

Implementing a full OAuth2 flow, including the route handlers, middleware, tests, and environment wiring, can be a token-intensive task. If you hit a usage limit mid-session, Claude Code stops responding and you could be locked out for up to 5 hours. This is especially frustrating when you are in the middle of a security-sensitive implementation where partial code is worse than no code.

Before starting an auth implementation session, check your current usage. You can run /usage in Claude Code, visit claude.ai/settings/usage, or use Usagebar for a persistent menu bar view on macOS. Usagebar shows your live usage percentage with smart notifications at 50%, 75%, and 90% of your limit, so you know exactly when to wrap up a session or break the work into smaller chunks. Your API credentials are stored securely in macOS Keychain, not in plain config files.

For more on managing this, see when Claude Code usage resets so you can plan intensive tasks like auth scaffolding around your reset window.

Get Usagebar — instant download, pay what you want (free for students). Never get locked out mid-auth-implementation again.

Tips for reducing token usage during OAuth2 implementation

  • Front-load context: Give Claude Code your full stack, provider, and requirements in the first message. Iterating on misunderstood requirements uses 2-3x the tokens.
  • Break it into phases: Do the authorization URL builder in one session, the callback handler in another. Each focused session is more efficient than one sprawling one.
  • Reuse generated helpers: Once Claude Code has written your token refresh helper, paste it back as context rather than asking it to regenerate. See more strategies in the guide on how to reduce Claude Code token usage.
  • Use slash commands: /clear between major phases resets context and keeps each conversation focused. Check the Claude Code slash commands list for all available shortcuts.

Key takeaways

  1. Give Claude Code your full stack, provider, and security requirements in the first prompt to minimize back-and-forth.
  2. Review the state parameter validation and PKCE implementation carefully — these are the most security-critical parts.
  3. Use PKCE for public clients (SPAs, mobile); server-side client secret for backend-only flows.
  4. Always store tokens in HttpOnly cookies or a server-side session store, never in localStorage.
  5. Check your Claude Code usage before starting — a token-heavy auth session can exhaust your limit mid-task.
  6. Use Usagebar for live usage alerts on macOS so you never hit a 5-hour lockout during critical work.

Sources

Track Your Claude Code Usage

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