Open Redirect in Flask with Basic Auth
Open Redirect in Flask with Basic Auth — how this specific combination creates or exposes the vulnerability
An open redirect in a Flask application using HTTP Basic Authentication occurs when an attacker can influence the redirect target after successful or partial authentication, enabling phishing or credential theft. The vulnerability arises when a redirect response (typically an HTTP 302) uses an attacker-controlled URL, often sourced from request parameters or headers without strict validation. In a Basic Auth context, the browser may send an Authorization header automatically when the redirect targets the same origin, but if the redirect goes to a different origin, the browser usually does not forward credentials. However, the initial authenticated request can still be abused to lure users into following a malicious chain, for example by embedding a link that includes session or referrer information that aids the attacker.
Consider a Flask route that redirects users based on a next query parameter without validation:
from flask import Flask, request, redirect
app = Flask(__name__)
@app.route('/login')
def login():
# Vulnerable: no validation of the 'next' parameter
next_url = request.args.get('next', '/')
return redirect(next_url)
If this route is protected by Basic Auth, an attacker could craft a URL like https://api.example.com/login?next=https://evil.com. A user who clicks this link and has cached credentials might be redirected to the attacker’s site after the browser sends the Authorization header to the Flask app. Even though the browser stops sending credentials to evil.com, the user may already have been tricked into following the redirect believing it is part of the trusted domain. Attack patterns such as this are commonly seen in OAuth misconfigurations and can be combined with SSRF or insecure direct object references to broaden impact.
In API contexts where Basic Auth is used, open redirects can also appear in error messages or unauthenticated entry points that later redirect authenticated flows. Because middleBrick scans unauthenticated attack surfaces, it can detect open redirect patterns by analyzing response headers and tracing redirect chains, flagging missing allowlists and unsafe use of user input in location headers.
Basic Auth-Specific Remediation in Flask — concrete code fixes
To mitigate open redirects in Flask with Basic Auth, always validate and restrict redirect targets to a safe set of paths or a strict allowlist. Avoid using raw user input in redirect responses. Below are concrete, secure coding examples.
1. Allowlist-based redirect validation
Define a set of trusted paths and reject any redirect that does not match.
from flask import Flask, request, redirect, abort
import urllib.parse
app = Flask(__name__)
TRUSTED_HOSTS = {'app.example.com', 'api.example.com'}
def is_safe_url(target):
parsed = urllib.parse.urlparse(target)
if parsed.scheme not in {'http', 'https'}:
return False
if parsed.hostname not in TRUSTED_HOSTS:
return False
# Optionally restrict to same path prefix
return parsed.path.startswith(('/dashboard', '/profile', '/api/'))
@app.route('/login')
def login():
next_url = request.args.get('next', '/')
if not is_safe_url(next_url):
abort(400, 'Invalid redirect target')
return redirect(next_url)
2. Use internal route names instead of raw URLs
Prefer named endpoints and the url_for function to generate safe redirects.
from flask import Flask, request, redirect, url_for
app = Flask(__name__)
@app.route('/login')
def login():
target = request.args.get('next', 'index')
# Only allow known endpoint names
allowed_endpoints = {'index', 'dashboard', 'settings'}
if target not in allowed_endpoints:
target = 'index'
return redirect(url_for(target))
3. Enforce HTTPS and avoid open redirects in error flows
Ensure that any redirect preserves secure transport and does not leak credentials in query strings.
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/oauth-callback')
def oauth_callback():
# Always use url_for for internal redirects
return redirect(url_for('oauth_handler', _external=True))
For API consumers using Basic Auth, combine these practices with strong password policies and consider deprecating Basic Auth in favor of token-based mechanisms where feasible. middleBrick’s continuous monitoring in the Pro plan can detect regressions by scanning on a configurable schedule and alerting when new open redirect patterns appear.