0 / 10 answered
Home
🔐
Auth Fundamentals
Core concepts every full-stack engineer must know before touching a single line of auth code — mental models, terminology, and the trust boundaries that underpin every authentication system.
AuthN vs AuthZ Stateful vs Stateless Cookies Mental Models JWT Claims Credential Stuffing
10
Questions
0
Opened
🔐
Auth Fundamentals
1
What is the difference between Authentication (AuthN) and Authorization (AuthZ)?
Easy Core Concept

Authentication (AuthN) answers "Who are you?" — it verifies the identity of a user or system. Authorization (AuthZ) answers "What are you allowed to do?" — it determines what an authenticated identity can access or perform.

Authentication always happens first. You cannot meaningfully authorize someone whose identity you don't know.

AspectAuthentication (AuthN)Authorization (AuthZ)
QuestionWho are you?What can you do?
MechanismPassword, JWT, biometric, OAuth tokenRoles, permissions, ACLs, policies
OutputVerified identity (user object / claims)Allow or deny the requested action
HTTP status on failure401 Unauthorized403 Forbidden
ExampleLogging in with email + passwordOnly admins can delete posts
Mental Model

Authentication is the ID check at a venue entrance — proving who you are. Authorization is the wristband you get after — determining which areas you can enter. You can't get the wristband without showing ID first.

Interview Tip

A common mistake is returning 401 when a user is authenticated but lacks permission — that should be 403. Interviewers notice this distinction.

2
What are the main authentication types used in MERN applications and when would you choose each?
Medium Architecture Decision Making
TypeMechanismBest For
Session + CookieOpaque session ID in httpOnly cookie; server holds state in Redis/DBTraditional web apps, server-rendered pages, when instant revocation is needed
JWTSelf-contained signed token; server is statelessSPAs, mobile apps, microservices, third-party API consumers
OAuth 2.0 / OIDCDelegated auth via third-party IdP (Google, GitHub)Social login, enterprise SSO, acting on behalf of a user in another system
API KeysOpaque secret sent in header per requestServer-to-server, developer APIs, integrations without user context
PasswordlessMagic links, TOTP, WebAuthn/passkeysHigh-security apps, great UX without password friction

In practice, most MERN apps combine these: JWT for the primary user auth, OAuth for social login, and API keys for server-to-server webhooks.

3
What is the difference between stateful and stateless authentication? What are the trade-offs?
Medium Architecture Scalability
Stateful (Sessions)

Server stores session data. Each request carries an opaque ID. Server looks it up in Redis/DB to retrieve the session. State lives server-side.

Stateless (JWT)

Token is self-contained — it carries all the data needed. Server just verifies the signature on every request. No DB lookup required for auth.

Trade-offStatefulStateless
RevocationInstant — delete the session recordHard — token valid until expiry unless you add a blocklist
ScalabilityNeeds shared session store (Redis) across instancesAny server can verify without coordination
Request costDB/Redis lookup per requestCPU cost of signature verification only
Token sizeSmall cookie (~30 bytes)Larger JWT (~300–500 bytes)
Suitable forWeb apps needing force-logoutAPIs, microservices, mobile
Key Insight
The choice isn't binary. You can have a stateless JWT system with a Redis-backed revocation list — giving you scalability while adding revocation capability, at the cost of one Redis lookup.
4
How do HTTP cookies work in the context of authentication? What role do they play?
Easy Cookies HTTP

Cookies are small pieces of data the server sends to the browser via the Set-Cookie response header. The browser automatically sends them back on every subsequent request to the same domain via the Cookie request header — this automatic inclusion is what makes them useful for auth.

1
User logs in → server sets Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Lax
2
Browser stores the cookie and attaches it to every subsequent request to that origin
3
Server reads req.cookies.sessionId, looks up the session, identifies the user
4
On logout, server sets an expired cookie to remove it from the browser

The key security flags — HttpOnly, Secure, and SameSite — are what separate a safe cookie from a vulnerable one. These are covered in depth in the Security segment.

5
What is the difference between a session and a token? How do they each prove identity?
Easy Sessions JWT
Session ID (Opaque Reference)

A random, meaningless string (e.g. 4f3a9b...). Acts as a key into a server-side lookup table. The session store holds the actual user data. Without the store, the ID means nothing.

Token (Self-Describing Value)

A structured, signed data structure (JWT). Contains the user data directly in its payload. Any party with the public key / secret can verify authenticity without contacting the issuer.

Mental Model

A session ID is like a coat-check ticket — it's just a number that points to your coat stored elsewhere. A JWT is like a notarized letter — it carries all the information about you and the notary's signature proves it hasn't been tampered with.

6
What is the trust model in a typical MERN authentication system? Who trusts whom?
Medium Architecture OAuth

Every auth system has a trust chain. Understanding it prevents entire categories of bugs.

