📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between OAuth 2.0 and OpenID Connect? Explain the roles, the authorisation code flow with PKCE, the client credentials flow, which flows are deprecated and why, and where OAuth 2.1 is heading.

OAuth 2.0 (delegated authorisation) vs OpenID Connect (authentication on top), the four roles, authorisation code + PKCE, client credentials, deprecated implicit and password flows, RFC 9700 and the OAuth 2.1 draft.

Mid-Level Theory Intermediate authentication entra-id oauth2 openid-connect pkce security

🎯 Key points

  • OAuth 2.0 = delegated authorisation (access tokens for APIs); OIDC = identity layer (ID token, userinfo, discovery)
  • Roles: resource owner, client, authorisation server, resource server
  • Authorisation code + PKCE (code_verifier, code_challenge_method=S256) for web, SPA and mobile; stops code interception and injection
  • Client credentials for service-to-service; authenticate with a certificate, workload identity federation or managed identity
  • Implicit and password grants: long discouraged, formally deprecated by RFC 9700 (OAuth 2.0 Security BCP, January 2025)
  • ID token: client validates iss, aud = its client id, nonce and signature; access token: API validates aud = the API
  • OAuth 2.1 is still an IETF Internet-Draft (draft 16, September 2026), not an RFC: PKCE for all, no implicit or password grant, exact redirect URI matching
  • state and nonce protect against CSRF on the callback and replay

⏱ 30-second answer

OAuth 2.0 is a framework for delegated authorisation: a client gets an access token to call an API on a user's (or its own) behalf. It says nothing about who the user is. OpenID Connect is a thin identity layer on top that adds the ID token (a JWT about the user, for the client), the userinfo endpoint and discovery metadata.

  • Authorisation code + PKCE: the browser gets a one-time code, and the client swaps it for tokens, proving with a code_verifier that it started the flow. Use it for web apps, SPAs and mobile.
  • Client credentials: a service authenticates as itself; no user.
  • Implicit and password flows are deprecated (RFC 9700); OAuth 2.1, still an IETF draft in late 2026, makes that official.

The trade-off: the redirect-based flows are more moving parts, but credentials never touch your app.

🗣 Full answer (senior)

How I would answer this in an interview

"OAuth 2.0 answers 'may this client call this API?'. There are four roles: the resource owner, usually the user; the client, the app that wants access; the authorisation server, such as Microsoft Entra ID; and the resource server, the API. The output is an access token whose audience is the API. OAuth deliberately doesn't define authentication, which is why people used to misuse access tokens as proof of login. OpenID Connect fixes that: you add the openid scope and the authorisation server also returns an ID token, a signed JWT whose audience is the client and which says who the user is and when and how they signed in, plus a standard discovery document and userinfo endpoint.

The flow I use for anything with a user is authorisation code with PKCE. The client creates a random code_verifier, sends its SHA-256 hash as code_challenge with the redirect to the authorisation server, the user signs in there, the browser comes back with a short-lived code, and the client exchanges code plus verifier for tokens over a back channel. PKCE means an intercepted code is useless. For daemons and service-to-service calls I use client credentials, ideally with a certificate or a managed identity rather than a secret. The implicit flow, which returned tokens in the URL fragment, and the password grant, where the app collects the user's password, are deprecated by the OAuth 2.0 Security Best Current Practice, RFC 9700.

The mistake I see is APIs accepting ID tokens as if they were access tokens, or SPAs still using implicit flow from an old tutorial. The senior line: OIDC tells the client who the user is, OAuth tells the API what the caller may do, and you should never mix up the two tokens."


OAuth 2.0 vs OpenID Connect

OAuth 2.0 (RFC 6749) OpenID Connect 1.0
Purpose Delegated access to APIs Authenticating the user to the client
Main artefact Access token (audience = API) ID token (audience = client)
Extras Scopes, refresh tokens openid scope, nonce, userinfo, discovery, standard claims
ASP.NET Core AddJwtBearer on the API AddOpenIdConnect + cookie in the web app

Flows

