OAuth 2.0 Flow — Auth

OAuth 2.0 gives an app limited permission (a scope) to use a user's account at another service, without the user's password. The flow is authorization code +…

The easiest way for School Portal to write to Mr. Andi's Google Calendar: just ask for his Google password. It's also the worst way. With that password, the Portal could read his email, open his Drive, even change his password.

OAuth 2.0 offers another way: an app gets limited permission to use your account at another service, without ever knowing your password. Picture a car's valet key. You don't give the parking attendant your main key. You give a special key that only starts the engine and opens the doors, and cannot open the boot. In this picture, the car is your account, the main key is the password, and the parking attendant is the app that asks for permission, such as School Portal. In OAuth that special key is called the access token, and the "engine and doors only" limit is called the scope (a permission limit).

The example: School Portal to Google Calendar

Mr. Andi, a teacher in School Portal, wants the exam timetable to appear in his Google Calendar automatically. School Portal needs permission to write events in that calendar, but must not know Mr. Andi's Google password. Four parties take part:

Role in OAuth In this example
Resource owner: the owner of the data, who grants permission Mr. Andi
Client: the app asking for permission the School Portal server
Authorization server: asks for consent and hands out tokens Google (accounts.google.com, oauth2.googleapis.com)
Resource server: holds the data the Google Calendar API

Notice the word client. In the first lesson, the client was the app that sends a request, such as a browser. In OAuth, the client is the app that asks for permission and then sends requests to Google: here the School Portal server, not Mr. Andi's browser. The authorization server is also often called the provider (the service that handles the login).

First, School Portal registers at the Google Cloud Console (Google's site for registering apps). There the Portal gets a client_id (the app's identity, fine to be public) and a client_secret (a secret, kept only on the server). While registering, School Portal also records the redirect_uri: the address on the Portal where Google sends Mr. Andi's browser back, https://portal.school.test/oauth/google/callback. This address is called the callback. The scope it asks for is https://www.googleapis.com/auth/calendar.events, meaning calendar events only, not email or Drive.

The flow is called Authorization Code + PKCE: eight steps, exactly as in the Lab. The code is written in JavaScript so it runs in the Lab and in Node (JavaScript that runs on a server). In Laravel, the Socialite library does the same steps (the Social Login lesson).

Steps 1-2: state, PKCE, then the authorize URL

Mr. Andi presses "Connect Google Calendar". The Portal server prepares two random values and keeps them in Mr. Andi's session:

The startLogin function below makes both values, then builds the authorize URL, the address of Google's permission page:

function base64url(bytes) {
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

async function startLogin(session) {
  session.state = base64url(crypto.getRandomValues(new Uint8Array(16)));
  session.verifier = base64url(crypto.getRandomValues(new Uint8Array(32))); // 43 characters
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(session.verifier));
  const params = new URLSearchParams({
    response_type: "code",
    client_id: "1234567890-portal.apps.googleusercontent.com",
    redirect_uri: "https://portal.school.test/oauth/google/callback",
    scope: "https://www.googleapis.com/auth/calendar.events",
    state: session.state,
    code_challenge: base64url(new Uint8Array(digest)),
    code_challenge_method: "S256",
  });
  return "https://accounts.google.com/o/oauth2/v2/auth?" + params; // answer with a 302 to here
}

With the example values from RFC 7636 (the PKCE standard) that the Lab uses, the verifier dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk gives the challenge E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM. The server answers the browser with the status code 302 (go to another address), and Mr. Andi's browser opens this URL:

https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=1234567890-portal.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fportal.school.test%2Foauth%2Fgoogle%2Fcallback&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.events&state=af0ifjsldkj&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256

Steps 3-5: consent and the callback

At Google, Mr. Andi signs in. He types his password at Google, not at the Portal. Then he sees the consent screen: School Portal wants to view and edit his calendar events. He presses Allow. Google makes an authorization code, records it together with the code_challenge, then sends the browser back to the redirect_uri:

https://portal.school.test/oauth/google/callback?state=af0ifjsldkj&code=SplxlOBeZQQYbYS6WxSbIA

If Mr. Andi presses Cancel, the callback carries ?error=access_denied&state=af0ifjsldkj. That is a valid answer, not an error that stops the app, so the client has to handle it. The handleCallback function runs on the Portal server when the browser opens the callback:

async function handleCallback(session, callbackUrl) {
  const query = new URL(callbackUrl).searchParams;
  const { state, verifier } = session;
  delete session.state; // single use
  delete session.verifier;
  if (!state || query.get("state") !== state) throw new Error("state mismatch");
  if (query.get("error")) return { error: query.get("error") }; // access_denied: Mr. Andi pressed Cancel

  const res = await fetch("https://oauth2.googleapis.com/token", {
    method: "POST",
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code: query.get("code"),
      redirect_uri: "https://portal.school.test/oauth/google/callback",
      client_id: "1234567890-portal.apps.googleusercontent.com",
      client_secret: process.env.GOOGLE_CLIENT_SECRET, // lives on the server only
      code_verifier: verifier,
    }),
  });
  return res.json();
}

Steps 6-7: exchange the code for a token

The fetch request in handleCallback goes from the Portal server straight to Google, not through the browser. Its body (the content of the request) carries the code, the client_secret and the code_verifier. Google computes the SHA-256 of that verifier and compares it with the challenge it recorded at step 3. On a match, Google answers:

