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

📚 Interview question

Your company runs a dozen products with separate sign-ins and wants one identity platform for customers, staff and partner integrations: single sign-on, social logins, MFA, APIs secured with tokens, and machine-to-machine access. Would you build an authentication server yourself, run one such as Duende IdentityServer or Keycloak, or buy a managed service like Microsoft Entra External ID or Auth0? Design the platform and justify the choice.

A staff-level identity platform design and build-vs-buy decision: requirements and sign-in estimates, OAuth 2.0 and OpenID Connect flows (authorisation code with PKCE, client credentials), token design and lifetimes, signing keys and rotation, workforce vs customer identity (Entra ID vs Entra External ID), migration from separate user stores, availability and security (MFA, Essential Eight), and the costs of building versus running versus buying.

Staff / Architect SystemDesign Expert build-vs-buy entra-external-id identity oauth2 openid-connect system-design

🎯 Key points

  • Clarify: user populations (customers, staff, partners, machines), volumes, MFA and social logins, residency, branding, existing user stores
  • Separate workforce identity (Microsoft Entra ID) from customer identity (Entra External ID, Auth0, Okta CIC, or self-hosted)
  • Standards only, aligned with the OAuth 2.0 Security BCP (RFC 9700) and the OAuth 2.1 draft: code + PKCE for every client, exact redirect URIs, no implicit or password grants; client credentials for machines
  • Token design: short-lived access tokens (5–60 min), audience per API, minimal claims, refresh token rotation or sender-constrained tokens, BFF for browser apps
  • APIs validate locally: JwtBearer caches discovery and JWKS (periodic refresh, immediate refresh on unknown kid) and rejects expired tokens with a small ClockSkew
  • Signing keys in an HSM or Key Vault, published via JWKS, rotated with overlap
  • Identity is tier zero: multi-zone, synthetic sign-in monitoring, existing sessions survive an IdP outage
  • Buy managed by default; self-host a certified product only for residency, scale cost or deep customisation; never build a token server

⏱ 30-second answer

I'd buy, not build. Identity is security-critical, standards-heavy and tier zero: if sign-in is down, every product is down. I separate workforce identity (staff in Microsoft Entra ID) from customer identity (Entra External ID, Auth0 or Okta CIC), and federate partners. Everything speaks OpenID Connect and OAuth 2.0: authorisation code with PKCE for web and mobile, client credentials for machines, short-lived access tokens with one audience per API, refresh token rotation and a BFF for browser apps. If residency, scale cost or customisation rule out SaaS, I'd run a certified product such as Duende IdentityServer or Keycloak, never write my own token server. The trade-off: managed services cost per user and constrain customisation; self-hosting gives control but makes your team responsible for patching, keys and 24/7 availability of the most attacked component you own.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd start with populations and numbers: [two million] customer accounts across the products, [3,000] staff, [40] partner integrations and [hundreds] of internal services. Requirements: single sign-on across products, Google and Apple sign-in for customers, MFA everywhere for staff and step-up for sensitive customer actions, branded sign-in pages per product, data in Australia, and a migration from [twelve] existing user tables.

The first decision is that staff and customers are different problems. Staff belong in Microsoft Entra ID with Conditional Access, phishing-resistant MFA and lifecycle from HR, which also covers Essential Eight MFA expectations. Customers need self-service sign-up, social logins, branding and scale, which is what Entra External ID, Auth0 or Okta's customer identity product are built for. Partners federate or use client credentials.

Then build versus buy. Building an authorisation server means implementing OpenID Connect correctly, protecting signing keys, rate-limiting credential stuffing, handling MFA, recovery, breached-password checks and keeping up with specs like OAuth 2.1 and passkeys, and running it at higher availability than any product it serves. For example, at [company] we [maintained a home-grown token service], and [a signing-key handling flaw found in a pen test] [led us to move to a managed provider within two quarters]. I'd only self-host if residency or cost at our scale ruled out SaaS, and then I'd run a certified product like Duende IdentityServer, which is commercially licensed, or Keycloak.