Flow Who uses it Status
Authorisation code + PKCE Web apps, SPAs, mobile, desktop Recommended for all user sign-ins
Client credentials Daemons, service-to-service Recommended; prefer certificates or managed identity
Device authorisation (RFC 8628) CLIs, TVs, devices without a browser Fine for those cases
On-behalf-of / token exchange (RFC 8693) API calling a downstream API as the user Fine; Entra ID calls it OBO
Implicit Old SPAs Deprecated: tokens in URLs and history
Resource owner password Legacy first-party apps Deprecated: app sees the password, breaks MFA

OAuth 2.1 (as of November 2026)

Still an Internet-Draft (revision 16, September 2026), not an RFC. It consolidates OAuth 2.0 with RFC 9700: PKCE required for all clients using the code flow, no implicit or password grants, exact redirect URI matching, no bearer tokens in query strings, and refresh tokens for public clients must be sender-constrained or rotated. Most identity platforms already behave this way, so designing to it today costs nothing.

Production example

At [company] a React SPA used implicit flow and kept access tokens valid for [one hour] in sessionStorage. We moved to authorisation code with PKCE through MSAL.js, then to a BFF so tokens left the browser entirely; token-related findings in the next pen test went from [4] to [0].

🔍 What the interviewer is checking

Checks that the candidate knows which protocol solves which problem and can pick the right flow and token for each client.

Green flags

  • Clearly separates access token (API) from ID token (client)
  • Explains PKCE mechanically (verifier, S256 challenge)
  • Knows implicit and password grants are deprecated and why
  • Mentions scopes vs app roles and validating them in the API
  • States OAuth 2.1 accurately as a draft that consolidates current best practice

Red flags

  • 'OAuth is for login'
  • Recommends implicit flow for SPAs
  • Can't say what PKCE protects against

📚 Learn in depth

1. The authorisation code flow with PKCE

Browser            Client (web app/BFF)           Authorisation server          API
   |  GET /login  ->     |                                   |                        |
   |                     | verifier = random(32 bytes)       |                        |
   |                     | challenge = BASE64URL(SHA256(verifier))                    |
   | <- 302 /authorize?response_type=code&client_id&redirect_uri&scope=openid api://orders/read
   |                       &state&nonce&code_challenge&code_challenge_method=S256      |
   |  ------------------------------------------------------>  user signs in, MFA   |
   | <- 302 redirect_uri?code=abc&state=...                     |                        |
   |  GET /signin-oidc?code=abc -> |                           |                        |
   |                     | POST /token code + verifier (+ client auth) ->             |
   |                     | <- id_token, access_token, refresh_token                   |
   |                     | validate id_token (iss, aud=client, nonce, signature)      |
   | <- Set-Cookie session|                                    |                        |
   |                     | GET /orders  Authorization: Bearer access_token  ------->  |
  • state ties the response to the request (CSRF on the callback).
  • nonce ties the ID token to the request (replay).
  • PKCE ties the code exchange to whoever started the flow, which protects public clients that can't keep a secret and also stops code injection for confidential ones.

2. Why implicit and password grants died

Implicit returned the access token in the URL fragment: it leaked into browser history, referrers and logs, couldn't be sender-constrained, and had no refresh token. Browsers now support CORS and Web Crypto, so code + PKCE works in SPAs. The password grant trains users to type passwords into third-party apps and bypasses MFA, conditional access and passkeys.

3. Scopes, audiences and consent

