How OAuth 2.0 works: authorization code flow and PKCE

By

Updated

Tagged: Networking

Learn how OAuth 2.0 authorization code flow, PKCE, state, scopes, access tokens, OpenID Connect, sessions, and social login work in practice.

You click “Continue with GitHub” on a site you’ve never visited before. GitHub asks if you want to approve the app, you click a button, and a second later you’re back on the site, logged in.

You didn’t type your GitHub password into that site, the site didn’t have to build GitHub’s login form, and GitHub didn’t hand over the keys to your whole account. OAuth handles all of that with two redirects in the browser and a handful of short-lived values passed between the browser, your app, and the provider.

In this tutorial, we’ll walk through the whole flow step by step. We’ll use GitHub as our concrete example, compare it with Google’s setup, add the security checks a modern app needs, and wrap up with how I use OAuth in my own projects. Here’s how the pieces move from start to finish:

Continue with GitHubStart loginRedirect to GitHubAuthorize requestLog in and approveRedirect with codeCallback with codeCode + PKCE verifierAccess tokenRequest profileGitHub userSession cookieUserBrowserYour applicationGitHubUserBrowserYour applicationGitHub

What OAuth is

OAuth 2.0 is an authorization framework that lets one app get limited access to resources living on another service, without asking the user for their password.

Think of a photo-printing app. It only needs permission to read a few photos from your cloud storage, not your password, your billing settings, or permission to delete files. OAuth solves this by giving the app a token scoped to just those permissions.

The original OAuth 2.0 spec is RFC 6749, and the current security guidance lives in RFC 9700, published in 2025. If you’re building an OAuth integration today, you want to follow both.

OAuth is not authentication

OAuth answers one specific question:

May this application access this resource?

Authentication answers a different one:

Who is this user?

Even so, lots of apps use OAuth for login. They grab an access token, call the provider’s profile endpoint, and treat the returned user ID as the person’s identity. That’s how GitHub OAuth login usually works.

Google login normally uses OpenID Connect (OIDC) instead, which puts a proper identity layer on top of OAuth 2.0 and sends back a signed ID token with identity claims. Whenever you’re building login and the provider supports OpenID Connect, go with OIDC rather than piecing together an identity from raw OAuth API responses.

The five actors

OAuth specs and docs use five specific names for the parts involved. Once you know what each one means, reading provider documentation gets much easier.

Resource owner

The resource owner is the person who owns the account and approves access. In our example, that’s you.

Client

The client is the application asking for access. This trips people up at first because “client” here means your app (including a server-rendered web app), not the user’s browser.

Authorization server

The authorization server handles logging the user in, asking for their consent, and issuing codes and tokens. With GitHub OAuth, GitHub plays this role.

Resource server

The resource server is the API holding the protected data. GitHub’s REST API, which takes your access token and hands back the user’s profile, is the resource server. Even when the same company runs both the authorization server and the resource server, they’re separate roles in the protocol.

User agent

The user agent is usually the browser. It follows the redirects between your app and the authorization server and carries the authorization code back, while your server-side app handles the token exchange behind the scenes.

Here’s how those five actors fit together in a login flow:

Resource ownerBrowserOAuth clientAuthorization serverResource server

Register the application first

Before a provider will talk to your app, you have to register it in their developer settings. They’ll give you a client ID, and if you’re running a confidential server-side app, a client secret too.

The client ID is public and just identifies your app, so it’s completely fine for it to show up in an authorization URL. The client secret is a real credential. Keep it on your server or in your hosting platform’s secret store, and never put it in frontend JavaScript, a mobile binary, a public repo, or a URL.

During registration, you also set one or more allowed callback URLs, like this:

https://app.flaviocopes.com/auth/github/callback

When a login starts, the provider checks the callback URL you send against the list you registered. Current OAuth guidance requires exact string matching (aside from a small localhost exception for native apps), which stops an attacker from swapping in their own URL and intercepting the authorization code.

Public and confidential clients

A confidential client is an app that can safely hold a secret, like a traditional web app running on a backend you control.

A public client can’t keep a secret at all. Browser-only apps, desktop apps, and mobile apps ship their code directly to the user’s device, where anyone can inspect it and pull out any embedded string, even if you name the variable CLIENT_SECRET.

Instead of pretending they can hide a shared secret, public clients rely on PKCE. Modern confidential clients should use PKCE as well.

The authorization code flow

The authorization code flow splits the browser redirects from the token exchange. The browser only ever sees a short-lived authorization code, while your server fetches the access token directly from the authorization server. That way, the token stays out of callback URLs and browser history.

Here are the eight stages in order:

  1. Your app creates a login transaction.
  2. The browser redirects to the provider’s authorization endpoint.
  3. The user signs in and approves access.
  4. The provider redirects the browser back to your callback URL with a code.
  5. Your app validates the transaction.
  6. Your app exchanges the code for tokens on the server.
  7. Your app calls the resource server using the access token.
  8. Your app creates its own local session for the user.

Create state and PKCE values

Before you send the browser off to the provider, generate three values:

  • state, which ties the upcoming callback to this specific browser session
  • code_verifier, a high-entropy random secret for this login attempt
  • code_challenge, the SHA-256 digest of that verifier

Save state and code_verifier in a short-lived server session or a protected cookie. Here’s how you can generate them using the Web Crypto API:

function randomBase64Url(bytes = 32) {
  const data = crypto.getRandomValues(new Uint8Array(bytes))
  const binary = String.fromCharCode(...data)

  return btoa(binary)
    .replaceAll('+', '-')
    .replaceAll('/', '_')
    .replaceAll('=', '')
}

async function sha256Base64Url(value) {
  const data = new TextEncoder().encode(value)
  const digest = await crypto.subtle.digest('SHA-256', data)
  const binary = String.fromCharCode(...new Uint8Array(digest))

  return btoa(binary)
    .replaceAll('+', '-')
    .replaceAll('/', '_')
    .replaceAll('=', '')
}

const state = randomBase64Url()
const codeVerifier = randomBase64Url(64)
const codeChallenge = await sha256Base64Url(codeVerifier)

Always use a cryptographically secure random generator here, never Math.random(). RFC 9700 requires PKCE for public clients and recommends it for confidential clients too, using the S256 challenge method.

Redirect the browser to GitHub

GitHub’s authorization endpoint is:

https://github.com/login/oauth/authorize

Build the redirect URL with URL and URLSearchParams so you don’t run into string-escaping bugs:

const authorizeUrl = new URL(
  'https://github.com/login/oauth/authorize',
)

authorizeUrl.search = new URLSearchParams({
  client_id: env.GITHUB_CLIENT_ID,
  redirect_uri: 'https://app.flaviocopes.com/auth/github/callback',
  scope: 'read:user user:email',
  state,
  code_challenge: codeChallenge,
  code_challenge_method: 'S256',
}).toString()

return Response.redirect(authorizeUrl, 302)

Once you redirect there, the browser leaves your app and lands on GitHub. Here’s what each query parameter does:

  • client_id identifies your registered app
  • redirect_uri tells GitHub where to send the browser afterward
  • scope lists the permissions you’re asking for
  • state ties the callback response back to this login transaction
  • code_challenge locks the future code exchange to your code_verifier
  • code_challenge_method tells GitHub how you hashed the challenge

Make sure your client secret never ends up in this URL.

The provider authenticates the user

Now GitHub is in charge of the screen. If the user isn’t logged in yet, GitHub signs them in (including any MFA or passkey checks) entirely on GitHub’s own origin, so your app never touches their credentials.

Next, GitHub shows the permissions your app asked for and lets the user approve or deny them. Keep in mind that signing in and granting consent happen separately, so a user who is already logged into GitHub can still get a prompt when you ask for a new scope.

The callback contains a code

Once the user clicks approve, GitHub redirects the browser back to your registered callback URL:

https://app.flaviocopes.com/auth/github/callback?code=abc123&state=xyz789

That code parameter isn’t an access token yet. It’s a short-lived, single-use value locked to your client ID and redirect URI, and the authorization server will reject it if anyone tries to exchange it twice.

If the user clicks cancel or denies permission, GitHub still redirects back to your callback, just with an error instead of a code:

https://app.flaviocopes.com/auth/github/callback?error=access_denied&state=xyz789

Treat cancellation as a normal user choice and send them back to your login page cleanly, rather than throwing a 500 error.

Validate the callback before exchanging anything

Before you touch the token endpoint, your callback handler needs to verify the login transaction and reject anything that looks off. Check five things:

  1. state is present in the callback.
  2. It matches the stored value character for character.
  3. The transaction hasn’t expired.
  4. It hasn’t been used before.
  5. The callback includes a code and no error from the provider.

Use a timing-safe comparison if your runtime has one, and make sure the stored state is high-entropy, short-lived, and single-use. As soon as validation passes, delete the stored transaction so hitting refresh in the browser can’t replay the login. Here’s how that check looks in code:

