Olga
Olga

Reputation: 111

How can we initiate a file download request tied to a user gesture with an auth header?

We are trying to build a web page that shows a button to download an XML file. The file is retrieved by making a request to a REST endpoint that requires a Bearer Token in the auth header.

We made a button with onclick function like this:

var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer <bearer token here>")

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
};

fetch('<url>', requestOptions)
  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    // the filename
    a.download = 'todo-1.json';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    alert('your file has downloaded!');
  })
  .catch(() => alert('Error')); 

Reference for above code

This seems to work great in most browsers, however, on Edge this download is blocked by Microsoft Defender SmartScreen, because it is not tied to a user gesture.

How can we initiate a file download request tied to a user gesture with an auth header?

We know we could change the auth mechanism so that it accepts the auth token from a cookie or the body of the request, but we don't want to do this.

Upvotes: 1

Views: 94

Answers (0)

Related Questions