Authorization header in img src link

I have apione that uses jwtfor authentication. I use this api for the application vuejs. I am trying to show an image in an application using

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

But apiexpecting a Authorizationheadline jwt tokenin it.

Is it possible to add headers to the browser request like this (the answer to several questions here made me believe that this is impossible)?

Is there a way around this (using js) or changing it myself api?

+21
source share
4 answers

, href img. , ajax html.

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

JWT queryparam.

+1

. fetch cookie fetch header {credentials: 'omit'}. MDN

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) {
...

, , - - localStorage, cookie. :

let reqJson = await req.json();
// response is: {token: 'string'}
//// login successful if there 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
}

, - localStorage, . (img, video, href), .

cookie , .

Node.js + -:

.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();
})

, - .

+1

staci img

<img src="my/api/icon/my-icon.png" />

<img src= ${pathInServer} />. .

-2

All Articles