yesnonoyesOAuth callbackProvider error?Show a safe loginmessageState matchesunused transaction?Reject callbackExchange code withverifier

Exchange the code for an access token

With the callback validated, your server makes a direct POST request to GitHub’s token endpoint:

https://github.com/login/oauth/access_token

Here’s what that request looks like in practice:

const tokenResponse = await fetch(
  'https://github.com/login/oauth/access_token',
  {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      client_id: env.GITHUB_CLIENT_ID,
      client_secret: env.GITHUB_CLIENT_SECRET,
      code,
      redirect_uri: 'https://app.flaviocopes.com/auth/github/callback',
      code_verifier: storedCodeVerifier,
    }),
  },
)

Always check the HTTP status before you try to pull the token out of the response:

if (!tokenResponse.ok) {
  throw new Error('GitHub token exchange failed')
}

const token = await tokenResponse.json()

A successful response gives you the access token, its token type, and the granted scope. Don’t log that response body, and keep the access token out of your analytics and error tracker.

PKCE comes into play right here. The authorization server hashes the code_verifier you sent and checks it against the code_challenge from the initial redirect, so a stolen authorization code can’t be exchanged without the verifier.

Call the protected API

Now your server can call GitHub’s resource server to fetch the user’s profile:

const profileResponse = await fetch(
  'https://api.github.com/user',
  {
    headers: {
      Accept: 'application/vnd.github+json',
      Authorization: `Bearer ${token.access_token}`,
      'X-GitHub-Api-Version': '2022-11-28',
    },
  },
)

Send the token in the Authorization header, never in a query string where it can end up in browser history, server logs, referrer headers, screenshots, or monitoring tools.

GitHub’s profile response includes a stable numeric ID. Store the provider name together with that ID as your external account key, because people change usernames all the time and you don’t want a rename to break their login.

Create your own session

OAuth doesn’t log the user into your app on its own. Your backend still has to take over and do five things:

  1. Find an existing local user or create a new one.
  2. Link the GitHub account to that user record.
  3. Create a session in your app.
  4. Set a secure session cookie.
  5. Redirect the browser to wherever the user was heading.

Here’s how that final step looks:

Provider profileLinked accountLocal userApplication sessionSecure cookie

Notice that the browser gets your own session ID, not GitHub’s access token. Set the cookie with HttpOnly, Secure, and an appropriate SameSite attribute, and rotate the session ID when login finishes to block session fixation.

OAuth tokens and application sessions are different

It helps to keep two concepts separate in your head and in your database schema: an access token authorizes API calls to the provider’s resource server, while an application session authenticates requests to your own app.

They expire and get revoked on different schedules. When someone logs out of your app, their GitHub authorization might still be active. Flip it around, and if they revoke your app inside GitHub’s settings, your local sessions won’t automatically disappear unless you check for that and invalidate them yourself.

Google login and OpenID Connect

Google follows the same authorization code flow, except for login you normally request OpenID Connect scopes:

openid email profile

Google’s authorization endpoint is:

https://accounts.google.com/o/oauth2/v2/auth

And the token endpoint is:

https://oauth2.googleapis.com/token

When you exchange the code, Google sends back both an access token and an ID token, which is a signed JWT carrying claims like:

  • iss, the issuer
  • sub, the stable Google account ID
  • aud, the intended client
  • exp, the expiration timestamp
  • email and email_verified, when you’ve requested them

Don’t just base64-decode the JWT and trust the JSON inside. You need to verify the signature, issuer, audience, expiration, and nonce (when you use one). In practice, reach for a maintained OpenID Connect library so key discovery and key rotation are handled for you.

Access tokens, ID tokens, and refresh tokens

It’s easy to mix up the different tokens involved in OAuth, especially once OpenID Connect and your own app sessions enter the picture. Each one is meant for a different recipient and does a specific job:

TokenAudiencePurpose
Access tokenResource serverAuthorize API requests
ID tokenOAuth clientDescribe an authenticated identity
Refresh tokenAuthorization serverRequest a new access token
Session tokenYour applicationAuthenticate local requests

Keep their roles separate. Use an ID token to read who logged in, never as a credential to call an API. Likewise, treat an access token as a key for the resource server, not as identity proof for your client, unless the provider explicitly specifies that format and you validate every claim for your app.

Refresh tokens deserve extra care because they live much longer than access tokens. Store them encrypted or inside a protected server-side credential store. On public clients, follow current guidance and use sender-constrained refresh tokens or refresh token rotation that detects replay. Only ask for offline access if your app genuinely needs to act on the user’s behalf after they close the browser.

