如何在javascript中通过websocket验证每个请求?

时间:2016-07-28 07:42:01

标签: javascript authentication websocket

设置了javascript服务器并为其配置了websocket。在客户端使用react和npm。所以,我想使用rest API验证对web套接字的每个请求。身份验证将是第一步,然后在身份验证完成后使用相同的Web套接字进行所有信息传输。是否可以将身份验证标头传递给websocket?有人可以告诉你如何继续吗?

以下是我正在尝试的服务器和客户端的代码。

服务器代码 -

#!/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 for ' + request.url);
        response.writeHead(404);
        response.end();
});

server.listen(5005, function() {
    console.log((new Date()) + ' Server is 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 from 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 some 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.');
    });
});

客户代码 -

import React from '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)
                )               
            ))
        }
     });

1 个答案:

答案 0 :(得分:0)

如果您想加密发送的数据,也许可以使用jwt或jwe。您可以使用许多库和完整文档:https://jwt.io/

所以你可以通过邮件或标题发送所有信息,并在每个HTTP或websocket调用中检查它