MEDIUM open redirectaxumbasic auth

Open Redirect in Axum with Basic Auth

Open Redirect in Axum with Basic Auth — how this specific combination creates or exposes the vulnerability

An open redirect in an Axum application that uses HTTP Basic Authentication can occur when a redirect target is derived from user-supplied input and the application relies on the presence of Basic Auth credentials to gate access. Even though Basic Auth provides a form of authentication, it does not prevent an attacker from influencing the redirect destination. If the server accepts a URL or path parameter such as next, return_to, or redirect and uses it in a 3xx response without strict validation, the authentication layer does not mitigate the open redirect risk.

Consider an Axum handler that conditionally requires Basic Auth for certain routes but still processes an external redirect parameter without validating that the target is same-origin or explicitly allowed. An attacker can supply a malicious URL as the redirect parameter. When a victim with valid Basic Auth credentials follows a crafted link, the browser first sends the Authorization header. If the server then responds with a 302 to the attacker-controlled URL, the browser automatically includes the same credentials in subsequent requests to the malicious site, enabling credential phishing or session fixation in the context of the trusted origin.

In practice, this can manifest when an application uses route parameters or query strings to determine where to send the client after login or an action that requires authentication. For example, a handler might parse form.next or a query string like ?redirect=https://example.com/account. If the server does not enforce a strict allowlist or prefix check (e.g., only allowing paths within the app’s domain), the Basic Auth protection becomes a mechanism that helps the attacker appear authenticated while the redirect carries the victim to an untrusted site. The presence of credentials does not neutralize the open redirect; it simply means that any leakage or reuse of those credentials on the malicious site may be more impactful because the user believes they are interacting with a trusted service.

Moreover, tooling such as middleBrick can detect this category of issue by analyzing the unauthenticated attack surface and the spec-defined routes alongside runtime behavior. It checks whether redirect responses include user-controlled locations and whether authentication mechanisms like Basic Auth are combined with insufficient validation. Findings from such scans can highlight insecure patterns in parameter handling and response construction that lead to open redirects, even when credentials are required to reach the endpoint.

Basic Auth-Specific Remediation in Axum — concrete code fixes

To remediate open redirect in Axum when using Basic Auth, ensure that any redirect target is either not user-controlled or is strictly validated against an allowlist. Do not rely on authentication alone to prevent unsafe navigation. Below are concrete code examples that demonstrate a vulnerable pattern and a secure fix.

Vulnerable example with Basic Auth and an unchecked redirect parameter:

use axum::{routing::get, Router, http::HeaderMap, response::Redirect};
use std::net::SocketAddr;

async fn handler_with_redirect(
    headers: HeaderMap,
    query: axum::extract::Query>,
) -> Redirect {
    // Vulnerable: redirect parameter is used without validation
    let redirect_to = query.get("redirect").unwrap_or(&"/home".to_string());
    Redirect::to(redirect_to)
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/login", get(handler_with_redirect));
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

This handler inspects a query parameter redirect and directly passes it to Redirect::to. Basic Auth may be enforced elsewhere via middleware, but the redirect itself is not constrained, enabling an open redirect.

Secure remediation with explicit allowlist and path-based redirects:

use axum::{routing::get, Router, http::HeaderMap, response::Redirect, extract::Extension};
use std::net::SocketAddr;

/// Validate redirect path: only allow same-origin paths, no external URLs.
fn safe_redirect_path(input: &str) -> bool {
    // Allow only paths that start with '/' and do not contain '://' or other schemes.
    input.starts_with('/') && !input.contains("://")
}

async fn handler_with_safe_redirect(
    headers: HeaderMap,
    query: axum::extract::Query>,
) -> Redirect {
    // Default destination within the application
    let default = "/dashboard";
    // Use a validated, same-origin path only
    let target = query.get("redirect")
        .filter(|url| safe_redirect_path(url))
        .unwrap_or(&default);
    Redirect::to(target)
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/login", get(handler_with_safe_redirect));
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

The secure version uses a helper safe_redirect_path to ensure the target is a same-origin path and rejects any value containing a scheme (://) or resembling an external URL. This approach ensures that even when Basic Auth credentials are present, the application does not redirect users to arbitrary external domains.

Additionally, prefer using internal route names or enums rather than raw strings for destinations. If you must accept external origins (e.g., OAuth flows), maintain a strict allowlist of trusted domains and perform exact or prefix matching before issuing the redirect. Combining these validations with proper use of middleware for Basic Auth ensures that authentication and navigation remain independently secure.

Frequently Asked Questions

Does using Basic Auth in Axum automatically prevent open redirects?
No. Basic Auth provides credentials but does not validate redirect targets. If your handler uses user-controlled parameters for redirect URLs without strict allowlist checks, an open redirect can still occur.
What is a safer pattern for handling redirects in Axum with authentication?
Validate redirect parameters against an allowlist of same-origin paths, reject any URLs containing schemes like http:// or https://, and default to a known internal route. Do not rely on authentication headers to enforce safe navigation.