Scopes and least privilege

A scope is a permission your app asks the provider to grant. For basic GitHub login, read:user gets you profile data and user:email lets you read private email addresses. Asking for a broad scope like repo gives your app heavy access to someone’s repositories, which makes no sense for a plain login button and will make careful users back out.

Ask only for what you need right now. If a feature down the road needs extra permissions, prompt for them when the user turns that feature on. That pattern is called incremental authorization.

Keep scopes separate from your app’s own permissions too. A GitHub scope tells you what you can do against GitHub’s API, while your own database stays in charge of who is a regular member or an admin inside your app.

What state protects

The state parameter ties the incoming callback back to the exact browser that started the login. Without that check, an attacker can begin an OAuth flow with their own provider account and trick a victim’s browser into loading the attacker’s callback URL, which can end up linking the victim’s session to the attacker’s account.

Generate a fresh random state for every login attempt, tie it to the browser session, give it a short lifetime, and delete it as soon as it’s checked. Don’t stuff unsigned redirect data into state either. If you want to send the user back to /dashboard after login, save that path on the server alongside the login transaction and restrict it to local destinations.

What PKCE protects

PKCE ties the initial authorization request to the final token exchange. Your client generates a secret verifier, sends only its derived challenge through the browser, and holds onto the original verifier until the callback arrives:

Create verifierSHA-256 →challengeRedirect withchallengeAuthorizationrequestRedirect with codeCodeCode + verifierHash verifier andcompareTokenClientBrowserProviderClientBrowserProvider

Because the provider checks that the verifier matches the original challenge, someone who only intercepts the authorization code can’t swap it for a token. Pair PKCE with exact redirect URIs, secure token storage, strict issuer checks, and solid session handling so the rest of the flow is covered too.

Flows you should avoid

OAuth 2.0 shipped with several grant types that you shouldn’t pick for a new app today.

Implicit grant

The implicit grant hands the access token straight back in the browser redirect, which exposes it in URLs, browser history, and any script running on the page. RFC 9700 recommends using the authorization code flow instead, and Google strongly discourages any response type that puts access tokens in URLs.

Resource owner password credentials

With this grant, your app asks the user directly for their provider username and password. That breaks the whole boundary OAuth exists to create, and it falls apart as soon as a provider uses MFA, passkeys, federation, or updated login policies. Current security guidance says not to use it at all.

Client credentials for user login

The client credentials grant authenticates an application acting on its own behalf, with no user consent and no user identity attached. It’s built for machine-to-machine API calls, not for a “Sign in with GitHub” button.

Common security mistakes

Loose redirect URI matching

Register exact callback URLs with your provider and check them strictly. Skip wildcard subdomains, prefix matching, and arbitrary query parameters in redirect URIs.

Reusing state or PKCE values

Start a fresh transaction for every login attempt. Making state and PKCE values single-use lets you spot and block replay attempts immediately.

Putting secrets in the frontend

Single-page apps, desktop apps, and mobile apps are all public clients because users can inspect the code or binary. Use the authorization code flow with PKCE and leave the client secret out of anything you ship to a device.

Logging codes and tokens

Scrub authorization headers, callback query strings, token responses, cookies, and raw provider error payloads before they ever hit your logs. Otherwise a leaked log file turns into live credentials.

Trusting email as the only account key

People change their email addresses, and not every provider verifies every address it returns. Key external accounts on the pair of issuer/provider plus the provider’s stable subject identifier instead.

Automatically linking matching emails

Even if two providers return the same email address, one of them might not have verified it or the address might have been recycled. For sensitive apps, ask the user to sign in first or go through an explicit verified linking step before merging accounts.

Open redirects after login

Never bounce a user to an arbitrary next URL coming from the browser. Restrict post-login redirects to local paths or a short, explicit allowlist of destinations you control.

Treating denial as an internal error

Users hit “Cancel” on consent screens all the time, so treat that as a normal branch rather than a 500 error. Send them back to the login page with a plain message and keep raw provider error details out of the UI.

How I use OAuth

In my own apps, I let a maintained authentication library handle the OAuth plumbing rather than writing the protocol code by hand.

For example, I built an Astro app running on Cloudflare Workers with Better Auth, D1, and Drizzle. On the server, I register GitHub as a social provider like this:

socialProviders: {
  github: {
    clientId: env.GITHUB_CLIENT_ID,
    clientSecret: env.GITHUB_CLIENT_SECRET,
  },
}

