Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 13

    OAuth, OpenID Connect and Authorization Code with PKCE

    A stolen code is not the verifier

    An interceptor obtains the authorization code from a code flow but does not possess the transaction's PKCE verifier. At which exchange should the request fail? Now consider a client that compares state strings but never binds the value to a browser transaction.

    OAuth delegates access to a resource; OpenID Connect supplies identity assertions to the client. Use the message trace to assign a job to the code, verifier, state, nonce and each token rather than treating them as interchangeable secrets.

    Authorization Code with PKCE

    1. The client creates a fresh high-entropy code verifier and an S256 challenge for this transaction.
    2. The browser goes to the authorization endpoint with the challenge, state and a registered redirect URI, using exact matching except for the permitted port variation in native-app loopback redirects.
    3. The authorization server authenticates the user and returns a short-lived code.
    4. The client sends the code, verifier and the same redirect URI to the token endpoint over TLS; a confidential client also authenticates.
    5. The client uses an access token intended for the resource API.

    PKCE binds code redemption to possession of the transaction's verifier, not to a client's identity. It does not replace confidential-client authentication. An unpredictable, one-time state securely bound to the initiating browser transaction helps defend against login CSRF; comparing two strings alone is not enough. See RFC 7636, section 4 and RFC 9700, section 2.1.

    Client categories

    A public client such as a typical native app or browser-only application cannot keep a distributed static client secret confidential. For the authorization code grant, RFC 9700 requires PKCE for public clients and recommends it for confidential clients. A confidential server application must also authenticate at the token endpoint, preferably with an asymmetric method when supported.

    For machine-to-machine calls without interactive user delegation, the client credentials grant can authorize the application to access its own or previously agreed resources. Workload and managed identities are identity/credential-management mechanisms, not separate OAuth grant names. Use narrow application permissions and prefer short-lived tokens and asymmetric or platform-managed credentials over widely copied secrets.

    BFF trade-off

    A backend-for-frontend acts as a confidential client, completes the OAuth flow and uses tokens on the server without exposing them to frontend JavaScript. Server-side session storage leaves only a session identifier in the browser cookie; protected client-side session storage is also possible, but is not server-only token storage. This reduces token exposure to JavaScript but introduces cookie, CSRF, BFF availability and session-revocation responsibilities. Use HTTPS, Secure/HttpOnly cookies, an appropriate SameSite policy and CSRF defenses; malicious JavaScript can still make requests through the user's session. See RFC 10017, section 6.1.

    Red flags

    • Access tokens in query strings.
    • Wildcard or loosely matched redirect URIs.
    • Implicit or password grants in a new design.
    • ID tokens accepted by a resource API.
    • Long-lived browser tokens stored where injected JavaScript can read them.

    Strong answers explain why the chosen flow fits the client and threat model, not simply that it is the newest option.

    Worked example: PKCE, state and redirect URIs in C#

    ASP.NET Core 10's OpenID Connect handler generates S256 PKCE for ResponseType = "code" (UsePkce defaults to true) and handles protected state, browser correlation and nonce validation. Redirect registration and matching remain authorization-server responsibilities. Interviewers still ask how it works, and you will need it when you review a hand-written client or a mobile app.

    The program below illustrates the RFC 7636 test vector and local verifier, state and redirect-string comparisons. It is not an OAuth client or token endpoint: it has no authorization code, browser session, one-time state consumption, client authentication, network exchange or ID-token validation, and omits verifier input validation. Use a maintained protocol library for a real flow.

    C#
    // PKCE (RFC 7636): S256 challenge = BASE64URL(SHA256(ASCII(code_verifier))). State is compared in constant time,
    // and the redirect URI is compared exactly, never with StartsWith.
    using System.Security.Cryptography;
    using System.Text;
    
    static string Base64Url(byte[] b) => Convert.ToBase64String(b).TrimEnd('=').Replace('+', '-').Replace('/', '_');
    static string Challenge(string verifier) => Base64Url(SHA256.HashData(Encoding.ASCII.GetBytes(verifier)));
    
    // 1) The RFC 7636 Appendix B test vector.
    const string rfcVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
    Console.WriteLine($"RFC vector challenge: {Challenge(rfcVerifier)}");
    Console.WriteLine($"matches RFC 7636:     {Challenge(rfcVerifier) == "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"}");
    
    // 2) A fresh verifier: 32 random bytes -> 43 base64url characters (the allowed range is 43 to 128).
    string verifier = Base64Url(RandomNumberGenerator.GetBytes(32));
    Console.WriteLine($"new verifier length:  {verifier.Length}");
    
    // 3) Only the PKCE comparison: no authorization code or token endpoint is implemented here.
    string stored = Challenge(verifier);
    bool Redeem(string presented) => CryptographicOperations.FixedTimeEquals(
        Encoding.ASCII.GetBytes(Challenge(presented)), Encoding.ASCII.GetBytes(stored));
    Console.WriteLine($"redeem with right verifier:  {Redeem(verifier)}");
    Console.WriteLine($"redeem with stolen code only (attacker's own verifier): {Redeem(Base64Url(RandomNumberGenerator.GetBytes(32)))}");
    
    // 4) Only a state-value comparison: browser binding and one-time use are not implemented here.
    string state = Base64Url(RandomNumberGenerator.GetBytes(16));
    bool StateOk(string returned) => CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(returned), Encoding.ASCII.GetBytes(state));
    Console.WriteLine($"callback with our state:     {StateOk(state)}");
    Console.WriteLine($"callback with forged state:  {StateOk("forged-state-value-0")}");
    
    // 5) Prefix matching accepts unregistered paths; this is a string comparison, not an HTTP request.
    const string registered = "https://app.example.com/callback";
    foreach (var uri in new[] { "https://app.example.com/callback", "https://app.example.com/callback.evil.net", "https://app.example.com/callback/../steal" })
        Console.WriteLine($"{uri,-48} StartsWith={uri.StartsWith(registered),-5} Exact={string.Equals(uri, registered, StringComparison.Ordinal)}");

    Illustrative expected output (spacing simplified; the random attacker verifier is expected not to match):

    Text
    RFC vector challenge: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
    matches RFC 7636:     True
    new verifier length:  43
    redeem with right verifier:  True
    redeem with stolen code only (attacker's own verifier): False
    callback with our state:     True
    callback with forged state:  False
    https://app.example.com/callback                 StartsWith=True  Exact=True
    https://app.example.com/callback.evil.net        StartsWith=True  Exact=False
    https://app.example.com/callback/../steal        StartsWith=True  Exact=False

    Reading the output

    • The expected challenge is the published RFC 7636 Appendix B value. It illustrates SHA-256 and base64url encoding (no padding, - and _).
    • 32 random bytes give a 43-character verifier, the minimum length the RFC allows. It must come from a cryptographic random generator, never Random or a GUID.
    • With S256 correctly enforced, an interceptor who lacks the verifier cannot redeem the code. PKCE does not protect a compromised client or a leaked verifier. The local Redeem function illustrates only the challenge comparison, not all token-endpoint checks.
    • The unequal state value is expected to fail the local comparison. A real client must also bind state to the initiating browser transaction, reject missing/expired values and consume it once; this console example cannot demonstrate login-CSRF protection.
    • StartsWith accepts https://app.example.com/callback.evil.net, a different path on the same host. Authorization servers must use exact registered redirect-URI matching, except for the permitted port variation in native-app loopback redirects (RFC 9700, section 2.1; RFC 8252, section 7.3). The HTTPS web callback in this example has no such exception.

    The flow, message by message

    This schematic uses a public client and a query-mode callback. Values are placeholders; real requests use proper URL/form encoding and TLS.

    Text
    1. Client        : verifier = BASE64URL(random(32 bytes)); challenge = S256(verifier)
                       create fresh state and nonce; securely bind transaction data to this browser
    2. Browser  ->  /authorize?response_type=code&client_id=spa&redirect_uri=<exact>&scope=openid%20orders.read
                              &code_challenge=<challenge>&code_challenge_method=S256&state=<state>&nonce=<nonce>
    3. IdP           : authenticates the user or reuses a valid session; obtains authorization/consent as needed
    4. IdP -> Browser: 302 <redirect_uri>?code=<short-lived code>&state=<state>
    5. Client        : validates state/correlation; POST /token with grant_type=authorization_code,
                       client_id=spa, code, redirect_uri and code_verifier
    6. IdP           : checks PKCE, code validity/expiry/one-time use, client binding and redirect_uri
    7. IdP -> Client : access_token (for the API), id_token (for the client), refresh_token (if allowed)
    8. Client        : validates the ID token before accepting sign-in, including nonce when sent

    A confidential client also authenticates at the token endpoint using its registered method; PKCE is not a substitute. In this flow the token-request redirect URI must equal the URI used in the authorization request, including the selected loopback port. This is distinct from the limited port exception when matching a native app against its registered redirect URI.

    nonce binds an ID token to its authentication request. If sent, it must be present and match; use a fresh, browser-bound value and reject replay. A nonce comparison alone does not validate a token: the client must also validate the trusted issuer, client audience, expiry and the applicable signature/algorithm checks. It is not interchangeable with state. See OpenID Connect Core, section 3.1.3.7.

    Which flow for which client

    clientflowwhy
    Server-rendered web app (MVC, Razor Pages)Authorization code + PKCE, confidential clientit can keep a secret or, better, a private key for client authentication
    SPA (React, Angular, Blazor WebAssembly)Authorization code + PKCE, or a BFF that does the code flow server-sidea browser-only client cannot keep a static client secret confidential; a BFF acts as a confidential client
    Native / mobileAuthorization code + PKCE through the system browserembedded web views let the host app inspect credentials and cookies; RFC 8252 forbids them for authorization
    Service to serviceClient credentials with asymmetric authentication where supported; a managed identity can obtain app-only tokens on supported platformsapplication permissions, not interactive user delegation; identity mechanism is distinct from grant type
    Input-constrained device or headless CLIDevice authorization grantthe user authorizes through a suitable browser elsewhere; a CLI with a usable browser can use code + PKCE

    For new designs, choose code + PKCE rather than implicit or resource owner password credentials. RFC 9700 says clients SHOULD NOT use implicit/access-token-in-authorization-response flows unless the specified injection and leakage risks are mitigated; the password grant MUST NOT be used (section 2.4). For browser-based clients, RFC 10017, section 7.2 is stricter: they MUST NOT use implicit to obtain access tokens.

    ASP.NET Core configuration for a server-side web app

    This ASP.NET Core 10 excerpt assumes the OIDC package, authentication namespaces, provider registration and HTTPS callback configuration. It is not a complete app or BFF. Keep the handler's validation and correlation protections enabled. The conceptual query-mode diagram above is not the handler's exact wire trace: its default response mode is form_post, and it uses pushed authorization requests when the provider advertises support. See the Microsoft configuration guide and pinned .NET 10 options.

    C#
    builder.Services.AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(o =>
    {
        o.Authority = "https://login.example.com";
        o.ClientId = "orders-web";
        o.ClientSecret = builder.Configuration["Oidc:ClientSecret"]; // from a secret store, never source control
        o.ResponseType = "code";      // authorization code flow
        o.UsePkce = true;             // already the default; stated for reviewers
        o.SaveTokens = true;          // saves received tokens in AuthenticationProperties; see storage caveat below
        o.MapInboundClaims = false;
        o.Scope.Add("orders.read");
    });

    SaveTokens defaults to false. With true and the plain .AddCookie() configuration above, received tokens become part of the protected authentication ticket carried by the browser cookie, not a server-only token vault. A BFF that keeps tokens off the browser needs an appropriate server-side token/session store; a cookie SessionStore (ITicketStore) can keep the ticket server-side and send a protected session identifier instead. SaveTokens does not itself refresh tokens or configure that store. See the pinned token-storage option and cookie handler.

    What did the state comparison prove?

    The console PKCE example prints False for a forged state value. What has that single result established?

    A That local comparison rejected this unequal value; browser binding, expiry and one-time transaction consumption still need a real client flow.
    B That every callback is protected against login CSRF without browser transaction state.
    C That PKCE authenticated this client at the token endpoint.
    D That a matching state value replaces all ID-token signature, issuer, audience and nonce checks.
    Show answer

    Correct answer: A

    The example implements value comparisons only, not an OAuth client or token endpoint. A real state-based defense needs an unpredictable value bound to the initiating browser transaction and a checked lifecycle. PKCE, confidential-client authentication and full ID-token validation have separate jobs.

    Explain the boundary

    Trace the client, authorization server and resource API separately. Assign each credential to its intended recipient.

    1. "What does PKCE protect against, and how is it different from state?"
    1. "Why not put the access token in the redirect URL?"
    1. "Can a resource API accept an ID token?"
    1. "A partner backend calls your API nightly. Which grant?"

    Stop here. State the transaction binding or token check that your answer depends on.

    Compare your reasoning

    1. PKCE rejects code redemption without the matching verifier when correctly enforced; it is not client authentication. One-time, browser-bound state correlates the callback and helps prevent login CSRF. Using both is common; RFC 9700 also permits relying on PKCE for CSRF protection when the client has ensured server support and securely binds the PKCE transaction to the browser.
    1. URLs end up in history, logs and Referer headers. The code flow returns a short-lived, one-time code instead, and the tokens travel in the back-channel token response.
    1. No. The ID token's audience is the client, and it describes the sign-in event. The API needs an access token whose audience is the API.
    1. For app-only access, client credentials with narrow application permissions and asymmetric client authentication, such as mutual TLS or private_key_jwt. A supported workload or managed identity can remove application-managed shared secrets, but is not itself a grant type. If access must be delegated by a particular user, that is a different authorization requirement.

    Quick reference

    concernanswer
    OAuth vs OpenID ConnectOAuth delegates access to an API; OIDC adds the ID token and identity claims for the client
    PKCEcode_challenge = BASE64URL(SHA256(ASCII(code_verifier))), method S256; fresh cryptographic verifier, 43 to 128 unreserved characters; not client authentication
    state / noncefresh, browser-bound transaction values; consume state once and check nonce/replay as part of full ID-token validation
    redirect URIexact match against the registered value, except the permitted native-app loopback port variation; never StartsWith (RFC 9700 / RFC 8252)
    which flowweb app, SPA, native app: authorization code + PKCE; app-only service access: client credentials; constrained device/headless CLI: device authorization grant
    never in a new designimplicit grant, password grant, tokens in query strings, ID tokens accepted by an API
    ASP.NET Coreset ResponseType = "code"; UsePkce defaults to true; SaveTokens stores tokens in the ticket, not automatically server-side
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·