简体   繁体   中英

What are the possible ways to authorize a websocket connection request in Express.io?

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();
  }
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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