john-jones
john-jones

Reputation: 7780

Connect client socket to a cookie

I am making a chat program.

I am using an Nginx server and NodeJS.

I have setup a websocket via ssl and that works fine.

I have decided to use cookies for authentication.

There are two functions which are crucial:

mconnection.prototype.make_server_https=function(){
console.log('Make server https');

var cthis=this;
var server_https=modules.https.createServer({
    key: this.ssl_key,
    cert:this.ssl_cert,
    ca:this.ssl_ca
    },(request,response)=>{
        console.log('### CreateServer ###');

        console.log('CreateServer, Request:');
        console.log(request);

        console.log('CreateServer, Response:');
        console.log(response);

        console.log('######');

and

mconnection.prototype.make_server_websocket=function(){
var server_websocket=new modules.ws.Server({server:this.server_https});

var cookie = require("cookie");

var cthis=this;
//whenever a new client connects with the server.
server_websocket.on('connection', function(client_socket, request){
    console.log('### On Connection ###');

    console.log('OnConnection, Client Socket:');
    console.log(client_socket);
    console.log('OnConnection, Request:');
    console.log(request);

    console.log('######');

If I do state the port number in the client url,
function make_server_https gets run and inside there i can access the cookie and set it via the response object.

but in the original url,
function make_server_websocket gets run, and there i have access to the client_socket on the server. But there it seems i dont have access to the cookies.

I need to client_websocket to start the connection with this given client. And I need to tie it somehow with the cookies login information.

But i never have both at the same time so i dont get how i could connect them to make the login happen.

I am probably misunderstanding something, any help in the right direction would really be appreciated.

Upvotes: 3

Views: 163

Answers (2)

john-jones
john-jones

Reputation: 7780

i got it. its an event called on headers, not on connection. and there i can just push onto the headers.

Upvotes: 0

Chandan
Chandan

Reputation: 11807

you have to serve you index page from node server using GET then when the request reaches backend you will have response object which can then be used to SET-COOKIE if not set from backend.

And after GET request is complete COOKIE will be added in browser, when next request is made for websocket connection COOKIE will be added to the request in REQUEST HEADERS by the browser which will be available in backend through request object.

And if you decide to use it in login system then you can SET-COOKIE on successfull login.

Upvotes: 1

Related Questions