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

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

问题描述

我有一个 php 登录名,用户输入用户名/密码,它根据登录信息检查 mysql 数据库.如果通过身份验证,会话是通过 php 创建的,用户现在可以使用 php 会话访问系统.我的问题是,一旦他们通过 php/session 进行身份验证,授权用户查看他们是否具有使用 socket.io 访问 nodejs 服务器的正确登录权限的过程是什么?我不希望此人访问 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

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

After login you have to reload client.php to authenticate

ps:我真的不喜欢创建另一个可能不安全的密码的概念.我建议您查看 openID(通过 Google 例如),Facebook Connect(仅列举几个选项).

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/session 会是什么对用户进行身份验证的过程看看他们是否有正确的登录访问 nodejs 服务器的权限用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 通信,因为这将是闪电般的快速/真棒:).现在我正在伪造来自 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 => 目前稳定版可以从:http://redis.googlecode.com/files/redis-2.2.11.tar.gz

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

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

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>

测试认证

当您从网络浏览器加载网页(PHP 文件)时,会显示消息 access denied,但是当您添加浏览器中也显示的 session_id 时redis 服务器将显示消息 access allowed .当然,通常您不会进行任何复制粘贴,而是让 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天全站免登陆