首页 > 解决方案 > 无法读取未定义的属性“会话” - 管理会话 Cookie Firebase 身份验证生成的 cookie

问题描述

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

我正在关注一个名为Manage Session CookiesFirebase signInWithEmailAndPassword的 Firebase 教程,该教程描述了如何在用户使用该功能登录后生成 cookie 。用户idTokenthen传递给一个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 端点,它idToken从先前的POST请求中获取 ,使用 创建会话 cookie createSessionCookie,然后使用 设置 cookie res.cookie('session', sessionCookie, options)

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,而是收到一条错误消息,说明TypeError: Cannot read property 'session' of undefined我的会话 cookie:

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 是否以某种方式没有从发生to/dashboard的页面转移到这个新的端点,?POST/login

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

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

标签: javascriptfirebaseexpresssessioncookies

解决方案


我相信你需要使用__sessioncookie。

将 Firebase 托管与 Cloud Functions 或 Cloud Run 一起使用时,通常会从传入请求中删除 cookie。 资源

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


推荐阅读