【问题标题】:Can't get session to save/persist on deployed express server无法让会话保存/保留在已部署的快速服务器上
【发布时间】:2020-12-28 09:56:42
【问题描述】:

我的登录尝试没有保存到生产中的表达会话。我将会话保存在 Mongo Store 中,并且会话在 MongoAtlas 中以修改后的方式出现(它们应该以它们的方式出现),但由于某种原因,服务器没有识别出现有会话并且正在创建一个新会话。当我启用快速会话调试时,它会在对服务器的每个请求上记录express-session no SID sent, generating session。这让我认为会话 ID 没有随请求一起发送,并且问题与我的客户端和服务器位于不同的域有关(我的客户端地址是 https://example.com,而我的服务器位于 https://app.example.com。我最初在https://www.example.com 上拥有我的客户,但改变它认为 cookie 被误认为是第 3 方 cookie(也许它仍然是)。

我的客户端托管在 Firebase Hosting 上,我的 Express 服务器托管在 Google Cloud Run 上

我的快速会话设置

app.set('trust proxy', true)
app.use(session({
   secret: 'myappisasecret', 
   resave: false,
   saveUninitialized: false,
   secure: true,
   store: new MongoStore({mongooseConnection: mongoose.connection}),
   cookie: {
       maxAge: 1000 * 60 * 60 * 24 * 7, // 1 week
       sameSite: 'lax',
       secure: true,
       domain: 'mysite.com'
   },
   proxy: true // I think this makes the trust proxy be useless 
}))

下面是我的 coors 服务器的东西。这段代码位于上面的代码之上,但我认为它不会导致任何问题,但认为包含它可能很重要。

let whitelist = ['https://app.example.com', 'https://www.example.com', 'https://example.web.app', 'https://example.com']
let corsOptions = {
   origin: (origin, callback) => {
       if (whitelist.indexOf(origin) !== -1 || origin === undefined) {
           callback(null, true)
       } else {
           console.log('Request Origin blocked: ', origin)
           callback(new Error('Request blocked by CORS'))
       }
   },
   credentials: true
}
 
 
app.use(cookieParser('myappisasecret'))
app.use(cors(corsOptions))

由于服务器没有收到会话 ID,我认为可能是我的客户端没有发送会话 ID,因此我在客户端请求代码中添加了 credentials: 'include'

const reqHeaders = {
            headers: {
                "Content-Type": "application/json"
            },
            credentials: 'include' as any,
            method: "GET"
        }
fetch('https://app.example.com/u/loggedIn', reqHeaders)
        .then(res => etc...

当此请求获得提交的表达式会话调试日志时: express-session saving z3ndMizKoxivXR0N9LBZYkPhDG65uvF2 然后 express-session split response

这让我觉得当它试图将我的用户数据保存到会话时,它会同时被初始会话数据覆盖。我设置了resave: false。但即便如此,每次发送到服务器的请求时,我仍然会收到express-session no SID sent

【问题讨论】:

    标签: node.js express firebase-hosting express-session google-cloud-run


    【解决方案1】:

    显然,当使用 Firebase 和 Cloud Run 托管时,由于 Google 的 CDN 缓存行为,cookie 标头会被剥离。

    以下是描述该内容的文档:

    https://firebase.google.com/docs/hosting/manage-cache#using_cookies

    我现在不知道如何实现会话。 F

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 2020-10-20
      • 2021-02-25
      • 2017-09-18
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多