The design itself is standard: the authorisation code flow with PKCE for every interactive app, a BFF so browser apps keep tokens server-side, client credentials with certificates or managed identities for machines, access tokens of [10–60 minutes] with an audience per API, refresh token rotation with reuse detection, and APIs validating tokens locally against the JWKS so the identity provider isn't on every request's path. Migration is just-in-time: on first sign-in we verify against the old hash, then create the user in the new store.

The mistake I see is treating identity as just another microservice. It's the most attacked component and the one every product depends on."


Requirements

Type Requirement Assumption
Functional SSO across 12 products, social logins, MFA, step-up Passkeys on the roadmap
Functional Machine-to-machine and partner access Client credentials, federation
Functional Self-service sign-up, recovery, profile, consent Branding per product
Non-functional Sign-in availability 99.95%+ Tier zero
Non-functional Data residency where possible in Australia Check provider regions
Non-functional Resist credential stuffing and phishing Bot protection, MFA, breached-password checks

Capacity estimate

Quantity Arithmetic Result
Monthly active customers 2M accounts × 40% 800,000 MAU (drives SaaS pricing)
Interactive sign-ins 800,000 × 8/month 6.4M/month ≈ 2.5/s avg, peak ×10 ≈ 25/s
Token refreshes 800,000 active × 20/day on active days ≈ 100–200/s at peak
Machine tokens 500 services × 1 per 50 min (cached) < 1/s (if cached!)
API token validations All API calls Local, no IdP call

The identity provider handles sign-ins and refreshes, not every API call, which is why local JWT validation matters.

High-level design

Staff ──► Microsoft Entra ID (Conditional Access, phishing-resistant MFA) ─┐
                                                                      │ federation for admin tools
Customers ─► Product web (BFF) / mobile app ── OIDC code + PKCE ──► Customer IdP (Entra External ID / Auth0)
                                                                 │   ├─ social: Google, Apple
                                                                 │   ├─ MFA, bot protection, breached-password checks
                                                                 │   └─ JIT migration hook ──► legacy user stores
                                                                 ▼
                                          Access token (aud = orders-api, 15 min) + refresh token (rotating)
APIs (ASP.NET Core) ── validate locally via cached JWKS ── authorise with scopes/roles + own permission data
Services / partners ── client credentials (cert / managed identity) ──► token ──► APIs

Build vs run vs buy

Option Control Effort and risk Cost profile Fits
Build your own token server Total Highest; security and spec burden Engineers forever Almost never
Run Duende IdentityServer / Keycloak High; your hosting and data Patching, keys, 24/7 ops Licence (Duende) + infra + ops Residency, heavy customisation, very large MAU
Managed CIAM (Entra External ID, Auth0, Okta CIC) Moderate; configuration and extensions Lowest Per MAU / per feature Most companies
Entra ID for workforce Moderate Low Per user licences, often already owned Staff, always

Production example

A group with [nine] products and [1.5M] customer accounts moved from separate user tables to a managed customer identity provider with just-in-time migration: [70%] of active users migrated silently within [six weeks], account-takeover incidents fell by [about 80%] after MFA and breached-password detection, and new products integrated sign-in in [days instead of a sprint].

🔍 What the interviewer is checking

Checks staff-level judgement on a security-critical build-vs-buy decision, plus correct use of OpenID Connect and OAuth 2.0, token design, key management, availability and migration.

Green flags

  • Separates workforce and customer identity
  • Standard flows only: code + PKCE, client credentials; BFF for browsers
  • Short tokens, audience per API, local validation, key rotation
  • Treats identity as tier zero and plans migration and exit
  • Justifies buy vs run with cost, residency and risk

Red flags

  • Proposes writing a custom auth server
  • Implicit or password grants
  • Long-lived tokens or one audience for everything
  • IdP called on every API request

📚 Learn in depth

1. The protocols, briefly

  • OAuth 2.0 delegates access: a client gets an access token for a resource (API).
  • OpenID Connect adds authentication: an ID token describing the user, plus discovery (/.well-known/openid-configuration) and JWKS for keys.
  • Flows: authorisation code + PKCE for all interactive clients, client credentials for machines, device code for TVs and CLIs. The implicit and resource-owner password grants are deprecated (OAuth 2.0 Security BCP; omitted from the OAuth 2.1 draft).

