【问题标题】:Cannot read property 'session' of undefined - Manage Session Cookie Firebase Auth generated cookie无法读取未定义的属性“会话” - 管理会话 Cookie Firebase 身份验证生成的 cookie
【发布时间】:2019-11-25 20:26:36
【问题描述】:

我面临的问题是,在设置 Firebase 会话 cookie 后,我转到另一个需要安全的端点,但 req 找不到 cookie。

我正在关注名为 Manage Session Cookies 的 Firebase 教程,该教程描述了如何在用户使用 Firebase signInWithEmailAndPassword 函数登录后生成 cookie。用户idToken 是then 传递给POST 请求:

首先,我正在生成一个令牌并将其发送到一个端点:

function signIn() {
  var email = document.getElementById('email').value;
  var password = document.getElementById('password').value;

  firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === 'auth/wrong-password') {
        alert('Wrong password.');
    } else {
        alert(errorMessage);
    }

    document.getElementById('quickstart-sign-in').disabled = false;

  }).then(user => {
    // Get the user's ID token as it is needed to exchange for a session cookie.
    return user.getIdToken().then(idToken => {
      if (firebase.auth().currentUser) {
        $.ajax({
          method: 'POST',
          url: '/login',
          data: {'email':firebase.auth().currentUser.email,idToken},
          success: function(data) {
            //do other things...
          }
        });          
      }      
    });
  })
}

URL 端点,它从先前的 POST 请求中获取 idToken,使用 createSessionCookie 创建会话 cookie,然后使用 res.cookie('session', sessionCookie, options) 设置 cookie:

exports.postLogin = (req, res, next) => {

  // Get the ID token passed
  const idToken = req.body.idToken.toString();

  // Set session expiration to 14 days.
  const expiresIn = 60 * 60 * 24 * 14 * 1000;

  var exampleDB = admin.database().ref('exampleDB');
  exampleDB.once('value', function(snapshot) {
    //unrelated things happening...
    //generate randomData...
  }).then(function() {
    admin.auth().createSessionCookie(idToken, {expiresIn})
      .then((sessionCookie) => {
       // Set cookie policy for session cookie.
       const options = {maxAge: expiresIn, httpOnly: true, secure: true};
       res.cookie('session', sessionCookie, options);
       res.status(200).send(randomData).end();
      }, error => {
       res.status(401).send('UNAUTHORIZED REQUEST!');
      });    
  });
};

当我转到另一个端点/dashboard 时,我面临的问题从这里开始。找不到我应该设置的 cookie,而是收到一条错误消息,指出我的会话 cookie 的 TypeError: Cannot read property 'session' of undefined:

exports.dashboard = (req, res, next) => {
  const sessionCookie = req.cookies.session || '';
  // a bunch of other code around the session cookie that doesn't even get triggered because of the break in req.cookies.session
}

我是否错误地检索了 cookie?还是我没有正确设置cookie?还是 cookie 没有从发生POST 到/login 的页面转移到这个新端点/dashboard?

在将req 记录到/dashboard 之后,我看到其中有以下内容,但我不知道它是否来自另一个会话。如果它来自 Firebase,我不知道如何正确访问它:

  sessionID: 'ublahxARQVljyGRblahPQrei',
  session: 
   Session {
     cookie: 
      { path: '/',
        _expires: null,
        originalMaxAge: null,
        httpOnly: true },
     returnTo: '/dashboard',
     flash: {},
     _csrfSecret: 'r46blahE+kOzblah5==' },

【问题讨论】:

    标签: javascript firebase express session cookies


    【解决方案1】:

    我相信您需要使用__session cookie。

    将 Firebase 托管与 Cloud Functions 或 Cloud 一起使用时 运行,cookie 通常从传入的请求中剥离。 source

    以前曾以不同的形式遇到过这种情况:Firebase Functions : How to store simple cookies to remember an authenticated user

    【讨论】:

    猜你喜欢
    • 2019-10-28
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多