When someone clicks the login button, the form posts to an Astro endpoint. In Astro 7 that’s still a plain POST handler returning a standard Response, which asks Better Auth for the GitHub authorization URL and redirects the browser there:

const { url } = await auth.api.signInSocial({
  body: {
    provider: 'github',
    callbackURL: '/dashboard',
  },
  headers: request.headers,
})

return Response.redirect(url, 302)

Better Auth takes care of state, callbacks, token exchange, linked accounts, and sessions, so my own code only needs to decide where to send the user after login (the dashboard).

I’ve used the same setup in a React and Supabase project too. There, the frontend called signInWithOAuth() with GitHub and a callback URL, and Supabase handled the authentication layer and gave back the app session. The libraries and wiring look different on the surface, while the underlying OAuth flow stays the same.

Even when a library does the heavy lifting, knowing how OAuth works saves a lot of debugging time when a callback breaks, because each failure points to a specific part of the flow:

  • Provider rejects the first redirect: check your client ID, scope, or redirect URI.
  • Callback state fails: check the transaction cookie, hostname, SameSite, or a replayed request.
  • Token exchange fails: check the code, verifier, client secret, or redirect URI.
  • Provider profile fails: check the token, scope, audience, or the provider’s API policy.
  • App session disappears: check cookie forwarding or your session configuration.

If you want to see the full project setup, check out my Better Auth on Astro and Cloudflare tutorial.

When I would not use social login

Social login always ties your sign-in experience to an outside provider, and sometimes that trade-off isn’t worth it.

If your audience doesn’t live on GitHub, don’t make GitHub the only way in. Same with Google-only login when your users care about account portability and don’t want their access tied to one company. And never ask for heavy scopes like repository or calendar access just to avoid building a standard login screen.

Depending on who you’re building for, email magic links, passkeys, or plain email and password can be a much better fit. Internal company tools are the opposite case: plugging into the organization’s OpenID Connect provider is usually the cleanest option because IT keeps account offboarding and MFA policy in one place.

Debug the flow one boundary at a time

OAuth bugs feel chaotic until you isolate which boundary failed. Walk through the flow in order instead of guessing.

Inspect the authorization request

Open DevTools and inspect the full URL your app sends to the provider. Verify the exact client ID, redirect URI, scope, state, and PKCE challenge. Just be careful not to paste a live authorization URL into a public issue tracker, since it carries live transaction parameters.

Inspect the callback

Look at the query string coming back from the provider to see whether you got a code or an error. Before your server does any other work, verify that the returned state matches the active transaction.

Inspect the server-side exchange

When the token request fails, log only the HTTP status, the provider’s error code, and a request correlation ID. Keep the authorization code, PKCE verifier, client secret, and returned tokens out of your logs.

Inspect cookies

Check the cookie’s domain, path, Secure, HttpOnly, SameSite, and expiration settings. A completely valid OAuth exchange followed by a dropped or mismatched cookie looks identical to a failed login from the user’s side.

Store the provider name, the provider’s account ID, and your local user ID in separate columns, and put a unique constraint on the provider and provider account ID pair so repeated callbacks can’t create duplicate links.

Test the unhappy paths

Seeing the login button work once on your laptop isn’t enough to trust an OAuth integration. Make sure you test the failure cases too:

  • user denies consent
  • callback has the wrong state
  • authorization code is reused
  • transaction expires
  • PKCE verifier is missing or wrong
  • provider returns an email without verification
  • linked local account already exists
  • session cookie cannot be set
  • provider API is unavailable
  • requested scope is not granted
  • post-login destination is external

In your automated test suite, mock the provider boundary so these cases run fast and reliably. When it’s practical, keep one real end-to-end test pointing at a dedicated test application on the provider’s side, and never point tests at production client secrets or real customer accounts.

The mental model to keep

At a high level, the flow breaks down into a few clear handoffs. OAuth delegates authorization by sending the user’s browser to the provider and bringing back a short-lived code. Your server checks the transaction and trades that code for tokens, while PKCE proves the server exchanging the code is the same client that started the request. From there, the access token talks to the provider’s API, OpenID Connect gives you a signed ID token when you need user identity, and your app creates its own local session.

When you ship this to production, stick to the authorization code flow with PKCE inside a maintained auth library, validate state, redirect URIs, issuers, and tokens strictly, request the smallest scopes you can get away with, and keep secrets and tokens out of URLs and logs.

Want me to talk about your product? You can sponsor this site.

Related posts about network: