Skip to content

Sign in with another site: OAuth, step by step

Deep diveUnder the hood

You click "Sign in with Provider", bounce through two redirects and land signed in, and the app never saw your password. Here is every message in that dance, who can see it, and the three random values (state, the PKCE verifier, the nonce) that keep each step from being hijacked.

01 Why the app never sees your password

Before OAuth, an app that wanted your contacts from another site asked for your password on that site, and kept it. It could then do anything you could, forever, and the only way to revoke it was to change your password. OAuth 2.0 (RFC 6749) replaces that with a token: the other site gives the app a limited, revocable credential, and your password is only ever typed on the site that owns it.

The four roles
RoleIn "Sign in with Provider"Does
Resource ownerYouApproves what the app may have
ClientThe app (app.example.com)Asks for tokens and uses them
Authorization serverThe provider's sign-in serviceSigns you in, asks for consent, issues tokens
Resource serverThe provider's APIAccepts the access token on API calls

OAuth on its own is about access: "this app may read your calendar". Signing in needs one more thing: proof of who you are. OpenID Connect (OIDC) adds that on top of OAuth: ask for the openid scope and the provider also returns an ID token, a signed statement of who signed in. "Sign in with Google" and similar buttons are OIDC.

02 The code flow, message by message

The standard flow for apps with a server is the authorization code flow, here with PKCE, which current guidance recommends for every kind of client. Watch which messages go through the browser and which do not.

The authorization code flow with PKCE
Step 1 of 11
Sign in with a provider (code flow + PKCE)
BrowserApp serverProviderNothing sent yet
What the app server holds (example values)
Empty
  • just sent or stored
  • checked and matches

You are on app.example.com and click Sign in with Provider. Nothing has been sent and the app holds nothing about you.

The split is the point. Anything that passes through the browser, the front channel, travels in URLs and can leak through history, logs, Referer headers or a malicious extension. So the front channel only carries the code: short-lived, usable once, and worthless without the verifier. The tokens travel on the back channel, a direct HTTPS call from the app server to the provider.

03 PKCE: proving the same app came back

