javascript img src 链接中的授权标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46642960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:49:56  来源:igfitidea点击:

Authorization header in img src link

javascripthtmljwt

提问by Ragas

I have an apithat uses jwtfor authencation. I am using this api for a vuejsapp. I am trying to display an image in the app using

我有一个api使用jwt的authencation。我正在将此 api 用于vuejs应用程序。我正在尝试使用

<img src="my/api/link" />

But the apiexpects Authorizationheader with jwt tokenin it.

但是里面的apiexpectsAuthorization标头jwt token

Can I add headers to browser request like this(Answer to few questions here has made me believe it's not possible)?

我可以像这样向浏览器请求添加标头吗(对这里的几个问题的回答让我相信这是不可能的)?

Is there any way around it(using js) or should i change the apiitself?

有没有办法解决它(使用js)或者我应该改变它api本身吗?

采纳答案by Tapas

You can not perform authentication on images which are directly used as href in img tag. If you really want this type of authentication on your images, then it's better to fetch them using ajax and then embed in your html.

您不能对直接用作 img 标签中的 href 的图像进行身份验证。如果您真的希望对图像进行这种类型的身份验证,那么最好使用 ajax 获取它们,然后嵌入到您的 html 中。

回答by arcol

By default browsers are sending cookies. You can prevent cookie sending in fetchif you set header's {credentials: 'omit'}. MDN

默认情况下,浏览器会发送 cookie。您可以防止饼干在发送fetch,如果你设置页眉的{credentials: 'omit'}MDN

Full fetchexample:

完整fetch示例:

const user = JSON.parse(localStorage.getItem('user'));
let headers = {};

if (user && user.token) {
  headers = { 'Authorization': 'Bearer ' + user.token };
} 

const requestOptions = {
    method: 'GET',
    headers: headers,
    credentials: 'omit'
};

let req = await fetch(`${serverUrl}/api/v2/foo`, requestOptions);
if (req.ok === true) {
...

Now, when you are login in, in your website, the webapp could save to credentials into bothlocalStorage and cookie. Example:

现在,当你正在登录,在您的网站,web应用程序可以保存到凭据为双方的localStorage和饼干。例子:

let reqJson = await req.json();
// response is: {token: 'string'}
//// login successful if there's a jwt token in the response
if (reqJson.token) {
    // store user details and jwt token in local storage to keep user logged in between page refreshes
    localStorage.setItem('user', JSON.stringify({token: reqJson.token}));
    document.cookie = `token=${reqJson.token};`; //set the cookies for img, etc
}

So your webapp uses localStorage, just like your smartphone application. Browser gets all the static contents (img, video, a href) by sending cookies by default.

所以你的 webapp 使用 localStorage,就像你的智能手机应用程序一样。默认情况下,浏览器通过发送 cookie 来获取所有静态内容(img、video、a href)。

On the server side, you can copy the cookie to authorization header, if there is none.

在服务器端,如果没有,您可以将 cookie 复制到授权标头。

Node.js+express example:

Node.js+express 示例:

.use(function(req, res, next) { //function setHeader
  if(req.cookies && req.headers &&
     !Object.prototype.hasOwnProperty.call(req.headers, 'authorization') &&
     Object.prototype.hasOwnProperty.call(req.cookies, 'token') &&
     req.cookies.token.length > 0
   ) {
    //req.cookies has no hasOwnProperty function,
    // likely created with Object.create(null)
    req.headers.authorization = 'Bearer ' + req.cookies.token.slice(0, req.cookies.token.length);
  }
  next();
})

I hope it helps someone.

我希望它可以帮助某人。

回答by Alexys

<img src="/api/images/yourimage.jpg?token=here-your-token">

In the backend you validate JWT from queryparam.

在后端,您从 queryparam 验证 JWT。

回答by Пантилеймон Кул?ш

There is another one method adds headers to HTTP request. Is it "Intercept HTTP requests". https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests

还有另一种方法向 HTTP 请求添加标头。是“拦截HTTP请求”吗?https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests