如何在javascript中通过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)
                )               
            ))
        }
     });

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

因此,您可以通过post或header发送所有信息,并在每次HTTP或websocket调用

中进行检查

相关内容

  • 没有找到相关文章

最新更新