In this lesson, you will learn how to secure your application against open redirection vulnerabilities by strictly validating and whitelisting destination URLs.
An open redirection vulnerability occurs when an application accepts a user-controlled input to determine a navigation target without proper verification. An attacker can manipulate this input to redirect users to a malicious site, using your trusted domain to lure them into phishing scams or malware downloads.
The Problem: Implicit Trust
Consider a common login flow where you want to redirect a user back to their original page after they authenticate:
// DANGEROUS: Does not validate the 'returnTo' parameter
app.get('/login', (req, res) => {
const returnTo = req.query.returnTo;
res.redirect(returnTo);
});
If an attacker sends a link like your-app.com/login?returnTo=https://malicious-site.com, your server will blindly bounce the user to the attacker's domain. Since the URL starts with your trusted domain, the victim is far more likely to trust the subsequent destination.
The Solution: Whitelisting
To prevent this, you must treat all navigation parameters as untrusted. The most robust defense is to compare the input against a strict allowlist (whitelist) of permitted paths or full URLs.
If the redirect must be dynamic, ensure it is restricted to your own domain and path structure:
const ALLOWED_REDIRECTS = ['/dashboard', '/profile', '/settings'];
app.get('/login', (req, res) => {
const returnTo = req.query.returnTo;
// Validate that the input is in our whitelist
if (ALLOWED_REDIRECTS.includes(returnTo)) {
return res.redirect(returnTo);
}
// Default fallback for unauthorized redirects
res.redirect('/dashboard');
});
For more complex applications, you can use the URL constructor to parse the input and ensure the hostname matches your own, effectively stripping out cross-domain attempts. Never allow a redirect to a user-provided URL that hasn't been explicitly checked against a set of known-good, internal-only endpoints. By enforcing these boundaries, you remove the attacker's ability to weaponize your site's navigation logic.
Key Takeaway: Always treat redirect parameters as untrusted input and strictly validate them against a pre-defined whitelist of internal paths.