2. Token design

| Token | Lifetime | Contents | Notes | |---|---|---|---| | ID token | Minutes | Who signed in | For the client only, never sent to APIs | | Access token | 5–60 min | sub, aud, scp/roles, iss, exp | One audience per API; minimal claims | | Refresh token | Days to weeks, sliding | Opaque | Rotation + reuse detection; server-side in a BFF | Keep permissions that change often out of tokens; look them up in the API with caching. Revocation of JWTs is hard, so short lifetimes are the control.

3. Signing keys

Asymmetric keys (RS256/ES256) held in an HSM or Key Vault. The IdP publishes current and next keys in JWKS; APIs cache JWKS and refresh on unknown kid. Rotate with overlap (publish new, start signing, retire old after max token lifetime). Managed providers do this for you; self-hosting means you own it.

4. Workforce vs customer identity

Workforce: Entra ID, Conditional Access, device compliance, privileged identity management, HR-driven joiner-mover-leaver. Customer: self-service sign-up, social and local accounts, progressive profiling, consent, branding, bot protection and scale to millions. Mixing them in one tenant creates policy conflicts and licence surprises.

5. Availability

Sign-in outage = all products down for new sessions. Mitigations: managed provider SLA and multi-region; APIs validate tokens locally so existing sessions continue; longer refresh windows during incidents; status monitoring with synthetic sign-ins every minute from Australia.

6. Security controls

Phishing-resistant MFA (passkeys/FIDO2) for staff and admins (ACSC Essential Eight maturity levels expect strong MFA); MFA or step-up for customers on sensitive actions; credential stuffing protection (rate limits, bot detection, breached-password checks); account recovery that isn't weaker than sign-in; audit logs of sign-ins to your SIEM (Microsoft Sentinel).

7. Migration

Just-in-time: the new IdP calls a migration API with the entered password; you verify against the legacy hash (bcrypt, PBKDF2, ASP.NET Core Identity's format) and return the profile; the IdP stores a new hash. After a period, bulk-import the rest with a forced reset. Map old user ids to the new sub so product data links up.

8. Residency and cost check

Confirm where each provider stores customer data and whether an Australian or APAC region is available for your tenant, and price at your MAU with the features you need (MFA, custom domains, enterprise federation). Self-hosting costs: licence (Duende is commercial above small-company thresholds; Keycloak is open source), infrastructure, and the engineers on call.

9. AWS mapping

Amazon Cognito user pools for customers, IAM Identity Center for workforce, IAM roles for machines.

Try it yourself

  1. Register a web app and an API in an Entra External ID or Auth0 dev tenant and sign in with code + PKCE.
  2. Call the API with a token for the wrong audience and confirm 401.
  3. Rotate a signing key in a local IdentityServer or Keycloak and watch the API refresh JWKS.
  4. Write a JIT migration endpoint that verifies an ASP.NET Core Identity password hash.
  5. Run a synthetic sign-in check every minute and alert on failure.

💻 Code

An API validating tokens locally from the provider's metadata (audience per API, short clock skew), a BFF using code + PKCE with server-side tokens, and a service calling an API with client credentials.

// Orders API: validates JWTs locally using cached JWKS from the issuer's metadata.
using Microsoft.AspNetCore.Authentication.JwtBearer;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = builder.Configuration["Identity:Authority"]; // discovery + JWKS, refreshed on unknown kid
        o.Audience = "api://orders";                              // tokens for other APIs are rejected
        o.MapInboundClaims = false;
        o.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(1); // default is 5 min
    });

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("orders.read", p => p.RequireClaim("scope", "orders.read"))
    .AddPolicy("orders.write.machine", p => p.RequireClaim("roles", "Orders.Write"));

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/orders/{id:guid}", (Guid id) => Results.Ok(new { id })).RequireAuthorization("orders.read");
app.Run();
// Product web BFF: OIDC code flow with PKCE; tokens stay server-side, the browser gets a cookie.
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

