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.
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?
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?
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?
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?
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.
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?