PYTHON

Implement Secure Redirect Validation in Python Flask

Prevent open redirect vulnerabilities in Flask applications by securely validating all redirect URLs to ensure they point to trusted domains.

from flask import Flask, redirect, request, url_for
from urllib.parse import urlparse, urljoin

app = Flask(__name__)
app.config['SECRET_KEY'] = 'a_very_secret_key_for_flask_sessions' # Replace with a strong, random key in production

# Define a list of trusted domains for redirects
TRUSTED_DOMAINS = ['localhost:5000', 'yourdomain.com', 'www.yourdomain.com']

def is_safe_url(target):
    """
    Checks if the target URL is safe to redirect to.
    A URL is considered safe if it's relative or points to a trusted domain.
    """
    ref_url = urlparse(request.host_url)
    target_url = urlparse(urljoin(request.host_url, target))

    # Check if the scheme and netloc (domain:port) match the current host
    # or if it's explicitly in the trusted domains list.
    # This prevents redirects to external, potentially malicious sites.
    return (target_url.scheme in ('http', 'https') and
            target_url.netloc == ref_url.netloc) or \
           (target_url.netloc in TRUSTED_DOMAINS)

@app.route('/')
def index():
    return 'Welcome to the secure app. Try navigating to /login?next=/dashboard'

@app.route('/login')
def login():
    next_url = request.args.get('next')
    if next_url and is_safe_url(next_url):
        return redirect(next_url)
    else:
        # If 'next' is not safe or not provided, redirect to a default safe page
        return redirect(url_for('dashboard'))

@app.route('/dashboard')
def dashboard():
    return 'Welcome to your secure dashboard!'

# Example of an unsafe redirect attempt (try in browser: /login?next=http://evil.com)
# This will be caught by is_safe_url and redirected to /dashboard.
# To test locally:
# 1. pip install Flask
# 2. Set FLASK_APP=your_file_name.py
# 3. flask run
# 4. Navigate to http://localhost:5000/login?next=http://malicious.com
#    You should be redirected to /dashboard.
# 5. Navigate to http://localhost:5000/login?next=/dashboard
#    You should be redirected to /dashboard.
How it works: This Python Flask snippet demonstrates how to implement secure redirect validation to prevent open redirect vulnerabilities. An open redirect vulnerability allows attackers to redirect users from a trusted site to a malicious one by manipulating URL parameters. The `is_safe_url` function checks if the `next_url` parameter (common in login flows) points to either a relative path within the current application or an explicitly trusted domain. If the URL is deemed unsafe, the application defaults to a secure internal page, thus protecting users from phishing and other redirection-based attacks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs