Skip to content

PKCE and URL-safe encoding

Mechanism

Asana creates a verifier in StartLogin with GenerateCodeVerifier(), sends GenerateCodeChallenge(code_verifier) with code_challenge_method = "S256", and returns the verifier in the login result's Context (lines 108–127).2

FinishLogin passes that context to TokenMethod. TokenMethod adds code_verifier to the token form only when Record.HasFields(context, "code_verifier") is true. Otherwise the field is omitted and the request continues without it (lines 129–154).3

The generator draws 50 characters from a 62-character ASCII alphabet with Number.RandomBetween (lines 217–223). The challenge helper hashes the verifier's ASCII bytes with SHA-256, converts the digest to Base64, replaces + with - and / with _, and removes = padding (lines 225–241). That matches the base64url, no-padding encoding used by the S256 method. Check RFC 7636 for the exact definition rather than relying on this summary.1

Anaplan takes a different approach. Its StartLogin sends the verifier itself as code_challenge with code_challenge_method = "plain", so there is no hashing step. Its verifier comes from two Text.NewGuid() values, and its Base64UrlEncodeWithoutPadding helper (lines 45–51) is defined but never called in the file.4

Choosing this shape

Use S256 with a verifier that is kept and returned at the token step, as Asana does. Use the plain method only when the provider requires it, and then accept that the challenge reveals the verifier to anyone who sees the authorization request. For a flow without PKCE, see OAuth2.

Adaptation and failure paths

Preserve the verifier across the callback, not the challenge. Asana stores the verifier in Context (line 126) and reads it in TokenMethod (line 151). If the context held the challenge instead, the token request would no longer carry the value the challenge was derived from.3

Review verifier generation separately from hashing. Number.RandomBetween is the generator at line 221, and the presence of SHA-256 does not assess its quality. Confirm that the verifier length and characters meet RFC 7636 (43 to 128 unreserved characters). The 50-character alphanumeric output at lines 219–221 falls within that range.1

TextEncoding.Ascii on line 233 is safe only because the generator at lines 219–221 emits ASCII letters and digits. Any change to the alphabet needs a review of that conversion.1

The missing-context branch in TokenMethod omits the verifier rather than generating a new one (lines 150–152). When a token exchange is rejected, compare the retained context, the method label, and the exact bytes hashed before changing unrelated credential code.3

See HMAC signing for another signing flow and credential access for the saved credential.

Examples

Asana/Asana.m · lines 217–241 Open original source ↗

GenerateCodeVerifier = () =>
    let
        ValidCharacters = Text.ToList("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456879"),
        StrLenght = 50,
        Result = Text.Combine(List.Transform( {1..StrLenght}, each ValidCharacters{Int32.From(Number.RandomBetween(0, List.Count(ValidCharacters)-1))}))
    in
        Result;

GenerateCodeChallenge = (code_verifier) =>
    let
        hash = Replace(HashString(code_verifier))
    in
        hash;

HashString = (str as text) =>
    let
        result = Binary.ToText(Crypto.CreateHash(CryptoAlgorithm.SHA256, Text.ToBinary(str, TextEncoding.Ascii)), BinaryEncoding.Base64)
    in
        result;

Replace = (str) =>
    let
        result = Text.Replace(Text.Replace(Text.Replace(str, "+", "-"), "/", "_"), "=", "")
    in
        result;

The login start creates the verifier and sends its challenge:

Asana/Asana.m · lines 108–127 Open original source ↗

StartLogin = (resourceUrl, state, display) =>
    let
        code_verifier = GenerateCodeVerifier(),
        authorizeUrl = authorize_uri & "?" & Uri.BuildQueryString([
            response_type = "code",
            client_id = client_id,
            redirect_uri = redirect_uri,
            state = state,
            display_ui = "always",
            code_challenge = GenerateCodeChallenge(code_verifier),
            code_challenge_method = "S256"
        ])
    in
        [
            LoginUri = authorizeUrl,
            CallbackUri = redirect_uri,
            WindowHeight = 720,
            WindowWidth = 1024,
            Context = [code_verifier = code_verifier]
        ];

The callback reads the saved verifier and adds it to the token form:

Asana/Asana.m · lines 129–154 Open original source ↗

FinishLogin = (context, callbackUri, state) =>
    let
        // parse the full callbackUri, and extract the Query string
        parts = Uri.Parts(callbackUri)[Query],
        // if the query string contains an "error" field, raise an error
        // otherwise call TokenMethod to exchange our code for an access_token
        result = if (Record.HasFields(parts, {"error", "error_description"})) then
                    error Error.Record(parts[error], parts[error_description], parts)
                 else
                    TokenMethod("authorization_code", "code", parts[code], context)
    in
        result;

TokenMethod = (grantType, tokenField, code, context) =>
    let
        queryString = [
            grant_type = grantType,
            redirect_uri = redirect_uri,
            client_id = client_id
        ],
        queryWithCodeVerifier =
            if Record.HasFields(context, "code_verifier") then
                Record.AddField(queryString, "code_verifier", context[code_verifier])
            else queryString,

        queryWithCode = Record.AddField(queryWithCodeVerifier, tokenField, code),

  1. Asana/Asana.m lines 217–241 hold the verifier generator, the S256 challenge helper, and the URL-safe replacement; lines 217–223 define the 50-character generator. ↩↩↩

  2. Asana/Asana.m lines 108–127 hold StartLogin, which builds code_challenge with S256 and returns Context = [code_verifier = code_verifier]. ↩

  3. Asana/Asana.m lines 129–154 hold FinishLogin and the start of TokenMethod, including the code_verifier check at lines 150–152 and the context read at line 151. ↩↩↩

  4. Anaplan/Anaplan.pq lines 54–78 hold StartLogin, which sends code_challenge = codeVerifier with code_challenge_method = "plain" (lines 67–68); lines 45–51 define the unused Base64 helper. ↩