Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 55 ยท Authentication and Sessions

The OAuth Authorization Code Flow

Learn the OAuth authorization code flow Shopify apps use to get access tokens: install URL, consent, state, HMAC validation and code exchange, with a simulator.

When a merchant installs your app, two things must be settled: the merchant must agree to the permissions you ask for, and your server must end up holding a credential, an access token, that lets it call that store's APIs. The standard way to do this is OAuth 2.0 with the authorization code grant. Shopify has used it since the first public apps, and nearly every other platform with "Sign in with..." or "Connect your account..." buttons uses the same pattern.

You will rarely write this flow by hand today, because the Shopify CLI template and the managed installation feature handle it. But you should understand it. It explains why redirect URLs exist, what the HMAC on a callback protects, why a state value matters, and it makes the newer token exchange flow (Token Exchange and Access Tokens) much easier to follow. The real requests below are read-only, since this site cannot talk to Shopify. The runnable part is a simulator with a pretend Shopify and a pretend app, which is a stand-in; we mark it clearly.

The cast

  • The merchant (the browser) clicks an install link.
  • Your app server, which owns a client ID and client secret.
  • Shopify, which shows the consent screen and issues codes and tokens.

The authorization code is a short-lived, single-use value. It proves that the merchant approved. Your server swaps it, together with the client secret, for the long-lived access token. The secret never passes through the browser, which is the point of the design.

sequenceDiagram
    participant M as Merchant browser
    participant A as Your app server
    participant S as Shopify
    M->>A: open install link for shop X
    A->>M: redirect to Shopify authorize URL (with state)
    M->>S: authorize request
    S->>M: consent screen
    M->>S: approve scopes
    S->>M: redirect to redirect_uri with code, hmac, state, shop
    M->>A: callback request
    A->>A: check state, shop and HMAC
    A->>S: POST code + client secret
    S->>A: access token + granted scopes

The browser carries the code; only the server, which knows the secret, can turn it into a token.

Step 1: the install request

The merchant arrives at your app, perhaps from the App Store or an install link, with the shop's domain in the query: https://your-app.example.com/auth?shop=cool-store.myshopify.com. First, validate the shop parameter. It must be a plain *.myshopify.com host name. If you accept any string, an attacker can make your server send requests, or redirects, to an address of their choosing.

Then generate a random state value, store it (in a signed cookie or a session) and redirect the browser to the store's authorize URL:

TEXT
https://cool-store.myshopify.com/admin/oauth/authorize
  ?client_id=YOUR_CLIENT_ID
  &scope=read_products,write_products
  &redirect_uri=https://your-app.example.com/auth/callback
  &state=3f9c1a...random

The redirect_uri must match one of the addresses declared in [auth] redirect_urls of your configuration (App Configuration with shopify.app.toml). Otherwise Shopify rejects the request.

Shopify shows the merchant the app's name and the permissions in plain language (for example, "view and edit products"). The merchant approves or cancels. You do not control this screen. This is why asking for fewer scopes helps conversion, and why Managed Installation and Access Scopes recommends least privilege.

Step 3: the callback

If the merchant approves, Shopify redirects the browser to your redirect_uri with query parameters, among them:

Parameter Meaning
code The single-use authorization code
shop The shop's domain
state The value you sent in step 1, returned unchanged
timestamp When Shopify issued the redirect
hmac A signature over the other parameters
host An encoded host value used by embedded apps

Your callback handler must verify three things before it uses the code:

  1. state matches. Compare the returned value with the one you stored for this browser. This defends against cross-site request forgery: without it, an attacker could trick a merchant's browser into completing an authorization that the attacker started, linking the attacker's data to the merchant's session.
  2. shop is a valid shop domain (the same pattern check as in step 1).
  3. The hmac is valid. Shopify computed it with your client secret, so a correct value shows the parameters were not forged or altered.

How the HMAC is computed

To verify, take all query parameters except hmac itself, sort them by name, join them as name=value pairs with &, and compute HMAC-SHA256 with your client secret as the key. The result in hexadecimal must equal the hmac you received. Compare with a timing-safe function, not ===, so an attacker cannot learn the correct value byte by byte from response times. The idea of signing a message with a shared secret is explained in Webhooks and Signatures; webhook signatures use the same primitive in a different encoding (Verifying Webhook Signatures).