builder.Services.AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(o => { o.Cookie.SameSite = SameSiteMode.Lax; o.Cookie.SecurePolicy = CookieSecurePolicy.Always; })
    .AddOpenIdConnect(o =>
    {
        o.Authority = builder.Configuration["Identity:Authority"];
        o.ClientId = builder.Configuration["Identity:ClientId"];
        o.ClientSecret = builder.Configuration["Identity:ClientSecret"]; // from Key Vault; prefer a certificate
        o.ResponseType = "code";
        o.UsePkce = true;
        o.SaveTokens = true;                        // stored in the auth session, not exposed to JavaScript
        o.Scope.Add("offline_access");
        o.Scope.Add("api://orders/orders.read");
        o.MapInboundClaims = false;
    });
// Service-to-service: client credentials with token caching (Microsoft.Identity.Client).
using Microsoft.Identity.Client;

namespace Billing;

public sealed class OrdersApiTokenProvider(IConfidentialClientApplication app)
{
    private static readonly string[] Scopes = ["api://orders/.default"];

    // MSAL caches the token and only calls the IdP near expiry: no token request per API call.
    public async Task<string> GetTokenAsync(CancellationToken ct) =>
        (await app.AcquireTokenForClient(Scopes).ExecuteAsync(ct)).AccessToken;
}

⚠ Common mistakes

  • Mistake: Writing your own token server or JWT issuing endpoint. Why it is wrong: subtle protocol and key-handling flaws become account takeovers across every product. Instead: a managed provider, or a certified product you run.
  • Mistake: Putting staff and customers in one identity system. Why it is wrong: conflicting policies, licensing surprises and a bigger blast radius. Instead: Entra ID for workforce, a CIAM product for customers.
  • Mistake: Using the implicit or password grant. Why it is wrong: tokens leak via URLs or apps handle raw passwords; both are deprecated. Instead: authorisation code + PKCE, client credentials for machines.
  • Mistake: One access token audience for all APIs. Why it is wrong: a token stolen from one API works against all of them. Instead: audience per API and minimal scopes.
  • Mistake: Long-lived access tokens to avoid refresh complexity. Why it is wrong: JWTs can't be easily revoked, so a stolen token works for hours or days. Instead: short access tokens, rotating refresh tokens, BFF for browsers.
  • Mistake: Calling the IdP to validate every API request. Why it is wrong: the IdP becomes a latency and availability bottleneck. Instead: local validation with cached JWKS; introspection only for opaque tokens.
  • Mistake: Requesting a new client-credentials token per call. Why it is wrong: throttling by the IdP and wasted latency. Instead: cache tokens until near expiry (MSAL does this).
  • Mistake: Forcing every user to reset their password during migration. Why it is wrong: mass churn and support load. Instead: just-in-time migration using legacy hashes, then a bulk tail.

🏛 Senior insight: trade-offs

At staff level the question is really about risk ownership. Building identity transfers the hardest security problem in the company onto one team; buying transfers it to a vendor whose whole business is that problem. I'd frame the decision in an ADR with total cost over three years (licences per MAU vs engineers, infrastructure and on-call), residency, customisation needs, exit cost and risk. Most of the time that ends with managed CIAM for customers and Entra ID for staff, and the engineering effort goes into good token design, a BFF, and permission data inside our own APIs.

Where the standards are going. OAuth 2.1 (still an IETF draft at the time of writing) consolidates what the Security BCP (RFC 9700, January 2025) already recommends: PKCE for all clients, no implicit or password grants (implicit leaks tokens through URLs and browser history; password grant trains users to type passwords into apps and blocks MFA), exact redirect-URI matching, and refresh tokens that are rotated or sender-constrained (DPoP or mTLS). Choosing a provider that already does all of this, plus passkeys, is part of the evaluation.

The surrounding platform. An API gateway such as Azure API Management can validate tokens at the edge (validate-jwt policy) and apply per-client rate limits for partners, but every API should still validate tokens itself; the gateway is defence in depth, not the only check.

