验证用户的socket.io/nodejs [英] Authenticate user for socket.io/nodejs

查看:114
本文介绍了验证用户的socket.io/nodejs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php登录名,用户输入了用户名/密码,它根据登录信息检查mysql db.如果通过身份验证,则会通过php创建会话,用户现在可以使用php会话访问系统.我的问题是,一旦他们通过php/session进行身份验证,将如何授权用户查看他们是否具有正确的登录权限以使用socket.io访问Node.js服务器?我不希望该人员可以访问nodejs/socket.io函数/服务器,除非他们已通过php登录进行了身份验证.

I have a php login, the user puts in a username/password, it checks the mysql db against the login information. If authenticated a session is created via php and the user can now access the system with the php session. My question is once they authenticate via php/session what would be the process to authorize the user to see if they have the right login permissions to access a nodejs server with socket.io? I dont want the person to have access to the nodejs/socket.io function/server unless they have authenticated via the php login.

推荐答案

更新

要求:

  1. 首先运行Redis.
  2. 接下来启动socket.io.
  3. 最后上传/托管PHP(在归档文件中具有依赖性).

Socket.io

var express = require('express'),
        app         = express.createServer(),
        sio         = require('socket.io'),
        redis   = require("redis"),
    client  = redis.createClient(),
        io          = null;

/**
 *  Used to parse cookie
 */
function parse_cookies(_cookies) {
    var cookies = {};

    _cookies && _cookies.split(';').forEach(function( cookie ) {
        var parts = cookie.split('=');
        cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
    });

    return cookies;
}

app.listen(3000, "localhost");
io = sio.listen(app);

io.of('/private').authorization(function (handshakeData, callback) {
        var cookies = parse_cookies(handshakeData.headers.cookie);

        client.get(cookies.PHPSESSID, function (err, reply) {
                handshakeData.identity = reply;
                callback(false, reply !== null);
        });
}).on('connection' , function (socket) {
        socket.emit('identity', socket.handshake.identity);
});

PHP

具有Openid身份验证的

php => http://dl.dropbox. com/u/314941/6503745/php.tar.gz

PHP

php with openid authentication => http://dl.dropbox.com/u/314941/6503745/php.tar.gz

登录后,您必须重新加载client.php进行身份验证

After login you have to reload client.php to authenticate

p.s:我真的不喜欢创建另一个可能很不安全的密码的概念.我建议您看看 openID (通过Google ),

p.s: I really don't like the concept of creating even another password which is probably is going to be unsafe. I would advice you to have a look at openID(via Google for example), Facebook Connect(just name a few options).

我的问题是,一旦他们通过身份验证 通过PHP/会话将是什么 验证用户身份的过程 查看他们是否具有正确的登录名 访问Node.js服务器的权限 用socket.io?我不要那个人 有权访问nodejs/socket.io 功能/服务器,除非他们有 通过php登录进行身份验证.

My question is once they authenticate via php/session what would be the process to authenticate the user to see if they have the right login permissions to access a nodejs server with socket.io? I dont want the person to have access to the nodejs/socket.io function/server unless they have authenticated via the php login.

将唯一的 session_id 添加到允许ID的列表/集中这样socket.io可以授权(搜索授权功能)的连接.我将让PHP使用 redis 与node.js进行通信,因为那样会很快/AWESOME :).现在,我正在从redis-cli

Add the unique session_id to a list/set of allowed ids so that socket.io can authorize(search for authorization function) that connection. I would let PHP communicate with node.js using redis because that is going to be lightning fast/AWESOME :). Right now I am faking the PHP communication from redis-cli

下载Redis =>现在可以从以下版本下载稳定版本:

Download redis => Right now the stable version can be downloaded from: http://redis.googlecode.com/files/redis-2.2.11.tar.gz

alfred@alfred-laptop:~$ mkdir ~/6502031
alfred@alfred-laptop:~/6502031$ cd ~/6502031/
alfred@alfred-laptop:~/6502031$ tar xfz redis-2.2.11.tar.gz 
alfred@alfred-laptop:~/6502031$ cd redis-2.2.11/src
alfred@alfred-laptop:~/6502031/redis-2.2.11/src$ make # wait couple of seconds

启动Redis服务器

alfred@alfred-laptop:~/6502031/redis-2.2.11/src$ ./redis-server 

Socket.io

npm依赖项

如果尚未安装npm,则首先访问 http://npmjs.org

Socket.io

npm dependencies

If npm is not already installed , then first visit http://npmjs.org

npm install express
npm install socket.io
npm install redis

列出我已安装的依赖项,并且根据npm ls

listing the dependencies I have installed and which you should also probably install in case of incompatibility according to npm ls

alfred@alfred-laptop:~/node/socketio-demo$ npm ls
/home/alfred/node/socketio-demo
├─┬ express@2.3.12 
│ ├── connect@1.5.1 
│ ├── mime@1.2.2 
│ └── qs@0.1.0 
├── hiredis@0.1.12 
├── redis@0.6.0 
└─┬ socket.io@0.7.2 
  ├── policyfile@0.0.3 
  └── socket.io-client@0.7.2 

代码

server.js

Code

server.js

var express = require('express'),
        app         = express.createServer(),
        sio         = require('socket.io'),
        redis   = require("redis"),
    client  = redis.createClient(),
        io          = null;

/**
 *  Used to parse cookie
 */
function parse_cookies(_cookies) {
    var cookies = {};

    _cookies && _cookies.split(';').forEach(function( cookie ) {
        var parts = cookie.split('=');
        cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
    });

    return cookies;
}

app.listen(3000, "localhost");
io = sio.listen(app);

io.configure(function () {
  function auth (data, fn) {
    var cookies = parse_cookies(data.headers.cookie);
    console.log('PHPSESSID: ' + cookies.PHPSESSID);

        client.sismember('sid', cookies.PHPSESSID, function (err , reply) {
            fn(null, reply);    
        });
  };

  io.set('authorization', auth);
});

io.sockets.on('connection', function (socket) {
  socket.emit('access', 'granted');
});

要运行服务器,只需运行node server.js

To run server just run node server.js

<?php

session_start();

echo "<h1>SID: " . session_id() . "</h1>";
?>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script src="http://localhost:3000/socket.io/socket.io.js"></script>
</head>
<body>
    <p id="text">access denied</p>
    <script>
        var socket = io.connect('http://localhost:3000/');
        socket.on('access', function (data) {
            $("#text").html(data);
        });
    </script>
</body>

测试身份验证

当您从Web浏览器加载网页(PHP文件)时,显示消息access denied,但是当您在浏览器中添加session_id并将其添加到Redis服务器时,也会显示消息access granted.当然,通常您不会进行任何复制粘贴,而只是让PHP直接与Redis通信..但是对于此演示,您将在允许访问之后将SID ramom807vt1io3sqvmc8m4via1放入redis.

Test authentication

When you load the webpage(PHP-file) from your web-browser the message access denied is shown, but when you add the session_id also shown in browser to redis server the message access granted will be shown. Of course normally you would not be doing any copy pasting but just let PHP communicate with Redis directly.. But for this demo you will put SID ramom807vt1io3sqvmc8m4via1 into redis after which access has been granted.

alfred@alfred-laptop:~/database/redis-2.2.0-rc4/src$ ./redis-cli 
redis> sadd sid ramom807vt1io3sqvmc8m4via1
(integer) 1
redis> 

这篇关于验证用户的socket.io/nodejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