JAVASCRIPT

Prevent Open Redirect Vulnerabilities

Safeguard your Node.js/Express application from open redirect vulnerabilities by securely validating and whitelisting redirect URLs to trusted internal or domain-specific paths.

const express = require('express');
const app = express();

const ALLOWED_REDIRECT_DOMAINS = ['localhost:3000', 'www.yourdomain.com', 'sub.yourdomain.com'];

function isValidRedirectUrl(url) {
  try {
    const parsedUrl = new URL(url, 'http://dummy.com'); // Base URL needed for relative paths

    // 1. Check if the URL is relative (internal path)
    if (parsedUrl.hostname === 'dummy.com' || url.startsWith('/')) {
      return true;
    }

    // 2. Check if the URL's hostname is in the allowed list
    if (ALLOWED_REDIRECT_DOMAINS.some(domain => parsedUrl.hostname === domain || parsedUrl.hostname.endsWith('.' + domain))) {
      return true;
    }

    return false;
  } catch (error) {
    return false; // Invalid URL format
  }
}

app.get('/redirect', (req, res) => {
  const targetUrl = req.query.url;

  if (targetUrl && isValidRedirectUrl(targetUrl)) {
    return res.redirect(targetUrl);
  } else {
    // Fallback to a safe default page or show an error
    return res.redirect('/'); 
  }
});

app.get('/', (req, res) => {
  res.send('Welcome to the homepage. Try redirecting to <a href="/redirect?url=/dashboard">/dashboard</a> or <a href="/redirect?url=https://www.yourdomain.com/about">https://www.yourdomain.com/about</a>');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: Open redirect vulnerabilities occur when a web application redirects users to an arbitrary URL specified in a request parameter, potentially leading to phishing attacks. This snippet provides a `isValidRedirectUrl` function for an Express.js application to prevent such vulnerabilities. It validates the `targetUrl` by first checking if it's a relative path (internal to the application) or if its domain is explicitly whitelisted. The `URL` constructor is used to safely parse URLs and extract hostname information. If the URL is not valid, the user is redirected to a safe default page (e.g., '/', the homepage), mitigating the risk of malicious redirects. Remember to keep `ALLOWED_REDIRECT_DOMAINS` up-to-date and restrict it only to trusted domains.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs