Intermediate LevelExpress JS
What is an Open Redirect vulnerability in res.redirect() and how do you validate target URLs securely?
❓ Interview Prompt: Explain Open Redirect security vulnerabilities, phishing risks, and validating target redirect URLs against domain whitelists.
An Open Redirect occurs when an application accepts an untrusted user-supplied URL in a query parameter ('res.redirect(req.query.next)') without validation. Attackers construct malicious links ('example.com/login?next=https://phishing-site.com') that trick users into logging into fake sites!
Defense:
Validate target redirect URLs against a whitelist of trusted relative paths or domain names before executing 'res.redirect()'.
Code Implementation Example
javascript
import express from 'express';
const app = express();
function getSafeRedirectUrl(target) {
// Allow ONLY internal relative paths starting with / (e.g. /dashboard)
if (target && target.startsWith('/') && !target.startsWith('//')) {
return target;
}
return '/dashboard'; // Fallback safe default
}
app.get('/login-callback', (req, res) => {
const safeUrl = getSafeRedirectUrl(req.query.next);
res.redirect(safeUrl);
});💡Preventing Open Redirect vulnerabilities by enforcing relative path validation.
🎯 Interview Key Takeaway
Validate user-supplied redirect targets against relative path rules to prevent Open Redirect phishing attacks.
#Open Redirect#Security#res.redirect#Intermediate
Back to all Express JS Questions→