JAVASCRIPT
Preventing Open Redirect Vulnerabilities in Express.js
Secure Express.js applications by validating redirect URLs against a whitelist or ensuring they are relative paths to prevent open redirect attacks.
const express = require('express');
const app = express();
const port = 3000;
// A whitelist of allowed external domains for redirects
const ALLOWED_EXTERNAL_REDIRECT_DOMAINS = [
'https://trusted-partner.com',
'https://another-safe-site.org'
];
function isSafeRedirectUrl(url) {
if (!url) {
return false;
}
// 1. Check for relative paths (always safe for internal redirects)
// Starts with '/' and doesn't start with '//' (protocol-relative URL)
if (url.startsWith('/') && !url.startsWith('//')) {
return true;
}
// 2. Check against a whitelist for absolute URLs
try {
const parsedUrl = new URL(url);
const origin = parsedUrl.origin; // e.g., "https://example.com"
// Ensure the protocol is http or https
if (!['http:', 'https:'].includes(parsedUrl.protocol)) {
return false;
}
// Check if the origin is in our allowed list
return ALLOWED_EXTERNAL_REDIRECT_DOMAINS.includes(origin);
} catch (e) {
// Invalid URL format
return false;
}
}
app.get('/login', (req, res) => {
const redirectUrl = req.query.next || '/dashboard'; // Get 'next' from query or default
if (isSafeRedirectUrl(redirectUrl)) {
console.log('Redirecting to a safe URL:', redirectUrl);
return res.redirect(redirectUrl);
} else {
console.warn('Attempted open redirect blocked:', redirectUrl);
// Fallback to a safe default or show an error
return res.redirect('/dashboard');
}
});
app.get('/dashboard', (req, res) => {
res.send('Welcome to the dashboard!');
});
app.get('/', (req, res) => {
res.send('Homepage. Try /login?next=https://trusted-partner.com/profile or /login?next=/dashboard');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
How it works: An open redirect vulnerability allows an attacker to manipulate a URL parameter (like `redirect` or `next`) to redirect users from a trusted site to an arbitrary, potentially malicious site. This Express.js snippet provides an `isSafeRedirectUrl` function that validates any redirect target. It prioritizes relative paths (which are inherently safe for internal redirects) and, for absolute URLs, checks if their origin matches a predefined whitelist of trusted external domains, preventing redirects to untrusted destinations.