Skip to content

Authentication

Sign customers in with OAuth and PKCE, or with your own sign-in, and read the catalog with a publishable key.

Updated

A call carries one of two credentials:

  • a publishable key, Publishable-Key: <key>, for what the store shows anyone, before anyone signs in;
  • a customer’s access token, Authorization: Bearer ctk_..., for everything that customer does.

Send one or the other, never both: both together answer 422 invalid. Neither ever goes in a cookie.

Publishable keys

A store’s own front end reads the catalog with the store’s publishable key, created under Settings, Connections, API clients in the merchant app (see Your own front end). It’s public by design, since it sits in your page’s source: it holds read alone, and reaches only the endpoints the reference marks as taking it, each answered as for a visitor:

  • the store, its products, their entries, its pages and their bodies;
  • the files those reads list as open to visitors, and a video’s chapters, summary and transcript where the video is;
  • a product’s reviews, its prompts without their text, and checking a certificate;
  • recording a page a visitor saw, for the store’s analytics (Visits).
curl 'https://api.sherpo.io/customer/v1/stores/yourstore.sherpo.io/products' \
  --header 'Publishable-Key: <publishable key>'

A file’s URL asked for with the key already carries it as publishable_key, so it works without the header (Files and media).

Answer Why
401 not_permitted, reason credential The key is unknown, revoked, or another store’s.
403 not_permitted, reason principal The endpoint doesn’t take a publishable key: sign the customer in.
403 not_permitted, reason plan The store’s plan doesn’t include its own front end (Lite).
422 invalid at ["headers", "publishable-key"] The key is malformed, or sent with an Authorization header.

Customer tokens

Each store has its own OAuth 2.1 authorization server. Its issuer is https://customer-auth.sherpo.io/s/{store}, where {store} is one of the store’s hostnames, and its metadata (RFC 8414) is at https://customer-auth.sherpo.io/.well-known/oauth-authorization-server/s/{store}:

Metadatajson
{
  "issuer": "https://customer-auth.sherpo.io/s/yourstore.sherpo.io",
  "authorization_endpoint": "https://customer-auth.sherpo.io/s/yourstore.sherpo.io/authorize",
  "token_endpoint": "https://customer-auth.sherpo.io/s/yourstore.sherpo.io/token",
  "registration_endpoint": "https://customer-auth.sherpo.io/s/yourstore.sherpo.io/register",
  "revocation_endpoint": "https://customer-auth.sherpo.io/s/yourstore.sherpo.io/revoke",
  "response_types_supported": ["code"],
  "response_modes_supported": ["query"],
  "grant_types_supported": [
    "authorization_code",
    "refresh_token",
    "urn:sherpo:params:oauth:grant-type:merchant-assertion"
  ],
  "code_challenge_methods_supported": ["S256"],
  "token_endpoint_auth_methods_supported": ["none", "client_secret_basic", "client_secret_post"],
  "revocation_endpoint_auth_methods_supported": ["none", "client_secret_basic", "client_secret_post"],
  "scopes_supported": ["read", "profile:write", "checkout:write", "review:write", "quiz:write", "progress:write", "subscription:write"],
  "authorization_response_iss_parameter_supported": true
}

The customer signs in with a code mailed to their address (or with Google, where the store offers it), then sees a consent page in the store’s name and colors listing what your app asks for. They may grant everything asked (Full access) or, when the app asked for read beside other scopes, read alone (Read-only). The token then carries what they granted.

Which client

  • A website or a mobile app whose code runs on the customer’s device is a public client: it registers itself once per store and proves each sign-in with PKCE.
  • A backend uses a client with a secret you create in the merchant app, with its redirect URIs. It runs the same flow, authenticating at the token endpoint with its secret (client_secret_basic or client_secret_post), PKCE still required.
  • A site that already signs its customers in trades its own sign-in for a token from its backend: see Your own sign-in.

Register an app

POST https://customer-auth.sherpo.io/s/{store}/register (RFC 7591), with a JSON body. Registration is open and needs no credential.

curl --request POST 'https://customer-auth.sherpo.io/s/yourstore.sherpo.io/register' \
  --header 'Content-Type: application/json' \
  --data '{
    "client_name": "Your Store app",
    "redirect_uris": ["https://www.example.com/callback"],
    "scope": "read checkout:write progress:write"
  }'
201json
{
  "client_id": "<client id>",
  "client_id_issued_at": 1793696400,
  "client_name": "Your Store app",
  "redirect_uris": ["https://www.example.com/callback"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none",
  "scope": "read checkout:write progress:write"
}
  • redirect_uris are where customers come back, with no fragment and no credentials in them: https:// addresses, http://localhost, http://127.0.0.1 or http://[::1] on any port, or a mobile app’s private-use scheme named after a domain it owns (com.example.app:/callback, RFC 8252).
  • scope is space separated; leave it out to hold every scope an app may register with (scopes_supported above). contact:write is refused here: only a client the merchant creates holds it.
  • token_endpoint_auth_method takes none (the default), client_secret_basic or client_secret_post. A secret method answers a client_secret once, with client_secret_expires_at: 0, which the app then presents at the token and revocation endpoints. It stays a registered app: PKCE still proves each exchange.
  • The name is cleaned and cut to 120 characters, and the answer carries the name kept.
  • A registration no customer connects within 24 hours lapses, and an unverified app that has held no customer’s token and made no call for 30 days may be removed to make room for new registrations: its client_id then stops working, so register again. One the merchant verifies stays.
  • Refusals answer RFC 7591’s errors with a description: invalid_redirect_uri, invalid_client_metadata (413 for a body too large), invalid_request with 404 when no store answers on the hostname, and temporarily_unavailable with 429 and Retry-After past the registration limit for your network.

Sign the customer in

  1. Send them to authorize

    Make a PKCE verifier and its S256 challenge, keep the verifier and a random state, and send the browser to the authorization endpoint.

    const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
    const challenge = base64url(
      new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))),
    );
    const state = base64url(crypto.getRandomValues(new Uint8Array(16)));
    sessionStorage.setItem('pkce', JSON.stringify({ verifier, state }));
    
    const authorize = new URL('https://customer-auth.sherpo.io/s/yourstore.sherpo.io/authorize');
    authorize.search = new URLSearchParams({
      response_type: 'code',
      client_id: '<client id>',
      redirect_uri: 'https://www.example.com/callback',
      scope: 'read checkout:write progress:write',
      state,
      code_challenge: challenge,
      code_challenge_method: 'S256',
    }).toString();
    location.assign(authorize);
    
    function base64url(bytes: Uint8Array) {
      return btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
    }

    Ask for no resource: a token issued for the store’s MCP server is refused here, and one issued here is refused there.

  2. Take the code back

    The customer comes back to your redirect URI with code, your state and iss (the issuer, RFC 9207). Check that state is yours and iss is the store’s issuer. A denial or a refusal comes back as error (access_denied, invalid_scope and the rest of OAuth’s errors) with the state. An invalid client or redirect URI never redirects: the customer sees an error page instead. The code works once, for 5 minutes.

  3. Trade it for a token

    POST the code and the verifier to the token endpoint, form encoded. The endpoint answers any origin, so a browser app calls it directly.

    curl --request POST 'https://customer-auth.sherpo.io/s/yourstore.sherpo.io/token' \
      --data-urlencode 'grant_type=authorization_code' \
      --data-urlencode 'code=<code>' \
      --data-urlencode 'redirect_uri=https://www.example.com/callback' \
      --data-urlencode 'client_id=<client id>' \
      --data-urlencode 'code_verifier=<verifier>'

    On your callback page, the same in the browser:

    const query = new URLSearchParams(location.search);
    const started = JSON.parse(sessionStorage.getItem('pkce') ?? 'null') as { verifier: string; state: string } | null;
    sessionStorage.removeItem('pkce');
    if (started === null || query.get('state') !== started.state) throw new Error('This sign-in didn\'t start here.');
    if (query.get('iss') !== 'https://customer-auth.sherpo.io/s/yourstore.sherpo.io') throw new Error('Another server answered.');
    const refused = query.get('error');
    if (refused !== null) throw new Error(`Sign-in ended: ${query.get('error_description') ?? refused}`);
    const code = query.get('code');
    if (code === null) throw new Error('The sign-in came back with no code.');
    
    const response = await fetch('https://customer-auth.sherpo.io/s/yourstore.sherpo.io/token', {
      method: 'POST',
      body: new URLSearchParams({
        grant_type: 'authorization_code',
        code,
        redirect_uri: 'https://www.example.com/callback',
        client_id: '<client id>',
        code_verifier: started.verifier,
      }),
    });
    const text = await response.text();
    let tokens: { access_token?: string; refresh_token?: string; expires_in?: number; error?: string; error_description?: string };
    try {
      tokens = JSON.parse(text) ?? {};
    } catch {
      throw new Error(`The token answer isn't JSON (HTTP ${response.status}): ${text.slice(0, 200)}`);
    }
    if (!response.ok) throw new Error(tokens.error_description ?? tokens.error ?? `HTTP ${response.status}`);
    if (typeof tokens.access_token !== 'string') throw new Error('The token answer holds no access token.');
    200json
    {
      "access_token": "ctk_...",
      "token_type": "Bearer",
      "expires_in": 3600,
      "refresh_token": "...",
      "scope": "read checkout:write progress:write"
    }

Call the API with the access token as a bearer:

curl 'https://api.sherpo.io/customer/v1/stores/yourstore.sherpo.io/profile' \
  --header 'Authorization: Bearer ctk_...'

Refresh and revoke

An access token lasts 1 hour (its expires_in, in seconds). Trade the refresh token for a new pair before it ends:

curl --request POST 'https://customer-auth.sherpo.io/s/yourstore.sherpo.io/token' \
  --data-urlencode 'grant_type=refresh_token' \
  --data-urlencode 'refresh_token=<refresh token>' \
  --data-urlencode 'client_id=<client id>'

Keep only the latest pair: a refresh token used twice revokes the token, signing the customer out. A refresh token lasts 30 days from the last refresh, so a customer who comes back within that time stays signed in. A refresh also ends the file and video URLs the old token asked for (Files and media).

When the customer signs out of your app, revoke the token (RFC 7009); either the access or the refresh token revokes both. It answers 200 whether or not there was anything to revoke.

curl --request POST 'https://customer-auth.sherpo.io/s/yourstore.sherpo.io/revoke' \
  --data-urlencode 'token=<refresh token>' \
  --data-urlencode 'client_id=<client id>'

The token endpoint answers OAuth’s own errors (RFC 6749): invalid_grant (400) when the code, verifier or refresh token no longer stands, invalid_request (400) for a malformed request, invalid_client (401) for a client it doesn’t accept, invalid_scope, and temporarily_unavailable (429, with Retry-After) past a limit. On a store whose plan doesn’t include its own front end, a grant answers invalid_grant with a description saying so.

Your own sign-in

A site that already signs its customers in can skip the mailed code. In the merchant app, turn on Signs in your own customers for a client with a secret. Its backend then trades the account it signed in for a token, authenticated by the client secret:

curl --request POST 'https://customer-auth.sherpo.io/s/yourstore.sherpo.io/token' \
  --user '<client id>:<client secret>' \
  --data-urlencode 'grant_type=urn:sherpo:params:oauth:grant-type:merchant-assertion' \
  --data-urlencode 'account_id=user_8231' \
  --data-urlencode 'email=ada@example.com' \
  --data-urlencode 'email_verified=true' \
  --data-urlencode 'name=Ada Lovelace' \
  --data-urlencode 'locale=en' \
  --data-urlencode 'scope=read checkout:write'
  • account_id is your own id for the account, required. Every client that signs in your customers shares the store’s account ids, so each must name the same customer by the same id.
  • email is optional, with email_verified=true when your site proved it. The address is kept on the customer unproven: it never lets anyone sign in with a mailed code.
  • name, locale and scope are optional; without scope, the token holds every scope the client does.
  • It answers the same JSON as the code exchange.

For an account not yet tied to a customer, an address you proved that a customer of the store already proved answers invalid_grant, so your sign-in never takes over someone’s account. Link them once: send the customer through the authorization flow with the same client, then call this grant again with link_token, the access token they granted. From then on, their tokens carry what the client holds. For an account already tied to a customer, an address another customer proved is left off.

The secret then acts as any of the store’s customers, so keep it on your server. Turning the setting off ends every token the client got this way; a leaked secret also needs Rotate secret.

Scopes

Scope Lets your app Merchant app label
read Read products, prices and what the customer holds Read
profile:write Change the customer’s name and locale, and mark, delete and choose their notifications Profiles
contact:write Change the address that signs in to the customer’s account Email addresses
checkout:write Buy, pay, and manage saved payment methods Checkout
review:write Write and delete the customer’s reviews Reviews
quiz:write Take quizzes Quizzes
progress:write Mark entries complete Progress
subscription:write Cancel, resume and change subscriptions Subscriptions

Each endpoint in the reference names the scope it needs. contact:write is granted on its own and held only by a client the merchant created, never by an app that registered itself, so manage a customer’s address from a backend.

Apps the store hasn’t verified

An app that registered itself is unverified until the merchant chooses Verify app for it. Its consent page tells the customer so, and warns about checkout:write. Until it’s verified, it pays only with a card the customer enters in your page: these answer 403 not_permitted with the reason principal:

  • paying with a saved card (instrument), or confirming a payment that runs on one;
  • a refund waiver, and a cart that asks for one;
  • making a payment method the default, or removing one;
  • resuming a subscription or changing its plan.

Send the customer to the store’s own pages for those: https://{served_hostname}/account/payment-methods and https://{served_hostname}/account/subscriptions, where served_hostname comes from GET /v1/stores/{store}.

Refused tokens

Answer Why
401 with WWW-Authenticate: Bearer No credential.
401 with error="invalid_token" The token is expired, revoked, malformed, or was issued for another service (the store’s MCP server): refresh it, or sign the customer in again.
403 with error="insufficient_scope" The customer didn’t grant the scope this endpoint needs.
403 not_permitted, reason principal The token may not act on this store or row, or the app isn’t verified for it (above).
422 invalid at ["query", "access_token"] A token sent in a file’s URL: it’s never taken there, since logs, history and Referer keep URLs. Anywhere else, a token in the query isn’t read at all, so the call answers as one with no credential.

Many refused tokens from one network answer 429 for a while instead; see Limits.

Type to search…

↑↓ navigate↵ selectEsc close