I'm trying to load some resource, in this example an image, in an HTML file, that has it's source on another server, which requires a login.
So writing
<img src="https://somewebsite.com/images/test.png">
without any form of authorisation provided, will give me a 401 response.
When I request the image e.g. with Postman and set the authorisation header accordingly, the image is loaded.
Embedding the login information directly into the image src like
<img src="https://username:password@somewebsite.com/images/test.png">
works perfectly fine too. Though I don't wan't to have sensible information visible in the DOM.
So basically, what I want to achieve is, that the authorisation header is set for the requests invoked by the img elements.
I already tried to do it with a service worker like this
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('/service-worker.js')
.then(registration => {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
})
.catch(err => {
console.log('ServiceWorker registration failed: ', err);
});
});
}
with the service-worker.js containing
self.addEventListener('fetch', event => {
event.respondWith(
fetch(event.request, {
mode: 'cors',
credentials: 'omit',
headers: {
"Authorization": "Basic " + btoa('cui-test:cui-testcui-test')
}
})
)
});
though that solution only works if the image's URL is hosted on the same server, not cross origin.
I'm wondering if there is any way to configure a service workers scope to another server.
Or a completely different way to set the header on all requests.