ScenarioTrust Chain
Custom JWT authUser trusts your server → Server signs token with a secret → Server trusts its own tokens (verified by secret)
OAuth / Social LoginUser trusts Google → Google issues token to your app → Your server trusts Google's signature → Your server issues its own session/JWT
MicroservicesService A trusts your Auth Service → Auth Service issues JWT → Service B verifies with Auth Service's public key → Service B trusts the claim
Security Implication
The trust chain is only as strong as its weakest link. If your JWT secret is leaked, every token ever signed is compromised. If you blindly trust Google's email claim without verifying it's confirmed, an attacker can spoof identity via an unverified Google account.
7
What is the difference between symmetric and asymmetric signing for JWTs? When would you use each?
Medium JWT Cryptography
HS256 — Symmetric (HMAC)

One shared secret used to both sign and verify. Fast. Simple. But: every verifier needs the secret. If a downstream service is compromised, the secret is exposed and attackers can forge tokens.

RS256 / ES256 — Asymmetric

Private key signs (only the auth server has it). Public key verifies (shared freely). Downstream services never see the private key. Compromise of a verifier doesn't compromise token signing.

javascript
// HS256 — same secret for sign & verify
const token = jwt.sign({ sub: userId }, process.env.JWT_SECRET, { algorithm: 'HS256' });
jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });

// RS256 — private key signs, public key verifies
const token = jwt.sign({ sub: userId }, privateKey, { algorithm: 'RS256' });
jwt.verify(token, publicKey, { algorithms: ['RS256'] }); // any service can do this

Rule of thumb: Use HS256 when a single service both signs and verifies. Use RS256/ES256 when multiple services need to verify tokens — microservices, third-party resource servers, or when you publish a JWKS endpoint.

8
What are JWT claims? Explain the standard registered claims and what each is used for.
Easy JWT Standards

JWT claims are key-value pairs in the payload that assert facts about the token and its subject. There are three claim types:

iss
Issuer — who created the token (e.g. "https://api.yourapp.com"). Validate this to prevent accepting tokens from other systems.
sub
Subject — who the token is about. Usually the user ID (MongoDB ObjectId). This is your primary user identifier.
aud
Audience — who the token is intended for. Prevents a token issued for one service from being used on another.
exp
Expiration time (Unix timestamp). jwt.verify() automatically rejects expired tokens. Always set this.
iat
Issued at (Unix timestamp). Useful for calculating token age or invalidating tokens issued before a password change.
nbf
Not Before — token is invalid before this time. Rare, but useful for delayed-activation scenarios.
jti
JWT ID — unique identifier for this specific token. Used for one-time tokens and revocation via a blocklist.
Best Practice
Always validate iss, aud, and exp in production — not just the signature. The jsonwebtoken library accepts options: jwt.verify(token, secret, { issuer, audience, algorithms })
9
What is credential stuffing and how do you defend against it in a MERN application?
Medium Security Attack Vectors

Credential stuffing is an attack where bad actors take username/password pairs from data breaches (billions are available for free) and automatically try them against your login endpoint. Because people reuse passwords, a significant percentage succeed.

It differs from brute force — the attacker isn't guessing; they're using credentials that actually work somewhere.

  • bcrypt/argon2 — slow hashing makes offline attacks expensive (but doesn't stop online stuffing)
  • Rate limiting — limit login attempts per IP per minute with express-rate-limit + Redis
  • Bot detection / CAPTCHA — Google reCAPTCHA v3 (invisible) after a threshold of failures
  • Breach detection — check submitted passwords against HaveIBeenPwned API (k-anonymity model — you never send the full hash)
  • MFA — even if credentials match, the attacker still needs the second factor
  • Anomaly detection — flag logins from new countries, devices, or IPs for step-up auth
HaveIBeenPwned API
Send the first 5 characters of the SHA-1 hash of the password. The API returns all hashes with that prefix. You check locally if the full hash appears in the list — the server never sees your full hash.
10
How do you manage authentication state in a React SPA? What are the pitfalls?
Medium React State Management

Auth state in React is typically managed in one of three ways, each with trade-offs:

ApproachHowTrade-off
React ContextAuthContext with user object, login/logout methods. Wrap app in AuthProvider.Simple. Works for most apps. Re-renders entire tree on change.
Redux / ZustandAuth slice in global store. Persisted to sessionStorage if needed.Good for complex apps already using global state. Overhead for small apps.
React Query / SWRQuery the /me endpoint to always get fresh server state. Cache + refetch.Source of truth is the server. Handles token expiry naturally.
Critical Pitfall — Never Trust Client-Side Auth Alone
React auth state is purely for UI decisions (show/hide a button, redirect to login). Every sensitive operation must be re-authorized on the server. An attacker can manipulate client-side state in DevTools and bypass any client-only check.
jsx
// Simple AuthContext pattern
const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(async () => {
    try {
      const res = await fetch('/api/auth/me', { credentials: 'include' });
      if (res.ok) setUser(await res.json());
    } finally { setLoading(false); }
  }, []);

  return (
    <AuthContext.Provider value={{ user, loading, setUser }}>
      {!loading && children}
    </AuthContext.Provider>
  );
}