A code in a URL can be intercepted. On a phone, another app can register the same custom URL scheme (myapp://callback) and receive the redirect. In a browser, the code can end up in logs. PKCE (Proof Key for Code Exchange, RFC 7636) makes a stolen code useless.

  • Before redirecting, the app makes a random code verifier, 43 to 128 characters, and keeps it.
  • It sends only the code challenge: BASE64URL(SHA-256(verifier)), with code_challenge_method=S256.
  • The provider stores the challenge alongside the code it issues.
  • At /token the app sends the verifier. The provider hashes it and compares with the stored challenge.

The hash runs one way: seeing the challenge in the URL does not reveal the verifier. With the example values from RFC 7636:

JavaScript
const crypto = require('node:crypto');
const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
console.log(challenge); // E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
A stolen code without the verifier
An attacker redeems an intercepted code (example)
AttackerProviderPOST /token code=Splx…400 invalid_grant
Stored by the provider with the code
code_challenge→E9Melhoa…challenge_method→S256
  • refused

The attacker has the code but not the verifier, which never left the app. With no verifier, or a guessed one, the hash does not match and the provider refuses.

PKCE was written for apps that cannot keep a secret, such as mobile apps and single-page apps, which have no client_secret worth the name. The OAuth security best current practice (RFC 9700) now recommends it for server apps too, because it also blocks attacks where a stolen code is injected into a different session.

04 state and nonce: is this reply for me?

PKCE protects the code. state protects you. Without it, an attacker can start a sign-in with their own account, stop at the callback, and send you that link: https://app.example.com/callback?code=ATTACKERS_CODE. If the app accepts it, you are now signed in as the attacker, and anything you save (a card, a document) goes into their account. This is login CSRF.

The fix is the random state from the trace. The app stores it in your session before the redirect and refuses any callback whose state does not match. The attacker cannot know your value, so their link fails. (PKCE also stops this, since the attacker’s code is bound to a verifier in the attacker’s session, but check state anyway: it is cheap, and some providers do not enforce PKCE.)

OIDC adds a similar value for the ID token: the app sends a random nonce in the authorize URL, and the provider copies it into the ID token. If the nonce in the token is not the one stored in your session, the token was issued for some other sign-in and is rejected.

05 What comes back, and what to trust

The token endpoint answers with JSON. The values here are shortened examples:

JSON
{
"access_token": "at_9f2c...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "rt_41ab...",
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ...",
"scope": "openid email"
}
Three tokens, three jobs
TokenRead byUsed for
ID tokenYour appWho signed in. A signed JWT you verify once, then start your own session.
Access tokenThe provider's APICalling the API as the user, sent in an Authorization: Bearer header. Your app should treat it as opaque.
Refresh tokenThe provider's token endpointGetting a new access token when the old one expires, without the user. Only issued for some scopes or settings.

Before trusting the ID token, check it the way What’s inside a JWT describes, with the provider’s keys from its jwks_uri (listed in /.well-known/openid-configuration):

  • the signature, with the key named by the token’s kid;
  • iss is exactly the provider’s issuer URL;
  • aud is your client_id, so a token issued to some other app is refused;
  • exp is in the future, and nonce matches the one in your session.

Then identify the user by iss plus sub, the provider’s permanent id for that account. Not by email: people change emails, and some providers let users add addresses without proving they own them. If you link accounts by email at all, require email_verified: true.

id-token.js
import { createRemoteJWKSet, jwtVerify } from 'jose';
const JWKS = createRemoteJWKSet(new URL('https://accounts.example.com/.well-known/jwks.json'));
export async function checkIdToken(idToken, expectedNonce) {
const { payload } = await jwtVerify(idToken, JWKS, {
issuer: 'https://accounts.example.com',
audience: 'my-app',
});
if (payload.nonce !== expectedNonce) throw new Error('nonce mismatch');
return { provider: payload.iss, userId: payload.sub, email: payload.email };
}

06 Build the requests yourself

The first redirect is just a URL. This script makes a verifier, its challenge and a state, and prints the URL an app would redirect to. accounts.example.com and my-app stand in for a real provider and client id.

authorize-url.js
const crypto = require('node:crypto');
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
const state = crypto.randomBytes(16).toString('base64url');
const url = new URL('https://accounts.example.com/authorize');
url.search = new URLSearchParams({
response_type: 'code',
client_id: 'my-app',
redirect_uri: 'http://localhost:3000/callback',
scope: 'openid email',
state,
code_challenge: challenge,
code_challenge_method: 'S256',
});

A real run with Node 24 printed the following; yours will differ, because the values are random each time:

Text
verifier: XGdjB-4bgFhyuBuxFaxl-kRuX5AvfRcFZdp1zlIyxAY
challenge: 7XZ3DFRKV7Jxx0uuU9YD8Smewu5qRyPGfokVhrq7OIM
https://accounts.example.com/authorize?response_type=code&client_id=my-app&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&scope=openid+email&state=XvbOn0Kn9HYpYU67GhMpCw&code_challenge=7XZ3DFRKV7Jxx0uuU9YD8Smewu5qRyPGfokVhrq7OIM&code_challenge_method=S256

After the callback, the app posts the code back as a form. The verifier goes here, and only here:

HTTP
POST /token HTTP/1.1
Host: accounts.example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic bXktYXBwOnMzY3JldA==
grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

The Authorization: Basic header is the client id and secret (my-app:s3cret, Base64-encoded), which a server app has and a mobile app does not. The body is shown on several lines for reading; on the wire it is one line. To try the whole flow against a real provider, register an app with one (most have a free developer console) and use its discovery URL to find the endpoints.

07 When it bites

redirect_uri=https://app.example.com/*Loose redirect URIsIf the provider accepts any path or subdomain, an attacker can have the code sent somewhere they control. Register exact redirect URIs; providers should compare them as exact strings.
if (req.query.code) signIn()Skipping the state checkAnyone can then sign a victim into the attacker’s account with a crafted callback link. Compare state with the session, and use it only once.
response_type=tokenThe implicit flowOlder single-page apps got the access token straight in the URL fragment, where it leaks. It is deprecated; use the code flow with PKCE in the browser too.
client_secret in app.jsA secret in code users downloadAnything shipped to a browser or phone can be read. Public clients have no secret and rely on PKCE; keep real secrets on your server.
GET /me with any access tokenUsing an access token as proof of identityAn access token says what its holder may call, not which app it was issued to. A token from another app for the same user would also work. Sign users in from a verified ID token with your own aud.
localStorage.setItem("token", …)Tokens where scripts can reach themAny XSS bug can read localStorage and send the tokens away. Keep tokens on the server and give the browser an HttpOnly session cookie.

The authorization code is not a password for the app; it is a one-time ticket. A provider must reject a code used twice, and good ones also revoke the tokens already issued from it, since a reused code suggests it was stolen.

08 Check yourself

Question

An attacker intercepts the redirect to myapp://callback?code=… on a phone. The app used PKCE. What can the attacker do with the code?

Question

Why do the tokens travel from provider to app server directly, instead of in the redirect URL?

Question

Your app gets an ID token whose aud is another app’s client id, but the signature and iss are valid. What should it do?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?