Modern App Auth: Crush Your Next Tech Interview
You’ve built the killer feature, deployed it, and it’s humming along. Then the security audit hits, or a client asks about OAuth flows, and suddenly that "working" feature feels a bit… squishy. Modern app auth isn't just about logging in anymore. It’s an entire ecosystem of protocols, flows, and vulnerabilities that can make or break your product, and your candidacy for your next senior role. Forget the basic username/password—interviewers want to see you think about security like an architect, not just a coder.
Why Auth Trips Up Smart Engineers
I’ve seen brilliant engineers, folks who could optimize a database query in their sleep, completely freeze when asked about OpenID Connect vs. SAML, or how refresh tokens work with SPAs. Why? Because auth often feels like a black box. You integrate an SDK, and it "just works," until it doesn't. Many companies, especially older ones, still struggle with legacy systems, mixing and matching outdated patterns with newer ones. This creates a messy, fragmented understanding. Your interviewers know this. They're looking for someone who can untangle that mess, build secure systems from the ground up, and explain it clearly. You won't get far just reciting definitions; you need to show you understand the why behind each piece.
The Core Protocols: OAuth 2.0 and OpenID Connect
Let's start with the big two. OAuth 2.0 is an authorization framework, not an authentication protocol. That's a critical distinction. It allows a user to grant an application limited access to their resources on another server, without giving the application their credentials. Think "Login with Google" where you grant an app access to your calendar, but the app never sees your Google password. You're delegating authorization.
OpenID Connect (OIDC), on the other hand, is an authentication layer built on top of OAuth 2.0. It adds identity to the mix. After OAuth 2.0 handles the authorization, OIDC provides an ID Token—a JSON Web Token (JWT)—that contains information about the authenticated user. This token proves who the user is. If an interviewer asks you about "OAuth for login," they're probably talking about OIDC. Don't correct them pedantically, but show you understand the difference. You'd explain that OIDC uses OAuth 2.0 for its underlying authorization flows to achieve user authentication.
A common scenario: A user wants to log into your application using their Google account. Your application redirects the user to Google (the Authorization Server). Google authenticates the user, then asks them if they consent to sharing certain profile information with your app. If they agree, Google redirects them back to your app with an authorization code. Your app then exchanges this code directly with Google's Authorization Server (backend-to-backend) for an Access Token and an ID Token. The Access Token is for accessing Google’s APIs on behalf of the user, and the ID Token contains the user's identity information. You'll then typically create a session for that user in your own application based on the identity provided by the ID Token.
Authentication Flows: Picking the Right Tool
The "flow" refers to the sequence of steps an application takes to get authorization from the user and acquire tokens. This is where most interviewees get lost. There's no one-size-fits-all, and picking the wrong one has serious security implications.
-
Authorization Code Flow (with PKCE): This is the gold standard for most public clients, especially Single Page Applications (SPAs) and mobile apps. PKCE (Proof Key for Code Exchange) adds a crucial layer of security, preventing authorization code interception attacks.
- How it works: The client generates a
code_verifier(a random high-entropy string) and acode_challenge(a hashed version of the verifier). It sends the challenge in the initial authorization request. After getting the authorization code, the client sends the originalcode_verifieralong with the code to the token endpoint. The Authorization Server hashes thecode_verifierand compares it to thecode_challengeit received earlier. If they match, it issues tokens. If an attacker intercepts the code, they won't have thecode_verifier. - When to use: SPAs, native mobile apps, desktop applications. Basically, anything where the client secret can't be kept truly confidential.
- Why it's better than plain Authorization Code: Without PKCE, if an attacker intercepts the authorization code, they could exchange it for tokens. PKCE ensures that only the original client that initiated the request can exchange the code.
- How it works: The client generates a
-
Client Credentials Flow: This is for machine-to-machine communication, where an application needs to access its own resources or protected APIs without a user context.
- How it works: The client authenticates directly with the Authorization Server using its
client_idandclient_secret(kept confidential!). It then receives an Access Token. - When to use: Backend services calling other backend services, cron jobs accessing an API. No user involved.
- Key point: Never expose
client_secretin a public client (like a SPA).
- How it works: The client authenticates directly with the Authorization Server using its
-
Implicit Flow (DEPRECATED): If you suggest this, you'll fail. It returns tokens directly in the browser's URL fragment without an authorization code exchange. This is vulnerable to token leakage and replay attacks.
- When not to use: Ever, for new applications. Old applications might still have it, but you should recommend migrating away.
-
Resource Owner Password Credentials Flow (DEPRECATED): Another one to avoid for new development. The client directly collects the user's username and password and sends them to the Authorization Server.
- Why it's bad: The client gets the user's full credentials, which is a massive security risk. It bypasses the Authorization Server's UI, removing opportunities for two-factor authentication or consent screens.
- When you might see it: Legacy systems, highly trusted first-party applications where the client is the resource owner, but even then, other flows are usually better.
An interviewer might ask you to design an auth system for a new social media app with a web (SPA) and mobile client. Your answer should immediately jump to Authorization Code Flow with PKCE for both. You'd explain why it's secure for public clients.
Tokens: Access, Refresh, and ID
Tokens are the currency of modern auth. You need to understand their purpose, lifecycle, and security implications.
-
Access Token: This is the token your client uses to access protected resources on an API server. It's usually a JWT, short-lived (minutes to an hour), and opaque to the client (meaning the client doesn't need to parse its contents, although it can if it's a JWT).
- Security: If intercepted, it could be used by an attacker until it expires. That's why they're short-lived.
- Storage: In a web app, often stored in memory or in an HTTP-only, secure cookie if the backend issues it after code exchange. Storing it in
localStorageis generally discouraged due to XSS vulnerabilities.
-
Refresh Token: Used to obtain new Access Tokens without requiring the user to re-authenticate. These are long-lived (days, weeks, months).
- Security: Highly sensitive. If an attacker gets a refresh token, they can get many Access Tokens. Therefore, refresh tokens must be stored very securely.
- Storage: For web apps, they should be stored in an HTTP-only, secure cookie. The backend issues this cookie after the initial code exchange. The SPA never sees the refresh token directly. When a new access token is needed, the SPA makes a request to the backend, which uses the refresh token from the cookie (invisible to client-side JS) to get a new access token from the Authorization Server.
- Revocation: Refresh tokens must be revocable. If a user logs out, their refresh token should be invalidated.
-
ID Token: This is a JWT containing claims about the authenticated user (e.g.,
subfor subject,email,name). It's signed by the Authorization Server, allowing the client to verify its authenticity and extract user information.- Purpose: Proves user identity. Not for authorization to APIs.
- Verification: The client (your backend, typically) verifies the token's signature using the Authorization Server's public key (found at its
/.well-known/openid-configurationendpoint). It also checksiss(issuer),aud(audience—your client ID),exp(expiration), andiat(issued at). - Storage: Usually consumed immediately by the client's backend to establish a session, not stored long-term client-side.
When developing a SPA, you'll typically have your backend manage the refresh token (in an HTTP-only cookie) and issue short-lived access tokens to the SPA, which then uses those to call your own APIs. This adds a layer of security, as the SPA never directly handles the long-lived refresh token.
JWTs: Structure, Verification, and Pitfalls
JSON Web Tokens are ubiquitous in modern auth. An interviewer expects you to know their structure and how to handle them securely.
A JWT has three parts, separated by dots: Header.Payload.Signature.
- Header: Contains metadata like the token type (
typ: JWT) and the signing algorithm (alg: HS256, RS256, etc.). - Payload: A JSON object containing "claims." These are statements about an entity (typically the user) and additional data. Standard claims include
iss(issuer),sub(subject),aud(audience),exp(expiration time),iat(issued at time). You can add custom claims too (e.g.,role: "admin"). - Signature: Created by taking the Base64Url encoded header, the Base64Url encoded payload, a secret (for symmetric algorithms like HS256) or a private key (for asymmetric algorithms like RS256), and then signing it.
Crucial points for interviews:
- JWTs are NOT encrypted. They're encoded and signed. Anyone can read the payload. This means you should never put sensitive information (like passwords) into a JWT payload.
- Verification is paramount. Always verify the signature, issuer, audience, and expiration of a JWT. Skipping any of these is a security flaw. Many libraries handle this, but you should know what they're doing under the hood.
- Signature algorithm: RS256 (asymmetric) is generally preferred for ID Tokens issued by an Authorization Server, as your client only needs the public key to verify. HS256 (symmetric) is fine for your own internal microservices if they share a secret, but it means the secret is exposed to more places.
- Revocation: JWTs are stateless by design, making revocation tricky before they expire. For short-lived access tokens, this isn't usually a problem. For longer-lived tokens (or refresh tokens), you'll need a mechanism like a blacklist/denylist or session management at the Authorization Server level. If your Access Tokens are truly short-lived (e.g., 5-15 minutes), relying on expiry is often sufficient. If you need immediate revocation for a specific token, you'll need a backend check against a database or cache.
Someone might ask: "How would you implement role-based access control (RBAC) with JWTs?" You'd explain that you'd put role claims ("roles": ["admin", "editor"]) in the JWT payload. On your API server, after verifying the token's signature and standard claims, you'd inspect the roles claim to determine if the user has permission to access the requested resource. This is efficient because the API server doesn't need to hit a database for every request. Just remember, if roles change, the user needs a new token.
Single Sign-On (SSO) and Federation
SSO is the holy grail for user experience and often a requirement for enterprise applications. It allows users to log in once and access multiple related, but independent, applications without re-authenticating.
- How it works (simplified): A user authenticates with an Identity Provider (IdP). The IdP then issues an authentication assertion (e.g., a SAML assertion or an OIDC ID Token) to the Service Provider (SP, your application). The SP trusts this assertion and logs the user in.
- Key protocols:
- SAML (Security Assertion Markup Language): XML-based, older, but still very common in enterprise environments (e.g., corporate intranets, B2B SaaS). It's verbose and complex but widely supported.
- OpenID Connect: JSON/JWT-based, simpler, more modern, and better suited for web and mobile. It's quickly becoming the preferred choice for new implementations.
An interviewer might present a scenario: "Your company is building a B2B SaaS product. Enterprise clients want to integrate it with their existing Active Directory and other internal systems for SSO. What protocols would you support?" Your answer should include SAML for broad enterprise compatibility and OIDC for modern integrations, explaining the trade-offs. You'd mention that SAML is often required when integrating with older IdPs like ADFS, while OIDC works better with newer cloud identity providers like Okta, Auth0, or Azure AD. You'd also mention supporting SCIM (System for Cross-domain Identity Management) for user provisioning and de-provisioning, as SSO often goes hand-in-hand with managing user lifecycles.
Federation is the concept underlying SSO. It's the establishment of trust relationships between different identity systems, allowing users to authenticate with one system and gain access to resources in another. OIDC and SAML are the mechanisms for achieving this.
Session Management: Cookies vs. Tokens
After a user authenticates, you need to maintain their "logged-in" state. This is session management.
-
Traditional Cookie-based Sessions:
- How it works: After successful login, the server creates a unique session ID, stores it in a database/cache (along with user data), and sends it to the client in an
HttpOnly,Secure,SameSite=Lax(orStrict) cookie. For subsequent requests, the browser sends this cookie, and the server looks up the session ID to identify the user. - Pros: Simple for server-rendered apps, easy to revoke sessions immediately.
- Cons: Requires server-side state (scalability challenge for distributed systems), vulnerable to CSRF if
SameSiteisn't properly configured or ifSameSite=Noneis used without properRefererchecks. - When to use: Server-rendered applications, applications where immediate session revocation is a critical requirement for all sessions.
- How it works: After successful login, the server creates a unique session ID, stores it in a database/cache (along with user data), and sends it to the client in an
-
Token-based Sessions (using JWTs):
- How it works: After successful login, the server issues an Access Token (often a JWT) to the client. The client stores this token (e.g., in memory, or if in a cookie, not
HttpOnlyso JS can access it to attach toAuthorizationheader). For subsequent requests, the client attaches the JWT to theAuthorization: Bearer <token>header. The API server validates the JWT's signature and claims. - Pros: Stateless (server doesn't need to store session data, great for scaling microservices), can be used across different domains/APIs easily.
- Cons: Revocation is harder (rely on expiry or a blacklist), JWTs are publicly readable (though signed), storage client-side can be tricky.
- When to use: SPAs, mobile apps, microservices architectures. Often combined with refresh tokens (stored in HTTP-only cookies) for better security and UX.
- How it works: After successful login, the server issues an Access Token (often a JWT) to the client. The client stores this token (e.g., in memory, or if in a cookie, not
The Hybrid Approach (SPA/Mobile with Backend for Frontend): This is often the recommended secure pattern.
- User authenticates with IdP (e.g., Auth0, Google) via Authorization Code Flow + PKCE.
- The SPA receives an authorization code.
- The SPA sends this code to its own backend (often a "Backend for Frontend" or BFF).
- The BFF exchanges the code with the IdP for an Access Token, ID Token, and Refresh Token.
- The BFF stores the Refresh Token in a secure,
HttpOnly,Secure,SameSite=Laxcookie. It then issues its own short-lived Access Token (or a session cookie) to the SPA. - The SPA uses this short-lived token/cookie for subsequent API calls to the BFF.
- When the short-lived token/cookie expires, the SPA requests a new one from the BFF. The BFF uses the refresh token (from the secure cookie) to get new tokens from the IdP and issues a new short-lived token to the SPA. This approach keeps the long-lived refresh token out of client-side JavaScript, mitigating XSS risks, and allows the backend to handle token refreshing and potential revocation.
An interviewer might ask: "You're building an API for both a web SPA and a native mobile app. How do you handle session management and token storage securely?" You'd describe the BFF pattern for the SPA, explaining the secure cookie for the refresh token and how the BFF acts as a proxy. For the mobile app, you'd discuss storing tokens securely in the device's keychain/secure storage, emphasizing that refresh tokens should still be treated with extreme care and potentially tied to device-specific identifiers.
Security Concerns and Best Practices
Knowing the "how" isn't enough; you must know the "what if."
- Cross-Site Scripting (XSS): If an attacker can inject malicious JavaScript into your site, they can steal client-side stored tokens (e.g., from
localStorage). This is a major reason whyHttpOnlycookies for refresh tokens are preferred. - Cross-Site Request Forgery (CSRF): An attacker tricks a user's browser into making an unwanted request to a web application where the user is authenticated. This is why
SameSite=Lax(orStrict) cookies are important. ForSameSite=None(required for cross-domain requests, often used in embedded widgets), you must implement CSRF tokens (anti-forgery tokens) or ensure your endpoints only accept non-GETrequests withContent-Type: application/json. - Token Replay Attacks: An attacker intercepts a token and reuses it. Short token lifespans and unique nonces (for OIDC ID Tokens) help mitigate this.
- Open Redirects: If your application allows arbitrary redirects after authentication, an attacker could redirect users to a malicious site. Always validate redirect URIs against a pre-registered whitelist.
- Rate Limiting: Protect your
/login,/register, and/forgot-passwordendpoints from brute-force attacks by implementing rate limiting. - Input Validation: Always validate all inputs, especially those related to authentication.
- HTTPS Everywhere: All communication related to authentication and authorization must happen over HTTPS. No exceptions.
client_secretprotection: Never expose client secrets in public clients (SPAs, mobile apps). They should only be used by confidential clients (your backend servers) that can guarantee their secrecy.- Key Rotation: Regularly rotate signing keys for your JWTs. This limits the damage if a key is compromised.
- MFA (Multi-Factor Authentication): While not typically something you implement directly if using an IdP, understanding its importance and how an IdP supports it is crucial.
During an interview, don't just list these. Explain how they apply to a given scenario. For instance, if asked about storing access tokens in localStorage for a SPA, you'd immediately bring up XSS risks and suggest the Backend-for-Frontend pattern with HttpOnly cookies for managing refresh tokens. You'd also mention that if the access token itself must be accessed by client-side JS (e.g., for calling external APIs directly), then localStorage is sometimes a pragmatic, albeit less secure, compromise, and then stress the absolute criticality of robust XSS protection (CSP, sanitizing all user input, up-to-date libraries) if you go down that path. This shows nuance.
Identity Providers (IdPs) vs. Building Your Own
This is a classic "build vs. buy" decision, and almost always, the answer for auth is "buy."
-
IdP (e.g., Auth0, Okta, AWS Cognito, Azure AD B2C, Firebase Auth):
- Pros: Security expertise, compliance (GDPR, HIPAA, etc.), scalability, maintained and updated, MFA built-in, social logins, SSO, user management, fraud detection. You don't have to worry about the intricacies of crypto, protocol implementations, or vulnerability patching.
- Cons: Cost, vendor lock-in, some customization limitations.
- When to use: Almost always, unless your company is an identity company, or has extremely niche, complex, and justifiable security requirements that no off-the-shelf solution can meet.
-
Building Your Own Auth System:
- Pros: Full control, extreme customization (potentially).
- Cons: Immense security risks, huge development and maintenance overhead, hard to keep up with evolving threats, lack of compliance expertise, takes focus away from your core product. This is a massive undertaking.
- When to use: Probably never. Seriously, don't. Your job is to build your business's core competency, not to become an identity and access management expert from scratch.
When an interviewer asks, "Would you ever build your own authentication system?" your immediate, strong answer should be "No, almost never." Then, you'd justify why using an IdP is superior: security, compliance, reduced operational burden, focus on core product. You might offer a tiny caveat like, "Unless we were building an IdP ourselves, or had extremely unique, government-level security requirements and a dedicated team of security experts, it's a huge risk and waste of resources." This shows you understand the trade-offs and the gravity of the decision.
Future Trends: Passkeys and Decentralized Identity
Stay current. Interviewers appreciate candidates who think ahead.
-
Passkeys (FIDO Alliance): These are cryptographic credentials generated by your device, replacing passwords. They offer phishing resistance, better security, and a much smoother user experience. Google, Apple, and Microsoft are all pushing this standard.
- How they work: When you "register" a passkey, your device generates a unique public/private key pair. The public key is sent to the service, while the private key stays on your device, protected by biometrics (fingerprint, face ID) or a PIN. For login, your device uses the private key to sign a challenge from the service. No password ever leaves your device.
- Why they're important: Solves password fatigue, phishing, and weak passwords.
- Interview talk: You'd mention how they integrate with existing IdPs, improve security significantly, and simplify UX.
-
Decentralized Identity (e.g., DIDs, Verifiable Credentials): This is more nascent but gaining traction. Users own and control their own identity data, issuing verifiable claims (like "I am over 21") that can be cryptographically proven without relying on a central authority.
- Why it's important: Enhances privacy, gives users more control, reduces data breaches by minimizing centralized honeypots of personal data.
- Interview talk: Acknowledge it's still evolving, but highlight its potential for privacy and user control, and how it challenges traditional IdP models.
Showing awareness of these emerging technologies demonstrates your commitment to staying updated and thinking about long-term security and user experience.
Final Thoughts on Interview Prep
Don't just memorize definitions. Understand the flows, the why behind each protocol choice, and the security implications of every decision. Draw diagrams on a whiteboard. Walk through a specific scenario (e.g., "Login with Google" for a SPA). Be ready to explain trade-offs and justify your choices. Auth is complex, and interviewers want to see that you respect that complexity and can design systems that are both functional and secure.
This isn't about being a security expert in every domain, but about demonstrating a solid foundation in modern authentication and authorization principles. Show them you can build robust, secure systems that users will trust.
Ready to Ace Your Next Interview?
Practice with AI-powered mock interviews tailored to your target role and company. Start Practicing for Free | Explore Interview Prep
