Request headers not sent from the Service Worker

I am trying to get a web service from Service Worker. This service is a JSP protected by basic Apache authentication, so I have to provide authentication credentials in the request headers. The following query works fine in the main window:

self.addEventListener('push', function(event) { console.log('Received a push message', event); event.waitUntil( fetch(ONLINE_SITE_ENDPOINT, { method: 'GET', mode: 'cors', headers: { 'Accept': 'application/json', 'Authorization': 'Basic btoa(auth info)' } }).then(function(response) { //process response }).catch(function(err) { }) ); }); 

This code falls within the scope of event.waitUntil () in a function called from the push event listener. However, the same exact call fails with 401 (Unauthorized). The Network panel from the developer tools shows that headers are not sent:

 OPTIONS /latest-new.jsp HTTP/1.1 Host: {an accessible host} Connection: keep-alive Access-Control-Request-Method: GET Origin: http://localhost User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36 Access-Control-Request-Headers: accept, authorization Accept: */* Referer: http://localhost/service-worker.js Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8 

Is something missing here? or can it simply not be achieved by a worker?

Additional information: simply cannot use XMLHttpRequest, since it is "not defined" in the working worker area. JSP headers before extracting JSON:

 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 

UPDATE: There is definitely something with authentication headers from production services, as requests for insecure URLs do not fail. The same service without authorization Apache works as expected.

+5
source share
2 answers

You must set how allowed headers also accept and authorization

 response.setHeader( "Access-Control-Allow-Headers", "x-requested-with, accept, authorization" ); 

also the response body for the β€œOPTIONS” request should be empty (this is not necessary, but there is no case for the body in such an answer), and Content-length: should be 0 (zero)

Please note that this request should not be passed to the application (you can, but do not need)

+1
source

Pass {"credentials": "include"} as the parameter to call fetch ().

https://fetch.spec.whatwg.org/

0
source

All Articles