无法读取未定义的属性“会话”-管理会话Cookie Firebase身份验证生成的Cookie

时间:2019-11-25 20:26:36

标签: javascript firebase express session cookies

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

我正在遵循一个名为Manage Session Cookies的Firebase教程,该教程描述了用户使用Firebase signInWithEmailAndPassword函数登录后如何生成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,使用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不会以某种方式从发生/dashboardPOST的页面转移到这个新端点/login

req登录到/dashboard后,我发现其中包含以下内容,但是我不知道它是否来自其他会话。如果它来自Firebase,我不知道如何正确访问它:

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

1 个答案:

答案 0 :(得分:2)

我认为您需要使用__session cookie。

  

将Firebase Hosting与Cloud Functions或Cloud一起使用时   运行时,通常会将Cookie从传入请求中删除。   source

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