'How to prevent Safari from dropping the Authorization header when following a same-origin redirect?

Safari seems to drop the Authorization header when following a same-origin 301 redirect. For example, this JS code:

fetch("/api/endpoint-that-redirects", { headers: new Headers({ "Authorization": "sometoken" })})

will trigger one GET to /api/endpoint-that-redirects with the Authorization header, which responds with a 301 w/ Location /api/endpoint. The browser follows this automatically, meaning it makes another GET to /api/endpoint, but this time without the Authorization header.

This seems to be expected behavior when redirecting to a different origin, but I can't see why this would happen if the redirect is to another URL at the same origin.

I've seen a lot of posts online and questions about this behavior on StackOverflow, but I haven't seen any definitive solution or at least an explanation about this behavior. It's also not clear in other questions if the redirect is to the same host.

Chrome (98) and Firefox (97) both follow the redirect and include the Authorization header in the subsequent GET request.



Solution 1:[1]

Safari 15.4+ (iOS 15.4, macOS 12.3) users will no longer experience this Authorization drop.

Details: A fix for this was actually merged into the WebKit/Safari code back in October 2021 but per comments at https://bugs.webkit.org/show_bug.cgi?id=230935#c18 didn’t end up shipping until mid-March 2022 in Safari 15.4.

So, this problem will continue to happen for any users of Safari versions prior to to 15.4 — users not upgraded to iOS 15.4 or macOS 12.3 yet — but not for users with current Safari/iOS/macOS.

Solution 2:[2]

This is a bug per the Fetch Standard as written. See httpRequest in HTTP-network-or-cache fetch. Each HTTP request essentially starts out with a clone from the input request, which includes all developer-set headers.

However, for the specific case of Authorization it is an open issue whether it shold be included across origins.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sideshowbarker
Solution 2 Anne