Request headers not sent from Service Worker

2019-03-30 05:47发布

问题:

I'm trying to fetch a web service from a Service Worker. This service is a JSP secured with basic Apache authentication, so I must provide the credentials to authenticate in the request headers. The following request works just fine from 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) {

    })
  );
});

That code is into an event.waitUntil() scope, into a function called from a 'push' event listener. However, the same exact call fails with a 401 (Unauthorized). The Network panel from the developer tools shows the headers are not being 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 there something missing here? or it just can't be achieved from a Service Worker?

Some extra info: just can't use XMLHttpRequest since it is 'Not defined' on the service worker scope. The headers on the JSP before retrieving the 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: definitely there is something with the authentication headers from the service workers, since the requests to non-secured URLs does not fails. The same service without Apache authorization works as expected.

回答1:

You should set as allowed headers also accept and authorization

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

also body of the response for "OPTIONS" request should be empty (it is not necessary indeed, but there is no use case for body in such response) and Content-length: should be 0 (zero)

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



回答2:

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

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