Open redirect

Validate redirect hosts and schemes to prevent unintended redirects to external sites.

Description

Redirecting to an unchecked next value lets the caller send visitors outside the service.

Potential impact

Users may disclose sensitive information on a phishing site. Filters that check only the initial domain can miss the external destination.

Remediation

For internal navigation, use a server-defined or validated local path. A value beginning with // can name an external host. If external redirects are required, check the parsed URL against the service’s allow-list. Use an internal fallback or reject the request if it fails.

Examples

Set allowed hosts for the actual service. Django's home and Flask's index refer to internal routes defined by the application.

Django

Before

python
# Unsafe Django code
from django.http import HttpResponseRedirect

def unsafe_redirect(request):
    url = request.GET.get('next')
    return HttpResponseRedirect(url)

After

python
# Safe Django code
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.http import url_has_allowed_host_and_scheme

def safe_redirect(request):
    url = request.GET.get('next', '')
    allowed_hosts = {'example.com', 'mysite.com'}
    if url_has_allowed_host_and_scheme(
        url,
        allowed_hosts=allowed_hosts,
        require_https=True,
    ):
        return HttpResponseRedirect(url)
    return redirect('home')

With these settings, Django’s helper accepts local relative paths or HTTPS destinations that exactly match its allow-list. The listed hosts have no port, so an explicitly supplied port does not match. Failed checks fall back to home.

Flask

Before

python
# Unsafe Flask code
from flask import Flask, request, redirect

app = Flask(__name__)

@app.route('/redirect')
def unsafe_redirect():
    url = request.args.get('next')
    return redirect(url)

After

python
# Safe Flask code
from flask import Flask, request, redirect, url_for
from urllib.parse import urlsplit

app = Flask(__name__)
ALLOWED_REDIRECT_HOSTS = frozenset({'example.com', 'mysite.com'})

def is_allowed_redirect(url):
    if not url:
        return False
    try:
        parsed = urlsplit(url)
        port = parsed.port
    except ValueError:
        return False

    return (
        parsed.scheme == 'https'
        and parsed.hostname in ALLOWED_REDIRECT_HOSTS
        and parsed.username is None
        and parsed.password is None
        and port in (None, 443)
    )

@app.route('/redirect')
def safe_redirect():
    url = request.args.get('next')
    if is_allowed_redirect(url):
        return redirect(url)
    return redirect(url_for('index'))

The Flask example’s is_allowed_redirect requires HTTPS, a listed hostname and either an omitted port or 443. It rejects URL usernames and passwords. The handler falls back to index if any check fails.

FastAPI

Before

python
# Unsafe FastAPI code
from fastapi import FastAPI, Request
from starlette.responses import RedirectResponse

app = FastAPI()

@app.get("/redirect")
async def unsafe_redirect(request: Request):
    url = request.query_params.get('next')
    return RedirectResponse(url)

After

python
# Safe FastAPI code
from fastapi import FastAPI, Request, HTTPException
from starlette.responses import RedirectResponse
from urllib.parse import urlsplit

app = FastAPI()
ALLOWED_REDIRECT_HOSTS = frozenset({'example.com', 'mysite.com'})

def is_allowed_redirect(url):
    if not url:
        return False
    try:
        parsed = urlsplit(url)
        port = parsed.port
    except ValueError:
        return False

    return (
        parsed.scheme == 'https'
        and parsed.hostname in ALLOWED_REDIRECT_HOSTS
        and parsed.username is None
        and parsed.password is None
        and port in (None, 443)
    )

@app.get("/redirect")
async def safe_redirect(request: Request):
    url = request.query_params.get('next')
    if is_allowed_redirect(url):
        return RedirectResponse(url)
    raise HTTPException(status_code=400, detail="Invalid redirect URL")

The FastAPI example’s is_allowed_redirect uses the same HTTPS, hostname, port and user information checks. If validation fails, the handler returns HTTP 400.

References