authentication - How to authenticate every request over a websocket in javascript? -


have setup javascript server , configured websocket it. on client side using react , npm. so, want authenticate every request web socket using rest api. authentication first step , information transfer happening using same web socket after authentication done. possible pass headers authentication websocket ? can please tell how proceed ?

below code server , client experimenting with.

server code -

#!/usr/bin/env node var websocketserver = require('websocket').server; var http = require('http');  var server = http.createserver(function(request, response) {         console.log((new date()) + ' received request ' + request.url);         response.writehead(404);         response.end(); });  server.listen(5005, function() {     console.log((new date()) + ' server listening on port 5005'); });   wsserver = new websocketserver({     httpserver: server,     autoacceptconnections: false });  function originisallowed(origin) {   return true; }  wsserver.on('request', function(request) {     if (!originisallowed(request.origin)) {         request.reject();           console.log((new date()) + ' connection origin ' + request.origin + ' rejected.');     return;     }      console.log(" ################ authorization ##################");        var auth = request.headers['authorization'];          if(!auth) {                      response.statuscode = 401;                 response.setheader('www-authenticate', 'basic realm="secure area"');         console.log(" authorization failed !!! ");                 response.end('<html><body>need creds son</body></html>');         }     else if(auth) {                  var tmp = auth.split(' ');                 var buf = new buffer(tmp[1], 'base64');                  var plain_auth = buf.tostring();                          console.log("decoded authorization :", plain_auth);                  var creds = plain_auth.split(':');                  var username = creds[0];                 var password = creds[1];                  if((username == 'hack') && (password == 'thegibson')) {                        console.log(" login successful !!!");                 }                 else {             console.log("login failed !!");                 }         }         var connection = request.accept('echo-protocol', request.origin);      console.log((new date()) + ' connection accepted.');     connection.on('message', function(message) {        //send message      });     connection.on('close', function(reasoncode, description) {     console.log((new date()) + ' peer ' + connection.remoteaddress + ' disconnected.');     }); }); 

client code -

import react 'react' var client = null; export default react.createclass({   getinitialstate: function() {      return { val : [],                   username : 'hacker',           password : 'thegibson' };   },     componentwillmount: function() {     //client = new websocket('ws://localhost:8000/','echo-protocol');      client = new websocket('ws://'+this.state.username+':'+this.state.password+'@localhost:5005/','echo-protocol');         client.onerror = function() {              console.log('connection error');            };          client.onopen = function() {             function senddata(){                         var details=[{"name" : "ravi", "age" : 15, "occupation": "student" }];                               if (client.readystate === client.open) {                                     client.send(details.tostring());                     console.log(details);                        settimeout(senddata,2000);                   }                 }             senddata();              };          client.onmessage = function(e) {             this.setstate({                     val: e.data             });             }.bind(this);      },      componentwillunmount: function(){         client.close();     },      render: function() {             return (react.createelement("div",null,                     react.createelement("ul",null,                          react.createelement("li",null,this.state.val.name," ( ", this.state.val.age,"  ) -  ","  occupation  :", this.state.val.occupation)                 )                            ))         }      }); 

maybe can use jwt or jwe if want encrypt data send. there many libraries can use , full documentation here: https://jwt.io/

so cand send via post or header information , check in every http or websocket call


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -