Handling authentification to Firebase Database with Fetch in a Service Worker

最后都变了- 提交于 2019-12-07 12:33:42

问题


I'm trying to query a Firebase database from a Service Worker using the Fetch API. However it doesn't work as expected as I can't get authenticated correctly.

Basically what I'm trying to do is from origin https://myproject.firebaseapp.com inside a Service Worker I do a call like this :

var fetchOptions = {};
fetchOptions.credentials = 'include';
var url = options.messageUrl;
var request = new Request('https://myproject.firebaseio.com/user/foobar.json', fetchOptions);   
messagePromise = fetch(request).then(function(response) {
  return response.json();
});

I'm getting this error :

Fetch API cannot load https://myproject.firebaseio.com/user/foobar.json. Response to preflight request doesn't pass access control check: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'https://myproject.firebaseapp.com' is therefore not allowed access.

Any idea of a way to fix it? How one should do to query/update the Firebase database from a SW?

I've read https://jakearchibald.com/2014/using-serviceworker-today/ and one of the gotcha was exactly that problem, the fact that Fetch request do not send authentification.

Ideally it would be great to be able to use the Firebase JS API inside a SW but this doesn't seem to work as well.


回答1:


Firebase doesn't store authentication info as a cookie or in anything that would be sent along in the credentials, so there's no need to send them in your fetch request. Instead, you'll need to pull the token from Firebase Auth:

firebase.auth().currentUser.getToken(true).then(function(token) {
  // token is the value you'll need to remember for later
});

Once you've got the token, you should be able to add it as a query parameter to the REST request e.g. ?auth={THE_TOKEN}. This will allow you to make your authenticated request in the Service Worker.



来源:https://stackoverflow.com/questions/37982400/handling-authentification-to-firebase-database-with-fetch-in-a-service-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!