Auth & Security
Fundamentals
Section titled “Fundamentals”Q (basic): Authentication vs authorization?
Say this: Authentication checks identity: login with a password, OAuth, or a token. Authorization checks permissions: can this authenticated user delete this post? Authentication always comes first. Failing authentication gives 401. Failing authorization gives 403.
Q (mid): Sessions vs JWT: tradeoffs?
Say this (30 sec):
- Session-based: the server stores session data (in a DB or Redis) and the client holds an opaque session ID cookie. Revocation is easy (delete the row) and the cookie is small. The cost is a store lookup on every request.
- JWT (stateless): the token itself carries the claims, and the server just verifies the signature. There’s no lookup, so it works well across services and edge runtimes. But you can’t easily revoke it before it expires, the token is bigger, and data in it can go stale (e.g. the role changed).
My usual take: sessions for a normal web app. JWTs for service-to-service calls or when stateless verification matters, always with short expiry plus refresh tokens.
Common wrong answer: “JWT is more secure than sessions.” Neither is more secure by nature. They’re different tradeoffs.
Q (mid): How do you revoke a JWT?
Say this: You can’t truly invalidate a signed token. Your options: (1) short-lived access tokens (5–15 min), so damage is time-limited; (2) revoke the refresh token in the DB so no new access tokens can be issued; (3) keep a denylist of token IDs (jti) in Redis until they expire; (4) store a token version per user and bump it on logout or password change. Options 3 and 4 bring back a lookup, so you’re partly back to sessions.
Q (mid): Explain access token + refresh token flow.
Say this (30 sec): On login, the server issues a short-lived access token (around 15 min) that’s sent with each API call, and a long-lived refresh token (days or weeks) stored in an httpOnly cookie and tracked in the DB. When the access token expires and the API returns 401, the client calls /refresh and gets a new access token. Refresh token rotation: each refresh gives a new refresh token and invalidates the old one. If an old one is reused, that suggests theft, so revoke the whole token family.
Q (mid): Where should you store tokens on the client?
Say this (30 sec): Prefer an httpOnly, Secure, SameSite=Lax/Strict cookie. JavaScript can’t read it, so an XSS bug can’t steal the token. localStorage is readable by any script on the page, so one XSS leaks the token. Cookies bring CSRF risk, which is handled by SameSite plus CSRF tokens for sensitive actions. Another option for SPAs is keeping the access token in memory and the refresh token in an httpOnly cookie.
Common wrong answer: “httpOnly cookies make you fully safe from XSS.” XSS can still send requests as the user while they’re on the page. It just can’t steal the token.
Q (basic): What's the structure of a JWT?
Say this (30 sec): It has three base64url-encoded parts separated by dots: header.payload.signature.
- Header: algorithm and type, e.g.
{"alg":"HS256","typ":"JWT"}. - Payload: claims like
sub(user ID),exp(expiry),iat(issued at),iss,aud, plus custom ones likerole. - Signature:
HMAC-SHA256(base64(header) + "." + base64(payload), secret)for HS256, or an RSA/ECDSA private-key signature for RS256/ES256.
The signature proves the token wasn’t tampered with, but the payload is readable by anyone.
Follow-ups they ask: “HS256 vs RS256?” HS256 uses one shared secret for signing and verifying. RS256 signs with a private key and verifies with a public key, which is better when many services verify but only one issues tokens (published through JWKS).
Common wrong answer: “JWT is encrypted.” Signed only. JWE is the encrypted variant.
Q (tricky): Common JWT security mistakes?
Say this: Accepting alg: none, or algorithm confusion (always pin the expected algorithm when verifying). Using a weak HS256 secret that can be brute-forced. Not checking exp, iss, or aud. Putting sensitive data in the payload. Using very long-lived access tokens. Storing tokens in localStorage.
Example:
jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'], issuer: 'my-api' });Q (basic): How should passwords be stored?
Say this (30 sec): Hash them with a slow, salted password-hashing algorithm: argon2id (current OWASP first choice), bcrypt (cost 10–12+), or scrypt. A salt is random data unique to each password, stored with the hash. Because of the salt, identical passwords produce different hashes, and rainbow tables don’t work. These algorithms are deliberately slow, so brute-forcing leaked hashes is expensive.
Example:
const hash = await bcrypt.hash(password, 12); // salt is generated and embedded in the hashconst ok = await bcrypt.compare(input, hash);Common wrong answer: “I encrypt passwords” (encryption can be reversed) or “I use SHA-256” (too fast, GPUs can try billions per second). Also, bcrypt only uses the first 72 bytes of input.
Q (basic): Hashing vs encryption vs encoding?
Say this: Encoding (base64) is a reversible format change with no key, so it gives no security. Encryption (AES, RSA) is reversible with a key, for data you need to read back. Hashing (SHA-256, bcrypt) is one-way, for passwords and integrity checks.
OAuth, OIDC, Better-auth
Section titled “OAuth, OIDC, Better-auth”Q (mid): Explain OAuth 2.0 and OIDC simply.
Say this (30 sec): OAuth 2.0 is for authorization. It lets an app access a user’s resources at another service without getting their password. OIDC (OpenID Connect) is a layer on top that adds authentication: an ID token (a JWT) that says who the user is. “Login with Google” is OIDC.
Authorization Code flow with PKCE (the one to know):
- The app redirects the user to Google with
client_id,redirect_uri,scope,state, and a PKCEcode_challenge. - The user logs in and consents at Google.
- Google redirects back to the app with a short-lived authorization code.
- The backend exchanges the code (plus
code_verifierand the client secret) for access, ID, and refresh tokens. - The app reads the ID token to identify the user and creates its own session.
Follow-ups they ask: “What’s state for?” It prevents CSRF on the callback. “What’s PKCE?” It stops an intercepted code from being used by an attacker. It’s now recommended for all clients. The implicit flow is deprecated.
Q (mid): What is Better-auth and why did you use it?
Say this (30 sec): Better-auth is a framework-agnostic TypeScript auth library that you host yourself. It handles email/password, social OAuth providers, and sessions stored in your own database: a session row plus a signed session cookie, with optional cookie caching to skip DB lookups. It plugs into the ORM through adapters like the Drizzle adapter, and its CLI generates the user, session, account, and verification tables. Extra features come as plugins: 2FA, passkeys, magic links, an admin/roles plugin, and an organization plugin for real multi-tenancy. I picked it over a hosted service like Auth0 or Clerk because the data stays in my Postgres, there’s no per-user pricing, it’s type-safe, and it runs on Workers with Hono.
Example:
export const auth = betterAuth({ database: drizzleAdapter(db, { provider: 'pg' }), emailAndPassword: { enabled: true }, socialProviders: { google: { clientId: env.GOOGLE_ID, clientSecret: env.GOOGLE_SECRET } },});
// Honoapp.on(['GET', 'POST'], '/api/auth/*', (c) => auth.handler(c.req.raw));const session = await auth.api.getSession({ headers: c.req.raw.headers });Follow-ups they ask: “Is it JWT-based?” By default it’s session-based (DB-backed). There’s a JWT plugin if you need tokens for other services.
RBAC and multi-tenancy
Section titled “RBAC and multi-tenancy”Q (mid): How did you implement RBAC in Express? Show the code.
Say this (30 sec): Two middlewares. authenticate verifies the token or session and attaches req.user. authorize(...roles) checks the user’s role and returns 403 if it doesn’t match. Roles map to permissions. For ownership rules like “only the author can edit”, I also check resource.userId === req.user.id in the handler or service, because a role alone isn’t enough.
Example:
const authenticate = (req, res, next) => { const token = req.cookies.access_token || req.headers.authorization?.split(' ')[1]; if (!token) return res.status(401).json({ error: 'Unauthenticated' }); try { req.user = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }); next(); } catch { return res.status(401).json({ error: 'Invalid or expired token' }); }};
const authorize = (...allowed) => (req, res, next) => allowed.includes(req.user.role) ? next() : res.status(403).json({ error: 'Forbidden' });
router.delete('/posts/:id', authenticate, authorize('admin', 'moderator'), deletePost);Follow-ups they ask: “The role is in the JWT. What if an admin demotes someone?” The old role lasts until the token expires. Fix it with short expiry, or by checking the role from the DB or session for sensitive actions.
Q (mid): RBAC vs ABAC?
Say this: RBAC grants permissions by role (admin, editor, user). It’s simple and easy to audit. ABAC decides using attributes of the user, resource, and context (e.g. “owner can edit during business hours”). Most real apps use RBAC plus ownership checks.
Q (tricky): What is multi-tenancy? (Your resume says "multi-tenant auth".)
Say this (30 sec): Multi-tenancy means one application instance serves multiple tenants. A tenant is usually an organization or customer account, like a company on Slack or Notion. Each tenant’s data is isolated from the others, and users belong to a tenant with roles inside it. There are three isolation strategies:
- Shared DB, shared tables, a
tenant_idcolumn on every row, enforced in every query or with Postgres RLS. Cheapest and most common. - Schema per tenant.
- Database per tenant. Strongest isolation, highest cost.
Be honest about your project: a social app where every user owns their own posts is per-user authorization, not multi-tenancy. If asked, correct it yourself: “I’d describe it more precisely as role-based auth with per-user data ownership. True multi-tenancy would mean organizations as tenants with tenant_id scoping, which I understand and could add, e.g. with Better-auth’s organization plugin.” Correcting yourself earns trust. Defending a wrong term loses it.
Common wrong answer: “Multi-tenant means many users can log in.”
OWASP and web security
Section titled “OWASP and web security”Q (basic): What is XSS and how do you prevent it?
Say this (30 sec): Cross-Site Scripting is when an attacker gets their JavaScript to run in another user’s browser. It can be stored (saved in the DB, like a malicious comment), reflected (comes from the URL), or DOM-based. Prevention: escape output. React escapes by default, so avoid dangerouslySetInnerHTML, or sanitize with DOMPurify if you must use it. Use a Content-Security-Policy header, httpOnly cookies so tokens can’t be stolen, and validate input.
Q (mid): What is CSRF and how do you prevent it?
Say this (30 sec): Cross-Site Request Forgery happens when a malicious site makes the user’s browser send a request to your site, and the browser attaches your cookies automatically. Example: a hidden form that posts to /transfer. Prevention: SameSite=Lax or Strict cookies (Lax is the default in modern Chrome), CSRF tokens (synchronizer or double-submit), checking the Origin/Referer header, and never using GET for state changes.
Follow-ups they ask: “Do JWTs in an Authorization header need CSRF protection?” No. The browser doesn’t attach headers automatically. CSRF is a cookie problem. But storing that JWT in localStorage exposes it to XSS.
Q (basic): What is SQL injection and how do you prevent it?
Say this: It happens when user input is concatenated into SQL, so it can change the query: ' OR '1'='1. Prevention: parameterized queries / prepared statements, which ORMs like Drizzle use by default, plus input validation and a DB user with least privilege.
Example:
// Vulnerabledb.query(`SELECT * FROM users WHERE email = '${email}'`);// Safedb.query('SELECT * FROM users WHERE email = $1', [email]);Common wrong answer: “ORMs make injection impossible.” Raw query escape hatches like sql.raw() or string interpolation are still vulnerable.
Q (mid): What is CORS? Does it protect your API?
Say this (30 sec): CORS is a browser mechanism that relaxes the Same-Origin Policy. The server sends Access-Control-Allow-Origin and related headers to say which other origins may read its responses. For non-simple requests (custom headers, JSON content type, PUT or DELETE), the browser first sends an OPTIONS preflight. CORS does not protect your API from curl, Postman, or other servers. It only controls what browsers let JS read.
Common wrong answer: Using Access-Control-Allow-Origin: * together with credentials. Browsers reject that combination. With cookies, you must list the specific origin and set Access-Control-Allow-Credentials: true.
Q (basic): Why HTTPS? What does it protect?
Say this: TLS gives encryption (nobody can eavesdrop on passwords or tokens), integrity (nobody can modify the data in transit), and authentication (the certificate proves you’re talking to the real server). Add HSTS so browsers always use HTTPS, and use Secure cookies.
Q (mid): How do you manage secrets?
Say this: Never put them in code or Git. Use env vars locally (.env in .gitignore) and a secret manager in production (Wrangler secrets, Azure Key Vault, AWS Secrets Manager, GitHub Actions secrets for CI). Follow least privilege, rotate keys, and scan repos with gitleaks or GitHub secret scanning. If a secret was ever committed, rotate it. Deleting it from Git history isn’t enough.
Q (mid): OWASP Top 10: name a few.
Say this: Broken Access Control (number 1: e.g. IDOR, changing /orders/123 to /orders/124), Cryptographic Failures, Injection (SQL and XSS), Insecure Design, Security Misconfiguration, Vulnerable and Outdated Components, Identification and Authentication Failures, Software and Data Integrity Failures, Logging and Monitoring Failures, and SSRF.
Follow-ups they ask: “What’s IDOR?” Insecure Direct Object Reference. The API trusts an ID from the client without checking ownership. The fix is to always scope queries: WHERE id = $1 AND user_id = $currentUser.
Q (basic): How would you protect a login endpoint?
Say this: Use rate limiting per IP and per account, lockout or exponential backoff after repeated failures, a CAPTCHA (e.g. Turnstile) after suspicious attempts, generic error messages (“invalid email or password”, which avoids user enumeration), slow password hashing, HTTPS only, 2FA, and logging of failed attempts.