socket.io-client how to set request header when ma

2020-02-17 09:04发布

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.

4条回答
狗以群分
2楼-- · 2020-02-17 09:23

As of version 2.0.0 / 2017-01-22 engine.io-client supports

[feature] Allow extraHeaders to be set for browser clients in XHR requests (#519)

However at this point the socket.io-client is not updated to support this functionality, so couple of days may make this saga end until that time use the following instructions: https://facundoolano.wordpress.com/2014/10/11/better-authentication-for-socket-io-no-query-strings/

查看更多
太酷不给撩
3楼-- · 2020-02-17 09:25

This information has been deprecated since socket.io 1.0

There are two methods of authorization: global or namespace (think route). The global method is set on the server with the io.set('authorization', function (handshakeData, callback) configuration call.

The handshakeData object contains the following information:

{
   headers: req.headers       // <Object> the headers of the request
 , time: (new Date) +''       // <String> date time of the connection
 , address: socket.address()  // <Object> remoteAddress and remotePort object
 , xdomain: !!headers.origin  // <Boolean> was it a cross domain request?
 , secure: socket.secure      // <Boolean> https connection
 , issued: +date              // <Number> EPOCH of when the handshake was created
 , url: request.url          // <String> the entrance path of the request
 , query: data.query          // <Object> the result of url.parse().query or a empty object
}

The above information and a deeper explanation is available on this documentation page.

查看更多
Fickle 薄情
4楼-- · 2020-02-17 09:26

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.

查看更多
我只想做你的唯一
5楼-- · 2020-02-17 09:38

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...

查看更多
登录 后发表回答