簡體   English   中英

使用 cors 時無法訪問 socket.io 中的護照用戶

[英]Unable to access passport user in socket.io when using cors

我正在創建一個反應應用程序,我正在添加注冊用戶的功能。 一切都成功,但我無法訪問套接字中的 Passport User 屬性我使用了 socket.io 示例中給出的相同代碼

const session = require("express-session");
const passport = require("passport");

io.use(wrap(session({ secret: "cats" })));
io.use(wrap(passport.initialize()));
io.use(wrap(passport.session()));

io.use((socket, next) => {
  if (socket.request.user) {
    next();
  } else {
    next(new Error("unauthorized"))
  }
});

如果域相同,則此示例可以正常工作,但是當我使用 CORS 時,我無法訪問 session 中的護照屬性。 我的反應應用程序域是 localhost:3000 和套接字服務器域是 localhost:5000

假設您使用相同的協議和相同的但使用不同的端口,如果您使用 cors 標志設置客戶端和服務器,它應該仍然可以正常工作,例如

// server-side
const io = new Server(httpServer, {
  cors: {
    origin: "https://example.com",
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }
});

// client-side
import { io } from "socket.io-client";
const socket = io("https://api.example.com", {
  withCredentials: true,
  extraHeaders: {
    "my-custom-header": "abcd"
  }
});

上面的示例取自 socket.io 文檔: https://socket.io/docs/v4/handling-cors/

但是,只有當客戶端/服務器共享相同的頂級域和相同的協議時,上述配置才有效。 例如客戶端: https://example.com ,服務器: https://server.example.Z4D236D1502D10BEC550Z6

我花了一些時間弄清楚為什么:客戶端: http://127.0.0.1:3000不適用於服務器: https://127.0.0.1:8000注意協議差異

有了 cors 配置,如果我將http://127.0.0.1:8000用於服務器,它就可以正常工作。

PS:如果您需要使用不同的頂級域,請注意可能適用於您的瀏覽器的 SameSite 策略: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie /SameSite此策略可能會限制將您的 cookies 發送到服務器。

所以...如果不同的協議或域,您應該確保您的 session cookie 將 SameSite 標志設置為“無”,通過:

const session = require('express-session');
...
// Session setup
const sessionConfig = {
  secret: 'secret', // Session secret
  resave: false, //don't save session if unmodified
  saveUninitialized: false, // don't create session until something stored
  cookie: {
    sameSite: 'none',
    secure: true,
  }
}
const sessionMiddleware = session(sessionConfig);
app.use(sessionMiddleware);
...
io.use(wrap(sessionMiddleware));

如果您使用 https:// 協議,則需要sameSitesecure屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM