Authentication and Security Interview Questions for Full Stack with Node.js
25 Authentication and Security questions with answers for full stack with node.js roles — 6 easy, 15 medium, 4 hard.
About Authentication and Security
Implement secure login with bcrypt or Argon2, JWT access and refresh tokens, sessions, OTP login, OAuth 2.0 and OpenID Connect. Protect APIs with RBAC, rate limiting, input validation, helmet and secret management, and defend against OWASP risks such as injection, XSS, CSRF, SSRF and broken object level authorisation.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What is the difference between authentication and authorisation?
Authentication verifies who the user is, for example by checking a password, OTP or OAuth login. Authorisation decides what that verified user is allowed to do, such as whether they can delete an order or view admin reports. In an API, authentication failures return 401 and authorisation failures return 403. Both must be enforced on the server, never only in the frontend.
A JSON Web Token is a compact, signed token used to carry claims between parties. It has three Base64URL parts separated by dots: header (algorithm and type), payload (claims like sub, role, exp) and signature. The signature proves the token was issued by the server and not modified. The payload is only encoded, not encrypted, so never put secrets in it.
Never store plain text or use fast hashes like MD5 or SHA-256 alone. Use a slow, salted password hashing algorithm such as bcrypt with a cost factor around 10 to 12, or Argon2id, which is the current recommendation. The library generates a unique salt per password. On login, compare using the library's compare function, which is timing-safe.
04
What is SQL injection and how do you prevent it in Node.js?
SQL injection happens when user input is concatenated into a query, letting attackers change it, for example ' OR 1=1 --. Prevent it with parameterised queries, such as pool.query('SELECT * FROM users WHERE email = $1', [email]) in pg, or an ORM like Prisma or Sequelize that parameterises automatically. Also validate input and give the database user minimum privileges.
05
How do you manage secrets such as database passwords and API keys in a Node.js app?
Never commit secrets to Git. Load them from environment variables, using a .env file only for local development and keeping it in .gitignore. In production, use a secrets manager such as AWS Secrets Manager, Azure Key Vault, HashiCorp Vault or Kubernetes secrets with encryption. Rotate keys regularly, scan repos with tools like gitleaks and validate required variables at startup.
06
How do you keep yourself updated about security best practices as a backend developer?
I follow the Node.js security release announcements and OWASP cheat sheets, read GitHub security advisories for packages we use and keep Dependabot alerts on. I also practise with labs like OWASP Juice Shop. In my last project I used this to propose helmet, rate limits and stricter input validation, and I shared a short security checklist that the team adopted in pull request reviews.
07
Compare session-based authentication with JWT-based authentication.
Sessions store state on the server, often in Redis, and the client holds only a session ID cookie; logout and revocation are easy. JWTs are stateless, so any service can verify them without a lookup, which suits microservices and mobile apps, but revoking a token before expiry needs a denylist or short lifetimes. Many systems combine short-lived JWT access tokens with server-stored refresh tokens.
08
How do access tokens and refresh tokens work together?
The access token is short-lived, around 5 to 15 minutes, and sent with each API request. The refresh token is long-lived, stored securely in an HttpOnly cookie, and used only at a refresh endpoint to get a new access token. Rotate refresh tokens on every use and store their hashes server-side, so a stolen or reused token can be detected and the session revoked.
localStorage is readable by any JavaScript on the page, so an XSS bug can steal tokens. HttpOnly, Secure, SameSite cookies cannot be read by JavaScript, which is safer for refresh tokens and session IDs. Cookies require CSRF protection, which SameSite=Lax or Strict plus CSRF tokens provide. A common pattern keeps the access token in memory and the refresh token in an HttpOnly cookie.
12
What is the difference between OAuth 2.0 and OpenID Connect?
OAuth 2.0 is an authorisation framework that issues access tokens for calling APIs; it does not define who the user is. OpenID Connect is an identity layer on top of OAuth 2.0 that adds an ID token, a JWT with user identity claims, and a userinfo endpoint. For social or enterprise single sign-on you use OIDC; for API access delegation you use OAuth scopes.
13
What is NoSQL injection in MongoDB and how do you prevent it?
If you pass req.body directly into a query, an attacker can send { "password": { "$ne": null } } and bypass checks. Prevent it by validating and casting input types with zod or Joi, rejecting objects where strings are expected, enabling Mongoose strictQuery and sanitizeFilter, and never building queries from raw user objects. Avoid $where and server-side JavaScript evaluation.
14
What are XSS and CSRF and how do you protect a Node.js app from them?
XSS injects malicious script into pages other users view; prevent it by escaping output, using templating or React auto-escaping, sanitising rich HTML with DOMPurify and setting a strong Content-Security-Policy. CSRF tricks a logged-in browser into sending unwanted requests; prevent it with SameSite cookies, CSRF tokens for cookie-based auth and checking Origin headers on state-changing requests.
15
How do you implement rate limiting on a login endpoint?
Define roles such as admin, manager and customer, and map them to permissions like order:read or order:refund. Put the role or permissions in the token or load them per request, and check them in middleware before handlers. For ownership rules, also check resource data, for example a customer can view only orders where order.userId equals req.user.id. Test both allowed and denied paths.
17
What is the OWASP Top 10 and which items matter most for Node.js APIs?
The OWASP Top 10 lists the most critical web application security risks. For Node APIs the most relevant are broken access control, injection, cryptographic failures, security misconfiguration, vulnerable and outdated components, authentication failures and server-side request forgery. OWASP also publishes an API Security Top 10, which highlights broken object level authorisation, where users access others' data by changing an ID.
18
A security audit finds that users can see other users' orders by changing the order ID in the URL. How do you fix it?
This is broken object level authorisation. Every query must be scoped to the authenticated user: Order.findOne({ _id: id, userId: req.user.id }), returning 404 if not found. Put this check in a shared service or middleware so no route can skip it, add tests that try other users' IDs, and consider non-guessable IDs like UUIDs as defence in depth, not as the fix.
19
How would you add OTP-based login for an Indian mobile app?
Generate a random 6-digit OTP with crypto.randomInt, store only its hash in Redis with a 5-minute TTL and an attempt counter, and send it through an SMS provider on a DLT-registered template. Verify with a timing-safe compare, limit to about 3 to 5 attempts and rate limit sends per number and IP. On success, issue access and refresh tokens and delete the OTP.
20
npm audit reports a critical vulnerability in a dependency of a dependency. What do you do?
First check whether the vulnerable code path is actually reachable in our usage and read the advisory. Try npm audit fix or updating the parent package to a version that pulls a patched sub-dependency. If none exists, use the overrides field in package.json to force a safe version and run tests. Track it in a ticket and enable Dependabot or Renovate for ongoing updates.
21
Tell me about a time you found a security issue in code and how you handled it.
Situation: during code review I noticed an admin export route that only hid the button in the frontend. Task: make sure no regular user could call it. Action: I reproduced it with a normal user token, reported it privately to my lead, added role middleware and tests, and checked similar routes. Result: we fixed four endpoints before release and added an authorisation checklist to pull requests.
22
Explain OAuth 2.0 and the Authorization Code flow with PKCE.
OAuth 2.0 lets an app access resources on a user's behalf without seeing their password, for example social login with an existing account. In Authorization Code with PKCE, the app creates a code verifier and sends its hash to the authorisation server. The user logs in and consents, the app receives a code and exchanges it plus the verifier for tokens. PKCE stops intercepted codes being reused.
23
Your JWT secret has leaked. What steps do you take?
Treat it as an incident. Generate a new secret and deploy it immediately, which invalidates all existing tokens and forces re-login. Revoke refresh tokens in the database, check logs for suspicious tokens or admin actions, and find how it leaked, for example a committed .env or logs. Move to a secrets manager, consider asymmetric RS256 keys with key IDs to rotate safely, and document the incident.
24
How would you design authentication for a system of ten microservices?
Centralise login in an identity service or provider such as Keycloak, Auth0 or Cognito that issues short-lived JWTs signed with RS256. The API gateway validates tokens, and each service verifies the signature using the public keys from a JWKS endpoint, so no shared secret is needed. Use service-to-service tokens or mTLS for internal calls and keep authorisation checks inside each service.
25
How do you prevent server-side request forgery when your API fetches a user-supplied URL?
An attacker could make your server call internal addresses such as 169.254.169.254 for cloud metadata or localhost admin ports. Allow only http and https, resolve the hostname and block private, loopback and link-local IP ranges, use an allowlist of domains where possible, disable redirects or revalidate them, set short timeouts and size limits, and run fetchers in an isolated network.
Frequently asked questions
How important is Authentication and Security in Full Stack with Node.js interviews?
Implement secure login with bcrypt or Argon2, JWT access and refresh tokens, sessions, OTP login, OAuth 2.0 and OpenID Connect. Protect APIs with RBAC, rate limiting, input validation, helmet and secret management, and defend against OWASP risks such as injection, XSS, CSRF, SSRF and broken object level authorisation.
How should I use the Authentication and Security sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.