Option When it fits Cost When not to
Managed CIAM Most customer-facing products Per-MAU pricing, vendor limits Hard residency the vendor can't meet; extreme MAU where per-user pricing dominates
Self-hosted certified product Residency, deep customisation, very large scale Licence (Duende), infra, 24/7 ops, key management Small teams without security ops
Build from scratch Practically never Unbounded Always prefer the above

Exit strategy matters: keep your own user id mapping (sub → internal user id), use standard protocols only, and avoid provider-specific claims in business logic, so you can switch providers with a migration rather than a rewrite. I measure sign-in success rate and latency, MFA adoption, account-takeover incidents, IdP throttling events, and cost per MAU.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions authorisation code with PKCE Why: Checks OAuth 2.0 vs OpenID Connect and the recommended flows
    How to 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.

  2. When: Candidate mentions refresh tokens or a BFF Why: Checks refresh token rotation, reuse detection and BFF token storage
    How to answer

    A refresh token lets a client get new short-lived access tokens without asking the user to sign in again. Because it is long-lived, it is the most valuable token to steal.

    • Rotation: every refresh returns a new refresh token and invalidates the old one. Reuse detection: if an old one is used again, someone has a copy, so the server revokes the whole token family.
    • Lifetimes: access tokens 5–15 minutes; refresh tokens bounded by an idle timeout and an absolute session limit.
    • Storage: in a SPA, anything JavaScript can read, XSS can steal. The BFF pattern keeps tokens on the server and gives the browser only an HttpOnly, Secure, SameSite cookie.

    The trade-off: a BFF adds a server hop and session state, in exchange for tokens that never reach the browser.

  3. When: Candidate mentions social logins or mobile apps Why: Checks combining SPA, mobile and social sign-in in one product's authentication
    How to answer

    Put a single identity provider in the middle (Entra External ID, Auth0 or a self-hosted OIDC server) that federates Google and Apple; every app speaks only OIDC to it, so adding a login provider never touches your code.

    • SPA: a BFF (ASP.NET Core) runs the code flow as a confidential client, keeps tokens server-side and gives the browser an HttpOnly, SameSite cookie; it proxies API calls with an access token.
    • Mobile: authorisation code + PKCE in the system browser (RFC 8252), tokens in Keychain/Keystore, rotating refresh tokens.
    • API: accepts JWT bearer only. The BFF and mobile apps both send tokens, so the API never needs cookies. If one host must accept both, use a policy scheme that forwards by header, plus CSRF protection for cookie requests.

    The trade-off: a BFF adds a hop and state, in exchange for no tokens in the browser.

🛠 Real-world problems: how you handle them

Replacing a home-grown token service across a group of products
Situation
A [media and subscriptions] group with [nine] products and [1.5M] customer accounts in separate user tables; a [home-grown JWT service] issued tokens for some products.
Signals
A penetration test found [weak signing-key handling and no key rotation]; credential-stuffing attacks caused [hundreds] of account takeovers a month; each new product spent [a sprint] on sign-in.
Investigation
Mapped every user store, password hash format and token consumer; estimated three-year cost of hardening the custom service vs managed CIAM at [800,000] MAU; checked residency and features (social logins, MFA, branding) with two vendors.
Resolution
Immediate: rotated the signing key, shortened token lifetimes and added rate limiting on sign-in. Long term: adopted a managed customer identity provider with code + PKCE, BFFs for web products, just-in-time migration from legacy hashes, and decommissioned the custom service after [six months].
Prevention
ADR recording the decision and exit plan; synthetic sign-in monitoring from Australia; sign-in logs to Sentinel with alerts on credential stuffing; architecture rule that no service issues its own tokens.

How to tell it (STAR)

**S:** At [company] we had [nine] products with separate user stores and a home-grown token service that a pen test flagged for [key handling]. **T:** I was asked to recommend and lead an identity strategy. **A:** I mapped every user store and token consumer, compared hardening our service with managed customer identity on three-year cost, residency and risk, and wrote it up as an ADR. We chose managed CIAM, moved web products to code + PKCE behind BFFs, and migrated users just in time from their legacy password hashes. **R:** [70%] of active users moved silently in [six weeks], account takeovers fell by [about 80%], and new products integrated sign-in in [days].

More in Systems to Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me