Step 4: exchange the code

With the checks done, your server makes a direct request to Shopify. This sketch is read-only:

JavaScript
// read-only sketch of the token request (Node 18+ fetch)
const response = await fetch(`https://${shop}/admin/oauth/access_token`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    client_id: process.env.SHOPIFY_API_KEY,
    client_secret: process.env.SHOPIFY_API_SECRET,
    code,
  }),
});
const { access_token, scope } = await response.json();

The response contains the access token and the scopes that were actually granted. Store the token against the shop (encrypted at rest if you can), and use it in a header on every Admin API call. A code works once; if you replay it, Shopify refuses.

Afterward you typically register things that depend on the install, redirect the merchant into the embedded app, and (for older apps) set up webhooks. Modern apps declare webhooks in configuration instead.

Why you usually do not write this yourself

Hand-written OAuth has several places to go wrong: shop validation, state storage, HMAC verification, cookie handling inside iframes, and redirects that must leave the iframe to reach the consent page. Shopify's app libraries implement all of that, and the template calls them for you.

Even better, managed installation moves the consent step out of your code. You list scopes in the configuration file; Shopify shows the consent screen itself during installation, without your app starting a redirect. For embedded apps, your server then gets a token by token exchange: it sends the session token the browser already has and receives an access token in return, with no redirect dance at all. You will see that in Session Tokens for Embedded Apps and Token Exchange and Access Tokens.

The authorization code flow is still worth knowing: it is the fallback for some app types, many integrations with other platforms use it, and every concept in it (consent, scopes, state, signed redirects, one-time codes) shows up again in the modern flows.

A simulator you can run

The code below runs a complete flow between a pretend Shopify and a pretend app inside one Node program. Everything is fake: the secrets, the shop and the token. It is a stand-in that shows the order of events and why each check exists. The HMAC computation, however, is the real algorithm from Node's crypto module, applied to the parameters the way the steps above describe.

Node.js Simulate the authorization code flow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output against the checks: the normal install works once, the replay fails because the state was consumed, the forged callback fails the HMAC, and a callback from the wrong browser fails the state check.

Looking at the signature on its own

The HMAC step is worth isolating, because you will reuse it for app proxies (App Proxy and Storefront Pages). This example signs a set of parameters, then shows how changing one value, or the order the parameters arrive in, affects the check. The sorting step is what makes the order of the query string irrelevant.

Node.js Signing sorted query parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Skipping the state check. The flow still "works", which is why the bug survives. It leaves a CSRF hole.
  • Comparing the HMAC with ===. Use a timing-safe comparison.
  • Using the shop parameter before validating it. It decides which server you contact.
  • Keeping the client secret in browser code. Only the server may see it.
  • Treating the code as reusable. It is single-use and short-lived. Exchange it immediately.
  • Requesting scopes you do not use. Every extra permission lowers merchant trust.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the app exchange the authorization code on the server instead of in the browser?

    The client secret proves the request comes from your app. If it were in browser code, anyone could read it and impersonate the app.
  2. 2. What attack does the state parameter defend against?

    Checking that the returned state equals the one stored for this browser shows the callback belongs to an authorization this browser started.
  3. 3. How is the callback HMAC computed?

    Remove hmac, sort the remaining parameters, join them as name=value pairs with ampersands and sign with the client secret.
  4. 4. Why compare signatures with a timing-safe function?

    An ordinary comparison can stop at the first differing byte, and measurable timing differences can leak information. A timing-safe comparison takes the same time either way.
  5. 5. What does managed installation change?

    Scopes are declared in configuration and Shopify handles consent during install. Tokens are still needed, and embedded apps can get them by token exchange.

Summary

  • OAuth's authorization code flow lets a merchant approve scopes and lets your server obtain an access token without exposing the client secret to the browser.
  • Validate the shop domain, store and compare state, verify the HMAC over the sorted parameters and then exchange the single-use code.
  • Redirect URLs in configuration limit where Shopify will send the browser.
  • Managed installation and token exchange remove most of this code from modern apps, but the same ideas remain.
  • The request sketches are real but read-only here; the simulator is a stand-in whose HMAC step uses the genuine algorithm.

Next: Managed Installation and Access Scopes