oskosk / express-socket.io-session

Share a cookie-based express-session middleware with socket.io
https://www.npmjs.com/package/express-socket.io-session
MIT License
135 stars 14 forks source link

Can't access express sessions in Websocket? #77

Closed Zaniyar closed 3 years ago

Zaniyar commented 3 years ago

Earlier I set session.user on login and log it here:

app.get('/', function (req, res) {
    res.send(JSON.stringify(req.session));
});

{"cookie":{"originalMaxAge":null,"expires":null,"secure":null,"httpOnly":true,"domain":null,"path":"/","sameSite":null},"user":{"_id":"61d1","firstname":"Billy","lastname":"Bob","email":"test@test.com","__v":0,"isLoggedIn":true}}

And now I would like to see the same session.user in my socket, but I got only the session.cookie:

 const data = socket.handshake || socket.request;
console.log("Session",(data as any).session)

Session { [1] cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true } [1] }

What am I missing here?

const expressSession =  require("express-session");
const sessionData = {
    name: COOKIE_NAME,
    secret:COOKIE_SECRET,
    resave: false,
    saveUninitialized: false,
    store: store
}
const session = expressSession(sessionData);
const socketSession = require("express-socket.io-session");
const sharedsession = socketSession(session, {
    autoSave:true
})
app.use(session);
app.set('trust proxy', 1)
app.use(cors({
    origin:['https://localhost:3000', 'http://localhost:3001', 'http://localhost:3000', 'ws://localhost:3000', 'wss://localhost:3000'],
    methods:['GET','POST'],
    credentials: true // enable set cookie
}));

//... 

io.on("connection", (socket: Socket) => {
    socket.on("message",userdata=>{
        var data = socket.handshake || socket.request;
        console.log("Session",(data as any).session)
    })

My backend and my client are on different servers running on https.

Zaniyar commented 3 years ago

Add withCredentials:true to client side for allowing exchange of sessions between different ports.

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