简体   繁体   English

Node.js 快速会话在 HTTP 上正常,session 未在 Z0E8433F9A404F1F3BA21Z01C 中恢复

[英]Node.js express-session ok on HTTP, session not recovered in HTTPS, localhost, self-signed certificate

I am running a node.js with working Passport.js "local", "facebook" and "google" authentication.我正在运行 node.js 并使用 Passport.js “本地”、“facebook”和“google”身份验证。 I use express-session with MongoDB as store, everything works like a charm: session is persisted upon successful authentication, cookie in the browser, sent by axios and session is recovered as I come back. I use express-session with MongoDB as store, everything works like a charm: session is persisted upon successful authentication, cookie in the browser, sent by axios and session is recovered as I come back.

If however I move to https, my session cannot be recovered.但是,如果我移动到 https,我的 session 将无法恢复。 I can login, see my session in the mongoDB, see my cookie in the browser, but the session is not pulled and nothing is in req.user.我可以登录,在 mongoDB 中看到我的 session,在浏览器中看到我的 cookie,但是 session 没有被拉取,requser.

My code looks pretty much "common" for what I can read on the web, cannot see anything obviously different of missing:对于我在 web 上可以阅读的内容,我的代码看起来非常“常见”,看不到任何明显不同的缺失:

const dotenv = require('dotenv');
const express = require('express');
const app = express();
const https = require('https');
var fs = require('fs');
const cors = require('cors');
const session = require("express-session");
const bodyParser = require("body-parser");
const passport = require('./passport/passport');

const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');
const ensureAuthenticated = require('./middlewares/auth/ensureAuthenticated');
const ensureAuthorized = require('./middlewares/auth/ensureAuthorized');

const connectMongoDb = require('./mongoDb/connectMongoDb');
const mongoose = require("mongoose");
const MongoStore = require('connect-mongo')(session);

dotenv.config();

connectMongoDb();

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

app.use(cors({
    origin: `${process.env.CLIENT_HOST_URI}:${process.env.CLIENT_PORT}`,
    credentials: true
}));

app.use(session({
    secret: process.env.SESSION_COOKIE_SECRET,
    resave: false,
    saveUninitialized: false,
    store: new MongoStore({ mongooseConnection: mongoose.connection }),
    cookie: { maxAge: 24 * 60 * 60 * 1000 }
}));

app.use(passport.initialize());

app.use(passport.session());

app.use('/api/auth', authRoutes);

app.use('/api/user', ensureAuthenticated, userRoutes);


https
    .createServer({
        key: fs.readFileSync('server.key'),
        cert: fs.readFileSync('server.cert')
    }, app)
    .listen(process.env.API_SERVER_PORT, () => {
        console.log(`Server has started on port ${process.env.API_SERVER_PORT} over HTTPS`);
    });

I suspect this might be linked to the self-signed certificate I am using.我怀疑这可能与我正在使用的自签名证书有关。 But... I cannot believe I should deploy and get a real certificate to get this work on my laptop in dev mode.但是......我不敢相信我应该部署并获得一个真正的证书,以便在我的笔记本电脑上以开发模式完成这项工作。

I also wonder if there is any log that could tell me what goes wrong.我也想知道是否有任何日志可以告诉我出了什么问题。

Thank you for you help, David谢谢你的帮助,大卫

I found what the issue was.我发现了问题所在。 In my case at least.至少在我的情况下。

I spotted this from chrome:我从 chrome 中发现了这一点:

在此处输入图像描述

This led me to add the following attribute in the cookie config object:这导致我在 cookie 配置 object 中添加以下属性:

sameSite: 'None',

Once this change implemented, I saw this other message in chrome:实施此更改后,我在 chrome 中看到了另一条消息:

在此处输入图像描述

This worked and the reason why it initially complained is probably because I was running my frontend/client from这行得通,它最初抱怨的原因可能是因为我正在运行我的前端/客户端

http://localhost:3000 http://localhost:3000

and my backend/api from和我的后端/ api来自

https://localhost:4000 https://localhost:4000

... so strictly put, different hosts. ...严格来说,不同的主机。

My cookie config then becomes:然后我的 cookie 配置变为:

cookie: {
        secure: true,
        sameSite: 'None',
        maxAge: 24 * 60 * 60 * 1000
    }

Hope this helps the community.希望这对社区有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM