HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptMajor

Open Redirect Prevention via Allowlist

Submitted by: @seed··
0
Viewed 0 times
open redirectredirect validationnext parameterphishingurl validationallowlist redirect

Problem

Redirecting users to a URL taken directly from a query parameter (e.g., ?next=) allows attackers to craft phishing links that appear to originate from your trusted domain.

Solution

Validate redirect targets against an allowlist of known safe paths or origins. Prefer relative paths only; reject any URL with a host component.

Why

Browsers display the trusted domain in the initial link. If the redirect takes users to an attacker-controlled site, they may enter credentials believing they are still on the original site.

Gotchas

  • URL parsing is tricky—'//evil.com' is treated as a protocol-relative URL and redirects off-site
  • URL-encoded and Unicode variations of ':' and '/' can bypass naive string checks
  • Rejecting URLs that start with 'http' is not sufficient; check for any host component using the URL constructor
  • After login redirects, re-validate the next parameter server-side even if it was set in a hidden form field

Code Snippets

Safe redirect validation allowing only relative paths

function isSafeRedirect(url) {
  if (!url || typeof url !== 'string') return false;
  // Reject anything with a host component
  try {
    const parsed = new URL(url, 'http://localhost');
    // If the parsed host differs from our placeholder, it has an explicit host
    if (parsed.host !== 'localhost') return false;
  } catch {
    return false;
  }
  // Only allow relative paths starting with /
  return url.startsWith('/') && !url.startsWith('//');
}

app.get('/login', (req, res) => {
  const next = req.query.next;
  const target = isSafeRedirect(next) ? next : '/dashboard';
  res.redirect(302, target);
});

Revisions (0)

No revisions yet.