javascriptblazorauthorizationunauthorized

How to add authorize token to js function to download file function?


I have a blazor client and there's a function need to download a file.

I have a look at this reference. It works if I set the API endpoint to allow anonymous. But when I set API endpoint with [Authorize], I don't know how to pass the bearer token to the request.

I can pass the token to the last parameter of the function triggerFileDownload but not sure how to put it in the request.

I have tried as below but didn't work, got the 401 Unauthorized:

window.triggerFileDownload = (fileName, url, token) => {

const anchorElement = document.createElement('a');
createCookie('Authorization', 'Bearer ' + token, 1);//this line didn't work
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
}


function createCookie(name, value, days) {
var expires;
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
}
else {
    expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}

When I open the tab Network in browser, I see:

enter image description here

Please can anyone suggest how to pass the token to the request to this function? I think it would be something needed to be done in the code marked with comment (//this line didn't work).

Thanks in advance.


Solution

  • The authorization header should be pass in the headers and I don't think it's possible directly when you click on a button. Another way is to use a xhr call to download the file and pass the Authorization bearer token

    <html>
        <head>
            <script>
                const origin = location.origin;
                const filename = 'fileToDownload.csv';
                const token = 'XXXXXXXX';
                function downloadFile() {
                    const fileUrl = [origin, filename].join('/');
                    fetch(fileUrl, {
                        method: 'GET',
                        headers: new Headers({
                            'Authorization': 'Bearer ' + token
                        })
                    })
                    .then(function (response) { return response.blob();})
                    .then(function (blob) {
                        var url = window.URL.createObjectURL(blob);
                        console.log(url);
                        var a = document.createElement('a');
                        a.href = url;
                        a.download = filename;
                        document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
                        a.click();    
                        a.remove();  //afterwards we remove the element again  
                    });
                }
            </script>
        </head>
        <body>
            <h1>Download file</h1>
            <div>
                <button onclick="downloadFile()" type="button">download file</button>
             </div>
        </body>
    </html>