-
-
Save jfromaniello/4087861 to your computer and use it in GitHub Desktop.
/* | |
* 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('xmlhttprequest').XMLHttpRequest; | |
require('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); | |
var header = j.get({ url: 'http://localhost:9000' }) | |
.map(function (c) { | |
return c.name + "=" + c.value; | |
}).join("; "); | |
this.setRequestHeader('cookie', header); | |
}; | |
}; | |
/* | |
* 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(); | |
})); | |
}); |
I fixed the cookie issue in socket-io-client 1.3.6 by overriding the http.ClientRequest constructor.
var ClientRequestOrig = require('http').ClientRequest;
// Override the ClientRequest constructor to set your cookie.
http.ClientRequest = function(options, cb) {
// Set your cookie
options.headers.Cookie = 'mycookie=mycookievalue';
return new ClientRequestOrig(options, cb);
};
This solution does not work when you have multiple socket.io clients in the same node instance. If the clients auth as different users, overriding the cookie in the common xmlhttprequest
makes all the clients appear to be the same
For those that are still ending up here, using a newer version of SocketIO client may be better for you. This pull requests outlines how you can set cookies using the library directly: rakeshok/socket.io-client-cookie#9
Posting the code from the pull request here as well:
const io = require('socket.io-client');
const cookie = 'connect.sid=xyz';
const socket = io(url, { path, extraHeaders: { cookie } `});
Sending cookies across origins is disabled in browsers (I believe at a lower level than any patching could allow).
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cookies</title>
<script>
window.addEventListener('load', function(event) {
let exist = document.getElementById("exist");
exist.textContent = document.cookie;
let mycookie = "mysession=abc123";
let elem = document.getElementById("cook");
elem.textContent = mycookie;
document.cookie = mycookie;
// let url = "https://www.google.ca/";
let url = "http://localhost:30080/";
let urlelem = document.getElementById("url");
urlelem.textContent = url;
let respelem = document.getElementById("resp");
let req = new Request(url, { credentials: "same-origin" });
fetch(req).then(function(resp) {
return resp.text();
}).then(function(text) {
respelem.textContent = text;
});
});
</script>
</head>
<body>
<p>
Existing document cookies <code id="exist"></code>.
<p>
Sending a cookie <code id="cook"></code> to URL <code id="url"></code>.
<p>
Response text: <code id="resp"></code>.
</body>
</html>
Existing document cookies .
Sending a cookie mysession=abc123 to URL http://localhost:30080/.
Response text: <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> [...] </body> </html> .
The browser's console shows the cookie being sent (when using the same origin as a destination).
GET / HTTP/1.1
Host: localhost:30080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:84.0) Gecko/20100101 Firefox/84.0
Accept: */*
Accept-Language: en-CA,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://localhost:30080/f.html
DNT: 1
Connection: keep-alive
Cookie: mysession=abc123
Complete example
For anyone that look for a complete example here is:
First create a file: client-code.js
Now create new file called:newXhr.js thank you @chrahunt
The dependencies package.json
In Windows
Now run this in the promt:
set DEBUG=* & node client-code.js
Unix base
Now run this in the shell/terminal:
DEBUG=* node client-code.js
Tested with socket.io v1.1.0
Cheers!