关于会话Cookie抛出错误的Firebase示例

时间:2018-07-21 15:28:51

标签: node.js firebase express cookies firebase-authentication

我正在遵循Firebase文档中的示例,但我一直在出错。我已经设法解决了其中的大多数问题,但是却不断出现错误,提示它找不到csrfToken cookie。

我尝试了不同的cookie库,并在浏览器中进行了检查,但仍然找不到csrfToken cookie。

我要提交的代码(客户端)

$("#submit").click(function() {
  firebase.auth().signInWithEmailAndPassword($("#pEmail").val(), 
$("#pPass").val()).then(user => {
    // Get the user's ID token as it is needed to exchange for a session cookie.
    return firebase.auth().currentUser.getIdToken().then(idToken => {
      // Session login endpoint is queried and the session cookie is set.
      // CSRF protection should be taken into account.
      // ...
      const csrfToken = Cookies.get('csrfToken');
      console.log(csrfToken);
      const postPromise = $.post("/signin", {idToken: idToken, csrfToken: csrfToken});
      return postPromise;
    });
  }).then(() => {
    // A page redirect would suffice as the persistence is set to NONE.
    return firebase.auth().signOut();
  }).then(() => {
    window.location.assign('/portal');
  });

});

任何帮助将不胜感激,非常感谢

1 个答案:

答案 0 :(得分:0)

请参见Firebase node quickstart。您的节点应用程序应设置此cookie。从示例代码中:

/**
 * Attaches a CSRF token to the request.
 * @param {string} url The URL to check.
 * @param {string} cookie The CSRF token name.
 * @param {string} value The CSRF token value to save.
 * @return {function} The middleware function to run.
 */
function attachCsrfToken(url, cookie, value) {
  return function(req, res, next) {
    if (req.url == url) {
      res.cookie(cookie, value);
    }
    next();
  }
}

设置中间件:

app.use(
    attachCsrfToken(
        '/', 
        'csrfToken', 
        (Math.random()* 100000000000000000).toString()
    )
);