/* | |
* Little example of how to use ```socket-io.client``` and ```request``` from node.js | |
* to authenticate thru http, and send the cookies during the socket.io handshake. | |
*/ | |
var io = require('socket.io-client'); | |
var request = require('request'); | |
/* | |
* This is the jar (like a cookie container) we will use always | |
*/ | |
var j = request.jar(); | |
/* | |
* First I will patch the xmlhttprequest library that socket.io-client uses | |
* internally to simulate XMLHttpRequest in the browser world. | |
*/ | |
var originalRequest = require('socket.io-client/node_modules/xmlhttprequest').XMLHttpRequest; | |
require('socket.io-client/node_modules/xmlhttprequest').XMLHttpRequest = function(){ | |
originalRequest.apply(this, arguments); | |
this.setDisableHeaderCheck(true); | |
var stdOpen = this.open; | |
/* | |
* I will patch now open in order to set my cookie from the jar request. | |
*/ | |
this.open = function() { | |
stdOpen.apply(this, arguments); | |
this.setRequestHeader('cookie', j.getCookieString('http://localhost:9000')); | |
}; | |
}; | |
/* | |
* Authenticate first, doing a post to some url | |
* with the credentials for instance | |
*/ | |
request.post({ | |
jar: j, | |
url: 'http://localhost:9000/login', | |
form: {username: 'jose', password: 'Pa123'} | |
}, function (err, resp, body){ | |
/* | |
* now we can connect.. and socket.io will send the cookies! | |
*/ | |
var socket = io.connect('http://localhost:9000'); | |
socket.on('connect', function(){ | |
console.log('connected! handshakedddddddddddd') | |
done(); | |
})); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Sending cookies across origins is disabled in browsers (I believe at a lower level than any patching could allow).
The browser's console shows the cookie being sent (when using the same origin as a destination).