Scopes (api://orders/Orders.Read) limit what a delegated token can do; the API must check them (scp claim). App roles (roles claim) are for application permissions in client credentials. The audience (aud) must equal the API's identifier.

4. In ASP.NET Core

  • Web app: AddAuthentication(Cookies).AddOpenIdConnect(...) with ResponseType = "code", UsePkce = true (default), SaveTokens = true to keep tokens in the cookie ticket for downstream calls.
  • API: AddJwtBearer validating audience and scopes.
  • Microsoft Entra ID: Microsoft.Identity.Web wraps both and adds token caching and OBO.
  • Since .NET 9, PushedAuthorizationBehavior lets the OIDC handler use Pushed Authorization Requests (RFC 9126) when the provider advertises it.

Try it yourself

  1. Register an app in a dev Entra tenant and sign in with AddOpenIdConnect; capture the redirect in browser dev tools and find code_challenge.
  2. Decode both the ID token and the access token at jwt.ms and compare aud.
  3. Call your API with the ID token and confirm it is rejected (wrong audience).
  4. Get a token with client credentials via az account get-access-token --resource api://... or MSAL and inspect the roles claim.
  5. Read the OAuth 2.1 draft's 'Differences from OAuth 2.0' section and list what your apps would need to change.

💻 Code

A web app signing users in with OpenID Connect (code + PKCE) and an API validating the access token and its scope.

// Web app: Program.cs (.NET 10)
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;          // session
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;        // login redirect
    })
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.Authority = builder.Configuration["Oidc:Authority"];
        options.ClientId = builder.Configuration["Oidc:ClientId"];
        options.ClientSecret = builder.Configuration["Oidc:ClientSecret"]; // from Key Vault, or use a certificate
        options.ResponseType = "code";        // authorisation code flow
        options.UsePkce = true;               // default, stated for clarity
        options.SaveTokens = true;            // keep the access token for downstream calls
        options.MapInboundClaims = false;
        options.Scope.Add("api://orders/Orders.Read");
        options.Scope.Add("offline_access");  // refresh token
    });

builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/", () => "Signed in").RequireAuthorization();
app.Run();
// API: require the delegated scope, not just a valid token.
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("orders.read", p => p.RequireAuthenticatedUser()
        .RequireAssertion(ctx => ctx.User.FindFirst("scp")?.Value.Split(' ').Contains("Orders.Read") == true));

app.MapGet("/orders", () => Results.Ok()).RequireAuthorization("orders.read");

⚠ Common mistakes

  • Mistake: Calling OAuth 2.0 an authentication protocol and using access tokens as proof of login. Why it is wrong: an access token is meant for the API and may not even be readable by the client; it says nothing reliable about the sign-in event. Instead: use OIDC and validate the ID token (issuer, aud equal to your client id, nonce, signature) in the client.
  • Mistake: Sending the ID token to APIs as a bearer token. Why it is wrong: its audience is the client, so a correctly configured API rejects it, while an API with audience validation turned off accepts ID tokens issued to any app in the tenant. Instead: request an access token for the API's scope and keep audience validation on.
  • Mistake: Still using the implicit flow in a SPA. Why it is wrong: tokens end up in URLs and history and there is no refresh token. Instead: authorisation code + PKCE via MSAL.js, or better a BFF.
  • Mistake: Using the password grant for a 'first-party' mobile app. Why it is wrong: it bypasses MFA, passkeys and conditional access, and is deprecated. Instead: code + PKCE in the system browser (ASWebAuthenticationSession / Custom Tabs).
  • Mistake: Skipping state and nonce checks in a hand-written client. Why it is wrong: the callback is open to CSRF and token replay. Instead: use the framework handler, which validates both.
  • Mistake: Client credentials with a long-lived client secret in config. Why it is wrong: secrets leak, get copied between environments and expire unexpectedly, causing outages. Instead: prefer a managed identity for Azure-hosted workloads, workload identity federation for GitHub Actions or Kubernetes, or a certificate kept in Key Vault; use a secret only as a last resort, stored in Key Vault with an expiry alert.
  • Mistake: APIs validating the token but not the scope or role. Why it is wrong: any app in the tenant that can get a token for the API can call every endpoint. Instead: require scp for delegated calls and roles for application calls.

🏛 Senior insight: trade-offs

The design question is not 'which flow' but 'where do the tokens live'. Code + PKCE is settled; the real decision for browser apps is whether tokens sit in JavaScript (MSAL.js) or behind a BFF with a cookie. I also push teams to stop distributing client secrets: certificates, workload identity federation and managed identities remove the most common OAuth incident, an expired or leaked secret.