{
  "access_token": "2YotnFZFEjr1zCsicMWpAA",
  "expires_in": 3599,
  "scope": "https://www.googleapis.com/auth/calendar.events",
  "token_type": "Bearer"
}

Step 8: the Portal calls POST https://www.googleapis.com/calendar/v3/calendars/primary/events with the header Authorization: Bearer 2YotnFZFEjr1zCsicMWpAA, and "Math Exam 8A" appears in Mr. Andi's calendar. This token lasts about 1 hour (3599 seconds), and only for the calendar scope.

After that hour, the Portal can no longer write to the calendar. Yet a new exam can be scheduled at any time, even while Mr. Andi is not using the Portal. For this, the authorize URL has an access_type parameter with two options:

access_type When to pick it
online (Google's default, used in the example above) the Portal calls Calendar only while Mr. Andi is using the Portal. When the token has expired, the Portal runs the authorize flow again.
offline the Portal writes to the calendar without Mr. Andi, for example a nightly job that copies new exams. The answer in step 6 also carries a refresh_token. Keep it on the server, then exchange it for a new access token with grant_type=refresh_token.

Google sends the refresh_token only on the first consent. If the Portal loses its refresh token, ask for Mr. Andi's consent again with prompt=consent in the authorize URL.

Why a code first, then a token

In steps 2 to 5, the browser carries only URLs between the Portal and Google: the authorize address, then the callback with the code. URLs can end up in the browser's history, in server logs (the record of incoming requests), or in a Referer header (a header that holds the address of the previous page). That is why what travels in the URL is an authorization code, which works once, lives briefly, and is useless without the client_secret and the code_verifier. The access token itself arrives as the answer to the step 6 request, server to server, so it never appears in the browser's URL or history.

The old flow, the Implicit Flow (response_type=token), put the access token straight into the URL. It is no longer recommended. Today every client is advised to use the authorization code + PKCE, SPAs (web apps that run fully in the browser) and mobile apps included.

📌 Other grant types

The way a client gets a token is called a grant type. This table shows when each grant type is used:

Grant type Used for
Authorization Code + PKCE a user grants access: web, SPA, mobile
Client Credentials machine to machine, no user, such as a nightly job calling another API
Device Code devices with no keyboard (TV, console): the screen shows a code, the user approves it from a phone

Logging in with Google uses the same flow, plus data about the user's identity. That is the next lesson, Social Login.

⚠️ What is often missed when adding OAuth

TL;DR: OAuth 2.0 gives an app limited permission (a scope) to use a user's account at another service, without the user's password. The flow is authorization code + PKCE. The client (the app asking for permission) makes two random values, a state and a code_verifier. Then it sends the code_challenge = base64url(SHA-256(verifier)) in the authorize URL, the address of the permission page at a provider such as Google. That URL is built with URLSearchParams. The user agrees at the provider. Then the browser comes back to the callback (an address on the client) with code (a single-use authorization code) and state: compare the state with the one kept in the session, and handle error=access_denied (the user pressed Cancel). After that the client exchanges code + verifier + client_secret (the client's secret) for an access token, from its server straight to the provider. All the client receives through the browser is the authorization code, so the token never appears in a URL. For machine to machine with no user, there is another flow: Client Credentials. The Implicit Flow, which put the token in the URL, is outdated.

⚡ Limited permission, no password

Meaning: OAuth 2.0 gives an app limited permission to use your account at another service, without ever knowing your password. Like a car's valet key for a parking attendant: it only starts the engine and opens the doors. The parking attendant is the app. The valet key is called the access token, and its limit is called the scope.

⚡ Check the state at the callback

Write:

const { state, verifier } = session;
delete session.state; // single use
delete session.verifier;
if (!state || query.get("state") !== state) throw new Error("state mismatch");
if (query.get("error")) return { error: query.get("error") }; // access_denied: Mr. Andi pressed Cancel

Meaning: Mr. Andi, a teacher, connects his Google Calendar to School Portal. At the start of the flow, the Portal server keeps two random values in the session: state (a marker for the flow) and the verifier (code_verifier, a PKCE secret that later proves to Google that the Portal started this flow). This code runs when Google sends the browser back to the callback, an address on the Portal. query holds the parameters of the callback URL. The state in that URL must equal the one in the session: this check makes sure the callback continues the flow Mr. Andi started. Both values are taken, then deleted from the session, so each flow may finish only once. error=access_denied is a valid answer, not an error that stops the app.

⚡ A code first, then a token

Guess first: Mr. Andi signed in and pressed Allow at Google. What does the browser bring back to the Portal: an access token or an authorization code (a single-use code)?

An authorization code. The browser comes back through the callback URL, and URLs can end up in the history and in logs. So all that travels in the URL is a code that works once, and it is useless without the client_secret (a secret that exists only on the Portal server) and the code_verifier. The access token comes from Google's server straight to the Portal's server.

Meaning: The flow is called authorization code + PKCE. At the start, the code_challenge = base64url(SHA-256(verifier)) goes in the authorize URL (the address of Google's permission page). At the end, the Portal server exchanges code + verifier + client_secret for an access token, and Google checks that the verifier matches the challenge sent at the start. The Implicit Flow, an old flow that put the token in the URL, is no longer recommended.

What you will learn