如何将授权令牌添加到 JavaScript 函数以下载文件?

huangapple go评论79阅读模式
英文:

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

问题

我有一个Blazor客户端,有一个需要下载文件的函数。

我查看了这个参考链接。如果我将API端点设置为允许匿名访问,它可以正常工作。但是当我将API端点设置为[Authorize]时,我不知道如何传递Bearer令牌给请求。

我可以将令牌传递给函数triggerFileDownload的最后一个参数,但不确定如何将其放入请求中。

我尝试过如下方式,但没有成功,出现了401未经授权的错误:

window.triggerFileDownload = (fileName, url, token) => {
    
    const anchorElement = document.createElement('a');
    createCookie('Authorization', 'Bearer ' + token, 1); //这行没有生效
    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=/";
}

当我在浏览器中打开网络选项卡时,我看到:

如何将授权令牌添加到 JavaScript 函数以下载文件?

请问是否有人可以建议如何将令牌传递给这个函数的请求?我认为这可能需要在评论中标记的代码中完成(//这行没有生效)。

提前感谢。

英文:

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 annonymous. But when I set api endpoint with [Authorize] I dont 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:

如何将授权令牌添加到 JavaScript 函数以下载文件?

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.

答案1

得分: 2

授权标头应该在标头中传递,我认为当您单击按钮时,直接传递授权标头是不可能的。

另一种方法是使用XHR调用来下载文件并传递授权Bearer令牌。

英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

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

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月15日 19:51:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定