JAVASCRIPT
Preventing Open Redirect Vulnerabilities
Protect your web application from open redirect vulnerabilities by strictly validating and whitelisting redirect URLs before processing any redirection.
const express = require('express');
const app = express();
// Whitelisted domains for redirection
const ALLOWED_REDIRECT_DOMAINS = [
'example.com',
'www.example.com',
'secure.example.com',
'another-safe-domain.com'
];
// Middleware to validate redirect URLs
function validateRedirectUrl(req, res, next) {
const redirectTo = req.query.next || req.body.next; // Common parameters for redirects
if (redirectTo) {
try {
const redirectUrl = new URL(redirectTo);
const redirectHostname = redirectUrl.hostname;
// Check if the hostname is in the whitelist OR is the same origin
if (ALLOWED_REDIRECT_DOMAINS.includes(redirectHostname) ||
redirectHostname === req.hostname) { // Allow redirects to current host
req.validatedRedirectTo = redirectTo;
return next();
}
} catch (e) {
// URL parsing failed, treat as invalid
}
console.warn(`Attempted invalid redirect to: ${redirectTo}`);
return res.status(400).send('Invalid redirect URL.');
}
next(); // No redirect parameter, continue
}
app.use(validateRedirectUrl); // Apply the validation middleware globally or to specific routes
app.get('/login', (req, res) => {
if (req.query.next) {
// In a real app, authenticate user first. For demo, simulate successful login.
if (req.validatedRedirectTo) {
return res.redirect(req.validatedRedirectTo);
} else {
// Fallback to a default page if validation failed or no 'next' parameter
return res.redirect('/dashboard');
}
}
res.send('Login page. Try navigating to /login?next=https://example.com/profile');
});
app.get('/dashboard', (req, res) => {
res.send('Welcome to the Dashboard!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This snippet illustrates how to prevent open redirect vulnerabilities in an Express.js application. Open redirects occur when an application allows an attacker to manipulate parameters to redirect users to arbitrary, potentially malicious, websites. The solution involves a middleware that validates any `next` (or similar) redirect parameter. It uses a whitelist of allowed domains or ensures the redirect stays within the application's own host. By parsing the URL and checking its hostname against trusted sources, the application prevents phishing and other attacks enabled by uncontrolled redirects.