Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io-client how to set request header when making connection

I'm trying to set a http header when socket.io client makes the connection request. Is there a way to do this?

Here is what i'm doing:

// server side var io = socketio(server);  io.use(function (socket, next) {   // authorize using authorization header in socket.request.headers });  // client side var socket = io();  // i'm trying to set an authorization header in this http reqeust 

Any ideas? Thanks.

like image 865
Ziyu Avatar asked May 01 '14 10:05

Ziyu


People also ask

Can I use socket IO client to connect to a standard WebSocket?

Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.

How do you fix Socket.IO Cors?

The error is simple to fix. Add cors and the origin that can communicate with the server, and that's all! const io = require('socket.io')(server, {cors: {origin: "*"}}); In the code above, I added a wildcard as my origin because I would like any origin to access it.

How do I know if socket IO client is connected?

You can check the socket. connected property: var socket = io. connect(); console.

How do I connect to a Socket.IO server?

listen(port); // Create a Socket.IO instance, passing it our server var socket = io. listen(server); // Add a connect listener socket. on('connection', function(client){ console. log('Connection to client established'); // Success!


2 Answers

You can use extraHeaders option, if you are using socket.io-client >= 1.4.

For example:

var socket = io("http://localhost", {   extraHeaders: {     Authorization: "Bearer authorization_token_here"   } }); 

engine.io-client, which is a backend of socket.io-client, introduced extraHeaders support on 2015-11-28.

like image 79
ymyzk Avatar answered Sep 18 '22 09:09

ymyzk


It seems like the client doesn't support setting headers, as not all transports allow for the setting of headers.

This post by facundoolano details a workaround to authentication that doesn't require placing the auth token in the query string.

His workaround module can be found at https://github.com/invisiblejs/socketio-auth.

Makes me wonder why on server-side, socket.io allows for the request headers to be accessed...

like image 26
bakavic Avatar answered Sep 18 '22 09:09

bakavic