Curl Basic Auth Redirect to Different Host

When using the curl command-line tool, managing sensitive data during HTTP redirects is a critical security consideration. By default, if curl is configured to follow redirects and is sent to a different host, it automatically strips basic authentication credentials to prevent security leaks. This article explains this default security behavior, how same-host redirects differ, and how to override this restriction using specific curl flags when necessary.

Default Security Behavior

When you pass basic authentication credentials to curl using the -u or --user option, curl converts these credentials into an Authorization: Basic <credentials> header. If you also use the -L or --location flag to follow HTTP 3xx redirects, curl monitors the destination of the redirect.

If the redirect location points to a different host (a different domain or subdomain), curl will automatically remove the Authorization header from the subsequent request. This prevents your username and password from being exposed to an untrusted external server.

Same-Host vs. Different-Host Redirects

How to Allow Credentials on Redirects: --location-trusted

If you are sure that the redirected host is safe and you need to pass the basic authentication credentials to it, you can override curl’s default security behavior.

To do this, use the --location-trusted option instead of the standard -L or --location option:

curl --location-trusted -u username:password https://example.com/redirect-to-external

When --location-trusted is used, curl will pass the username and password to all hosts that it is redirected to, regardless of whether they match the original host.

Security Best Practices

Using --location-trusted should be done with extreme caution. If the initial server is compromised or if an attacker can manipulate the redirect destination, your plaintext-equivalent basic authentication credentials will be transmitted to the attacker’s server. Whenever possible, it is safer to handle the redirect manually in your script or application by inspecting the Location header first before deciding to send credentials to the new host.