The PKCE Authorization Code Flow

End-to-end walkthrough of the authorization code grant with PKCE — the standard flow for user-attached applications.

The PKCE Authorization Code Flow

PKCE (pronounced "pixie") is the authorization code grant hardened against code interception attacks. Securely Connect uses PKCE on every authorization_code request — for public and confidential clients. The only PKCE method we support is S256.

This guide walks the whole flow. If you just want copy-paste code, jump to the Implement PKCE recipe.

📘

Third-party? PKCE is required, even with a client_secret.

Consent for a third-party client only happens at /oauth/authorize, and that endpoint requires a code_challenge. A client_secret is an additional credential on the token exchange — it does not replace the verifier/challenge pair. If you have both, you send both.

The actors

  • Your app — the OAuth client.
  • The user agent — usually a browser, sometimes a system browser tab opened from a mobile/desktop app.
  • auth.securely.io — the authorization server.

The flow at a glance

1. App generates code_verifier (random) and code_challenge = SHA256(verifier)
2. App redirects user to /oauth/authorize with code_challenge
3. User logs in
4. (THIRD_PARTY only) User consents and picks a business
5. Auth server redirects back to your redirect_uri with ?code=…&state=…
6. App POSTs to /oauth/token with code + code_verifier
7. Auth server verifies SHA256(code_verifier) == stored code_challenge
8. Auth server returns access_token (+ refresh_token)

Step 1 — Generate the verifier and challenge

The verifier is a cryptographically random string, 43–128 characters, base64url-encoded. The challenge is its SHA-256 hash, also base64url-encoded.

