Why is the req.cookies.session undefined? Firebase + Node + express

ⅰ亾dé卋堺 提交于 2021-02-07 10:16:13

问题


I'm trying to assign a generate a session cookie in exchange for the provided ID token. Here are the docs I'm following.

Here is my client side sign-in code:

firebase.auth().signInWithEmailAndPassword(email, password)
    .then(function(user) {
        firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
            return sendToken(idToken);
        });
    })
    // .then(() => {
    //     return firebase.auth().signOut();
    // })
    .then(() => {
        window.location.assign('/member');
    })
    .catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        alert(errorMessage);
    });

My send sendToken() posts the idToken to the server:

function sendToken(idToken) {
console.log("Posting " + idToken);
var xhr = new XMLHttpRequest();
var params = `token=${idToken}`;
xhr.open('POST', "/login", true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
return new Promise(function(resolve, reject) {
   xhr.onreadystatechange = function() {//Call a function when the state changes.
        if (xhr.readyState == 4 && xhr.status == 200) {
            resolve();
        } else if (xhr.readyState == 4 && xhr.status != 200) {
            reject("Invalid http return status");
        }
    }
   return xhr.send(params);
});
}

And at the server, I'm returning a session cookie:

app.post('/login', (req, res) => {
if (req.body.token) {
   const idToken = req.body.token.toString();
  // Set session expiration to 1 day.
   const expiresIn = 60 * 60 * 24 * 1 * 1000;
   return firebase.auth().createSessionCookie(idToken, {expiresIn}).then((sessionCookie) => {
     const options = {maxAge: expiresIn, httpOnly: true, secure: true};
     res.cookie('session', sessionCookie, options);
     res.end(JSON.stringify({status: 'success'}));
  })
  .catch((error) => {
  res.status(401).send('UNAUTHORIZED REQUEST!');
 });
}
return res.status(400).send("MISSING TOKEN");
});

I've also set up a middleware to verify the session cookie before the server serves the member info:

function authVerification(req, res, next){
 const sessionCookie = req.cookies.session || '';
 // Verify the session cookie. In this case an additional check is added to 
 detect
 // if the user's Firebase session was revoked, user deleted/disabled, etc.
 return firebase.auth().verifySessionCookie(
 sessionCookie, true /** checkRevoked */).then((decodedClaims) => {
   console.log("decoded claims: " + decodedClaims);
   next();
   // serveContentForUser('/profile', req, res, decodedClaims);
 }).catch(error => {
   // Session cookie is unavailable or invalid. Force user to login.
   res.send(error);
 });
}

But, when I try to get a member's page after signing in:

app.get("/member", authVerification, (req, res) => {
  res.send("member page");
});

I keep getting error from authVerification:

code: "auth/argument-error", message: "Decoding Firebase session cookie failed. Make sure you passed the entire string JWT which represents a session cookie. See https://firebase.google.com/docs/auth/admin/manage-cookies for details on how to retrieve a session cookie."

Can anyone please point me in the right direction. Thank you in advance!


回答1:


Solution in the quickstart-nodejs repo.

enter link description here

You have to add cookie-parser and body-parser. Here is how I solved it with Firebase Cloud Functions:

const admin = require("firebase-admin");
const functions = require("firebase-functions");
const next = require("next");
const cors = require("cors");
const express = require("express");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev, conf: { distDir: "next" } });
const handle = app.getRequestHandler();

admin.initializeApp({
  credential: admin.credential.cert("Service account key"),
  databaseURL: "Path to database"
});

const server = express();
server.use(cors({ origin: true }));
server.use(bodyParser.json());
// Support URL-encoded bodies.
server.use(bodyParser.urlencoded({
  extended: true
}));
// Support cookie manipulation.
server.use(cookieParser());
// Attach CSRF token on each request.
server.use(attachCsrfToken('/', 'csrfToken', (Math.random()* 100000000000000000).toString()));


function attachCsrfToken(url, cookie, value) {
  return function(req, res, next) {
    if (req.url === url) {
      res.cookie(cookie, value);
    }
    next();
  }
}

server.post("/login", (req, res) => {
  if (req.body && req.body.idToken) {
    const idToken = `${req.body.idToken}`;
    const expiresIn = 60 * 60 * 24 * 5 * 1000;
    admin.auth().createSessionCookie(idToken, { expiresIn }).then((sessionCookie) => {
      const options = { maxAge: expiresIn, httpOnly: true, secure: true };
      res.cookie("session", sessionCookie, options);
      res.end(JSON.stringify({ sessionCookie }));
    }, error => {
      res.status(401).send(error);
    });
  } else {
    res.status(401).send("Token empty");
  }
});

server.post("/profile", (req, res) => {
  if (req.cookies && req.cookies.session) {
    const sessionCookie = `${req.cookies.session}`;
    admin.auth().verifySessionCookie(
      sessionCookie, true /** checkRevoked */).then((decodedClaims) => {
      res.end(JSON.stringify({ decodedClaims }));
    }).catch(error => {
      res.status(401).send(error);
    });
  } else {
    res.status(401).send("Session empty");
  }
});

exports.next = functions.https.onRequest((req, res) => {
  if (req.method === "POST") {
    if (!req.path) req.url = `/${request.url}`;
    return server(req, res);
  }

  return app.prepare().then(() => handle(req, res));
});

Nothing special on the client side. You can use isomorphic-unfetch, axios or jQuery.



来源:https://stackoverflow.com/questions/52774148/why-is-the-req-cookies-session-undefined-firebase-node-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!