codebot
codebot

Reputation: 697

How to authenticate in websockets, using node and express-ws

I am using node 10.16.0, express 4.0.0 and express-ws module . In my normal routes that I use REST, I am using a middleware to check if there is a header with a token and validate that token.

How do I do the same thing for websockets?

I cannot just add a header to ws and pass it to the node route, even though express-ws allows to easily create express-style routes.

Currently, I am using an http server to create a ws server and then seperating different express routes

//app.js
const app = express();

const wsHttpServer = http.createServer();
wsHttpServer.listen(5001);
const expressWs = require('express-ws')(app , wsHttpServer);

app.use(cors());

app.use(express.static(path.join(__dirname,'public'))); 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.json());
app.use(express.urlencoded({extended:false})); 

app.use('/ws', require('./routes/wsroute')); 
app.use('/login', require('./routes/login'));


const port = process.env.PORT || 4000;
app.listen(port, ()=>{
    console.log('server runs on port ', port);
});

exports.expressWs = expressWs;

and then for the ws routes, according to the express-ws examples

//wsroute.js
router.ws('/users/:name/:date/:time', /*token.validate(),*/  (ws, req) => { 
    const name = req.params.name;  
    const date = req.params.date;
    const time = req.params.time;  
    console.log('ws route');
    console.log('ws route',name, date, time);    
});

If I un-comment the token.validate() part, this will never control log because there is no header with a token.

How can I add a header to ws, like I do in REST, so it can be checked automatically? I guess that if the ws server is initialized using an http server and the ws route also includes a req, I can somehow do it?

Or is there another method?

Thanks

Upvotes: 4

Views: 20444

Answers (1)

Claudio Viola
Claudio Viola

Reputation: 319

duplicate of Websockets token authentication using middleware and express in node.js . Follow the example there.

Listen to the wsHttpServer.on('upgrade') event and perform authentication of your choice there. If you wish you can also append a header on the upgrade eventbefore it reaches your route.

Upvotes: 3

Related Questions