【问题标题】:Handling authentification to Firebase Database with Fetch in a Service Worker在 Service Worker 中使用 Fetch 处理对 Firebase 数据库的身份验证
【发布时间】:2023-03-05 19:49:01
【问题描述】:

我正在尝试使用 Fetch API 从 Service Worker 查询 Firebase 数据库。但是它不能按预期工作,因为我无法正确验证。

基本上我想要做的是来自 Service Worker 内部的 origin https://myproject.firebaseapp.com 我做了这样的调用:

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

我收到此错误:

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.

有解决方法的想法吗?如何从 SW 查询/更新 Firebase 数据库?

我已经阅读了https://jakearchibald.com/2014/using-serviceworker-today/,其中一个问题正是这个问题,即 Fetch 请求不发送身份验证这一事实。

理想情况下,能够在 SW 中使用 Firebase JS API 会很棒,但这似乎也无法正常工作。

【问题讨论】:

    标签: firebase firebase-realtime-database firebase-authentication service-worker fetch-api


    【解决方案1】:

    Firebase 不会将身份验证信息存储为 cookie 或任何将随凭据一起发送的内容,因此无需在您的获取请求中发送它们。相反,您需要从 Firebase Auth 中提取令牌:

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

    获得令牌后,您应该能够将其作为查询参数添加到 REST 请求中,例如?auth={THE_TOKEN}。这将允许您在 Service Worker 中发出经过身份验证的请求。

    【讨论】:

    • 感谢您的回答,我按照您的建议做了并且可以成功检索令牌,然后我将其传递给 SW 并可以成功存储它以供查询。但是,当我使用 ?token={the_token} 查询 URL 时,我得到了一个权限被拒绝的答案。事实上,具有相同 URL 和令牌的 curl 返回相同的结果。我错过了什么?请注意,应用程序的其余部分可以使用 PolymerFire 元素很好地查询 firebase 数据库(我已成功登录)
    • 糟糕!这就是我没有用文档刷新自己的结果。参数实际上是?auth= 而不是?token=。有关更多有用信息,请参阅 the docs
    猜你喜欢
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 2017-05-07
    • 2017-01-13
    • 2019-04-19
    • 1970-01-01
    相关资源
    最近更新 更多