What is fetch's redirect and authorization headers expected behavior? (Safari has different behavior from other Mac browsers)
Asked Answered
F

0

7

In short, when using an authorization header with the fetch api and a redirect is followed Chrome, FireFox, and Opera (on a Mac) include the authorization header in the second request. However, Safari (12.0.1) does not. From the fetch api spec and issue #553 my understanding is that the header should be included. Is this a correct understanding of how fetch is supposed to work?

Here's the simplified code I'm using with a workaround for Safari but I'd like to know if there's something I'm doing wrong that's causing the behavior with Safari or if there is a better workaround.

export async function loadData(token) {
  const opts = {headers: {Authorization: `Bearer ${token}`}, credentials: 'include', redirect: 'follow'};
  let response = await fetch('/api/data', opts);

  // Work around for Safari not including headers in redirected request
  if (response.status === 401 && response.redirected) {
    response = await fetch(response.url, opts);
  }

  if (response.ok) {
    return response.json();
  }

  return null;
}

Quick edit some additional info about the redirect. The redirected location is to the same origin and is a 302:

content-length: 118
content-type: text/plain; charset=utf-8
date: Mon, 26 Nov 2018 20:12:18 GMT
location: /api/data/current-version
server: nginx
status: 302
strict-transport-security: max-age=15768000
vary: Accept
Fugacious answered 26/11, 2018 at 20:10 Comment(1)
Your understanding is correct. The request object used for the redirect should be a copy of the request object you created and added the Authorization header to. So if it’s not in Safari, then that sounds like a Safari/WebKit bug which you should take time to report at bugs.webkit.orgDarlinedarling

© 2022 - 2024 — McMap. All rights reserved.