Reputation: 2412
I have encountered two possibilities and would prefer a solution that performs the check prior to fully establishing the websocket.
var express = require("express.io");
var app = express().http().io();
app.use(express.json());
app.use(express.cookieParser());
app.use(express.session({secret: process.env.COOKIESECRET}));
Option 1: How to get the Express session object?
UPDATE: This might not be workable as Express.io registers its own "authorize" function which makes the Express session available to Socket.io.
app.io.configure(function() {
app.io.set("authorize", function(handshake, authorize) {
// Cookie is available...?
//handshake.headers.cookie
});
});
Option 2: Easy to get Express session, but connection already established.
app.io.route("test", function(req) {
if(!req.session.IsAuthorized) {
req.io.disconnect();
}
});
Upvotes: 0
Views: 161
Reputation: 3973
You can pass in a reference to your sessionstore so it is available when you configure your socket server:
var sessionStore = new express.session.MemoryStore();
app.use(express.session({secret: process.env.COOKIESECRET, store: sessionStore}));
I think you should be able to get the rest from there by matching the handshake.headers
object to stuff in your session store. Note that the default store is held in memory, which is not great for production purposes (but fine for now I guess). The above relates to your option 1 method.
Upvotes: 1