function base64UrlEncode(buffer) {
  return btoa(String.fromCharCode(...new Uint8Array(buffer)))
    .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

async function generatePkcePair() {
  const verifierBytes = crypto.getRandomValues(new Uint8Array(32));
  const codeVerifier = base64UrlEncode(verifierBytes);

  const challengeBytes = await crypto.subtle.digest(
    'SHA-256',
    new TextEncoder().encode(codeVerifier),
  );
  const codeChallenge = base64UrlEncode(challengeBytes);

  return { codeVerifier, codeChallenge };
}
using System.Security.Cryptography;

static (string verifier, string challenge) GeneratePkcePair() {
    var bytes = RandomNumberGenerator.GetBytes(32);
    var verifier = Base64UrlEncode(bytes);

    var challengeBytes = SHA256.HashData(Encoding.UTF8.GetBytes(verifier));
    var challenge = Base64UrlEncode(challengeBytes);

    return (verifier, challenge);
}

static string Base64UrlEncode(byte[] bytes) =>
    Convert.ToBase64String(bytes)
        .TrimEnd('=').Replace('+', '-').Replace('/', '_');
package main

import (
    "crypto/rand"
    "crypto/sha256"
    "encoding/base64"
)

func generatePkcePair() (verifier, challenge string, err error) {
    b := make([]byte, 32)
    if _, err = rand.Read(b); err != nil {
        return
    }
    verifier = base64.RawURLEncoding.EncodeToString(b)
    sum := sha256.Sum256([]byte(verifier))
    challenge = base64.RawURLEncoding.EncodeToString(sum[:])
    return
}
# PKCE generation isn't a shell-friendly task — but for testing:
VERIFIER=$(openssl rand -base64 32 | tr -d '=+/' | cut -c1-64)
CHALLENGE=$(printf "%s" "$VERIFIER" | openssl dgst -sha256 -binary \
  | openssl base64 | tr -d '=' | tr '/+' '_-')
echo "verifier=$VERIFIER"
echo "challenge=$CHALLENGE"

Save the verifier in a place tied to this authorization request (session, secure storage). You'll need it in step 6.

Step 2 — Redirect the user to /oauth/authorize

Build a URL with these query parameters:

ParameterRequiredValue
client_id✓Your client ID
response_type✓code
redirect_uri✓An exact match of a redirect URI registered on your client
code_challenge✓The challenge from step 1
code_challenge_methodoptionalS256 (default; only value supported)
staterecommendedAn opaque value you'll verify in the callback (CSRF protection)
merchant_idoptionalPre-select a merchant context
business_idoptionalPre-select a business context
https://auth.securely.io/oauth/authorize
  ?client_id=YOUR_CLIENT_ID
  &response_type=code
  &redirect_uri=https%3A%2F%2Fyour.app%2Fcallback
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256
  &state=2c1c5f8a
📘

Method GET or POST?

The endpoint accepts both. GET is easier for browser redirects; POST is useful if you're submitting from a form and don't want the parameters in URL history.

Step 3 — User logs in

The auth server presents the login screen. For repeat users with an active session, this step may be silent.

Step 4 — Consent (THIRD_PARTY only)

For third-party clients, the auth server redirects the user to the consent screen:

https://auth.securely.io/login?consent_challenge=eyJhbGciOiJSUzI1NiIs...

The user sees your app's name and logo, picks which of their businesses you may access, and approves or denies. See Business Consent for details. Second-party clients skip this step — their keys are already scoped to a single business, so there's nothing to consent to at runtime.

Step 5 — Redirect back to your app with a code

On success, the auth server redirects the user agent to your redirect_uri:

https://your.app/callback?code=AUTH_CODE_HERE&state=2c1c5f8a

In your callback handler:

  1. Verify state matches the value you sent in step 2. If not, abort.
  2. Extract code.
🚧

If state doesn't match

Treat the request as hostile. Do not exchange the code, do not redirect the user back into a flow. Log it and bail.

Step 6 — Exchange the code for tokens

POST to /oauth/token with application/x-www-form-urlencoded:

curl -X POST https://auth.securely.io/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=AUTH_CODE_HERE" \
  -d "redirect_uri=https://your.app/callback" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "code_verifier=ORIGINAL_VERIFIER_FROM_STEP_1"
const params = new URLSearchParams({
  grant_type: 'authorization_code',
  code,
  redirect_uri: 'https://your.app/callback',
  client_id: 'YOUR_CLIENT_ID',
  code_verifier: codeVerifier,
});

const res = await fetch('https://auth.securely.io/oauth/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: params,
});
const tokens = await res.json();
using var http = new HttpClient();
var body = new FormUrlEncodedContent(new Dictionary<string, string> {
    ["grant_type"]    = "authorization_code",
    ["code"]          = code,
    ["redirect_uri"]  = "https://your.app/callback",
    ["client_id"]     = "YOUR_CLIENT_ID",
    ["code_verifier"] = codeVerifier,
});
var res = await http.PostAsync("https://auth.securely.io/oauth/token", body);
var tokens = await res.Content.ReadFromJsonAsync<TokenResponse>();
form := url.Values{
    "grant_type":    {"authorization_code"},
    "code":          {code},
    "redirect_uri":  {"https://your.app/callback"},
    "client_id":     {"YOUR_CLIENT_ID"},
    "code_verifier": {codeVerifier},
}
res, err := http.PostForm("https://auth.securely.io/oauth/token", form)

Confidential clients also include client_secret in the form body.

Step 7 — The token response

{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "eyJhbGciOiJSUzI1NiIs..."
}
FieldMeaning
access_tokenThe JWT you send as Authorization: Bearer … to the resource API.
token_typeAlways Bearer.
expires_inSeconds until the access token expires (one hour by default).
refresh_tokenSingle-use refresh token. See Access Tokens and Refresh Rotation.

What can go wrong

ErrorCauseFix
invalid_grantCode already used, expired, or code_verifier mismatchAuthorization codes are single-use. Start a new flow.
invalid_request — bad redirect_uriURI doesn't exactly match a registered redirectCheck exact string match including trailing slashes.
unauthorized_clientClient not authorized for this grantCheck your client config — third-party can't use client_credentials, second-party usually doesn't use authorization_code.
invalid_clientWrong client_id or (for confidential) wrong client_secretVerify credentials.


What’s Next

Did this page help you?