Option When it fits Cost When not to
Code + PKCE with a confidential web app/BFF Server-rendered apps, SPAs with a backend Server session, Data Protection keys Pure static hosting with no backend
Code + PKCE in a public client (MSAL.js, mobile) Mobile apps, SPAs without a backend Tokens on the device; refresh token rotation needed High-risk data in the browser
Client credentials with managed identity Azure-hosted services calling Azure or your APIs None beyond role assignments Calls that must act as a specific user (use OBO)

OAuth 2.1 isn't final, but it is the right checklist today: if a design would break under 2.1, it is already against RFC 9700.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the tokens are JWTs Why: Checks they know how the API validates the access token
    How to answer

    A JWT is three base64url parts, header.payload.signature. The header says which algorithm and key (alg, kid) signed it; the payload holds claims (iss, aud, sub, exp, scopes); the signature proves nobody changed them. It is signed, not encrypted, so anyone holding it can read it: no personal or secret data.

    • RS256/ES256: the identity provider signs with a private key and APIs verify with the public key from its JWKS endpoint. HS256 uses one shared secret, so every verifier could also forge tokens.
    • In ASP.NET Core, AddJwtBearer with Authority and Audience validates issuer, audience, lifetime and signature (with a 5-minute ClockSkew).

    The trade-off: validation is local and fast, but a stolen token is valid until exp, so keep access tokens short-lived.

  2. When: Candidate says PKCE is only for mobile apps and SPAs Why: Checks understanding of authorisation code injection, not just public clients
    How to answer

    PKCE binds the code exchange to the session that started the flow. Without it, an attacker who obtains a victim's authorisation code (from logs, a leaky redirect or a malicious app) can inject it into their own session with the confidential client, which redeems it with its own secret, so the attacker ends up logged in as the victim. The client secret doesn't help, because the legitimate client is the one redeeming the code. The OAuth 2.0 Security Best Current Practice (RFC 9700, January 2025) therefore recommends PKCE for confidential clients too, and the OAuth 2.1 draft requires it for all clients. ASP.NET Core's OIDC handler enables it by default (UsePkce = true).

🛠 Real-world problems: how you handle them

SPA on implicit flow fails a pen test and breaks when third-party cookies go
Situation
A [customer portal] React SPA for [~40,000] Australian customers used the implicit flow against [the identity provider], with one-hour access tokens in `sessionStorage` and silent renew through a hidden iframe.
Signals
Pen test findings: tokens in browser history and Referer headers, no token binding. Separately, [Safari] users were logged out every hour because the iframe silent renew depended on third-party cookies, and support tickets about 'random logouts' rose to [~60 a week].
Investigation
Captured the flow in browser dev tools and saw `#access_token=` in the redirect URL; confirmed in the IdP sign-in logs that the app registration allowed implicit grant; checked the Referer on outbound calls to [an analytics domain] and found token fragments in its logs; reviewed RFC 9700 and the IdP's guidance.
Resolution
Immediately disabled implicit grant on the app registration after shipping MSAL.js with authorisation code + PKCE, which uses refresh tokens instead of iframes. Then built a small ASP.NET Core BFF (cookie + OIDC + YARP proxy) so the browser holds only an `HttpOnly` cookie and no tokens at all.
Prevention
An app-registration policy that forbids implicit grant; a checklist item in architecture review ('where do tokens live?'); a CSP that limits third-party scripts; an automated ZAP scan in the pipeline that flags tokens in URLs.

How to tell it (STAR)

**S:** Our [customer portal] SPA used implicit flow, and a pen test found access tokens in browser history and a third-party analytics log, while [Safari] users were being logged out hourly. **T:** I was asked to fix the findings without a big rewrite. **A:** I replaced implicit flow with authorisation code and PKCE through MSAL.js, which removed tokens from URLs and the iframe dependency, turned implicit grant off on the app registration, and then proposed and built a small BFF so tokens never reached JavaScript. **R:** The re-test closed all [4] token findings, 'random logout' tickets dropped from [~60 a week] to [a handful], and the BFF became the template for [two] other apps.

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me