Advertisement

Authentication & Authorization interview questions and answers

15 Authentication & Authorization interview questions for Node.js roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How would you implement API key authentication for a Node.js service consumed by other backend services, and what are its security limitations?

API key authentication issues each consuming service a unique, typically long random string sent via a header on every request, checked server-side against a stored (ideally hashed) list of valid keys -- simple to implement and suitable for service-to-service communication, but limited because API keys typically don't expire on their own, carry no fine-grained claims like a JWT does, and if leaked (in logs, source control, or client-side code) remain valid until manually revoked, making key rotation and secure storage critical.
app.use((req, res, next) => {
  const apiKey = req.headers['x-api-key'];
  const hashedKey = crypto.createHash('sha256').update(apiKey || '').digest('hex');
  const client = apiKeyStore.findByHash(hashedKey);
  if (!client) return res.status(401).json({ error: 'Invalid API key' });
  req.client = client;
  next();
});
Real-world example
A weather-data API issues each paying customer a unique API key, storing only its SHA-256 hash in the database (never the raw key, mirroring password-storage best practice), and provides a self-service dashboard for customers to rotate their key immediately if they suspect it has leaked.
Likely follow-ups
  • Why is storing a hash of the API key rather than the raw key itself considered best practice, similar to passwords?
  • How would you add rate limiting scoped per API key rather than per IP address?
Security HTTP & HTTPS Modules
Q12 Advanced Save

What is the principle of least privilege, and how does it apply to designing an authorization system for a multi-tenant Node.js SaaS application?

The principle of least privilege states that any user, service, or process should be granted only the minimum access necessary to perform its function, and nothing more -- in a multi-tenant SaaS context, this means enforcing strict tenant isolation (a user from Tenant A should never be able to access Tenant B's data, even accidentally through a missing filter), scoping database queries and API tokens to a specific tenant ID by default, and giving even administrative roles the narrowest permissions actually required for their job rather than blanket superuser access.
// Middleware enforcing tenant scoping on every query automatically
function scopeToTenant(req, res, next) {
  req.tenantId = req.user.tenantId;
  next();
}

async function getOrders(req) {
  // Every query is forced through the authenticated user's own tenant scope
  return db.orders.find({ tenantId: req.tenantId });
}
Real-world example
A multi-tenant project-management SaaS enforces tenant scoping at the database-query layer itself (not just in route middleware), so that even a bug in a specific route handler that forgets to filter by tenant would still be caught by the underlying data-access layer, preventing any possibility of cross-tenant data leakage.
Likely follow-ups
  • What's the difference between enforcing tenant isolation at the application layer versus at the database layer (like PostgreSQL row-level security)?
  • How do you audit an existing codebase to verify least-privilege is actually being enforced consistently?
Security Databases & ORMs (MongoDB/Mongoose SQL/Sequelize)
Q13 Intermediate Save

How do you implement email verification and password-reset flows securely in a Node.js application?

Both flows rely on generating a cryptographically random, single-use token, storing only its hash in the database alongside an expiration timestamp, and emailing the user a link containing the raw token -- when the link is clicked, the submitted token is hashed and compared against the stored hash, and the action (verifying the email, or allowing a password reset) is only permitted if the hash matches and the token hasn't expired or already been used, after which the token is immediately invalidated to prevent reuse.
const crypto = require('node:crypto');

async function generateResetToken(userId) {
  const rawToken = crypto.randomBytes(32).toString('hex');
  const hashedToken = crypto.createHash('sha256').update(rawToken).digest('hex');
  await db.passwordResets.create({ userId, hashedToken, expiresAt: Date.now() + 3600000 });
  return rawToken; // only the raw token is emailed, never stored
}
Real-world example
A SaaS product's password-reset emails contain a link with a raw random token that expires after one hour and can only be used once; even if the reset-tokens database table were compromised, an attacker would only see hashed tokens that can't be reversed back into a working reset link.
Likely follow-ups
  • Why should the raw token never be stored in the database, mirroring the reasoning behind password hashing?
  • How do you prevent an attacker from enumerating valid email addresses through the password-reset request endpoint's response differences?
Security Email & Notifications
Q14 Beginner Save

What is the difference between storing an authentication token in localStorage versus an httpOnly cookie, from a security perspective?

A token in localStorage is accessible to any JavaScript running on the page, meaning a successful XSS (Cross-Site Scripting) attack can trivially steal it and exfiltrate it to an attacker. An httpOnly cookie is inaccessible to JavaScript entirely (the browser enforces this at the API level), making it immune to token theft via XSS, though cookies bring their own separate consideration around CSRF protection, which is why httpOnly cookies are generally the more secure default for browser-based session or token storage.
// Setting an httpOnly cookie server-side (JavaScript on the page can never read this)
res.cookie('accessToken', token, {
  httpOnly: true,
  secure: true, // only sent over HTTPS
  sameSite: 'strict',
});
Real-world example
A single-page application initially stored its JWT in localStorage for simplicity, but after a security review moved to httpOnly cookies specifically to eliminate the token-theft risk from a class of XSS vulnerabilities the team couldn't fully rule out across a large, frequently-updated frontend codebase.
Likely follow-ups
  • Given httpOnly cookies protect against XSS token theft, what protects against the corresponding CSRF risk they introduce?
  • Is there a legitimate reason a team might still choose localStorage despite this tradeoff?
Security HTTP & HTTPS Modules
Q15 Intermediate Save

How would you implement Attribute-Based Access Control (ABAC) in a Node.js application when RBAC roles aren't expressive enough?

ABAC evaluates access decisions based on attributes of the user, the resource, and the context (time of day, IP location, resource ownership) rather than a fixed role -- a policy engine evaluates rules like 'a user can edit a document if user.department === document.department AND user.id === document.ownerId' at request time, providing much finer-grained control than RBAC alone can express, at the cost of more complex policy definitions and evaluation logic.
function canEditDocument(user, document) {
  return (
    document.ownerId === user.id ||
    (user.department === document.department && user.role === 'manager')
  );
}

app.put('/documents/:id', requireAuth, async (req, res) => {
  const doc = await Document.findById(req.params.id);
  if (!canEditDocument(req.user, doc)) return res.status(403).json({ error: 'Forbidden' });
  updateDocument(doc, req.body);
});
Real-world example
A document-management system lets a manager edit any document belonging to their own department, and lets any user edit documents they personally own, regardless of department -- a rule that a simple role check alone couldn't express, requiring an attribute-based comparison between the user and the specific resource involved.
Likely follow-ups
  • How do dedicated policy engines like Open Policy Agent (OPA) or CASL formalize this pattern beyond hand-written if statements?
  • At what point does the combinatorial complexity of ABAC rules become a maintenance burden?
Security Design Patterns in JavaScript

Showing 11–15 of 15