使用http-auth进行身份验证时,从socket.io获取用户对象

时间:2016-01-18 15:08:19

标签: node.js sockets express http-authentication

我想在建立socket.io连接时获取用户对象。这样我就可以记录用户的操作。

使用express.js我可以得到这样的用户:

app.get('/', function(req, res) {
    // req.user
})

如何从socket.io连接中获取用户?我的socket.io实现使用与express.js相同的http服务器。

以下是代码:

var auth = require('http-auth')
var basic = auth.basic({
    file: __dirname + '/.htpasswd'
})

var express = require('express')
var app = express()
var http = require('http')
var server = http.createServer(basic, app)

var io = require('socket.io')(server)

io.on('connection', function(socket) {
    // how to get user?
})

谢谢:)

2 个答案:

答案 0 :(得分:1)

var request = require('request');
request('/users', function (error, response, body) {
  if (!error && response.statusCode == 200) {

     var users = body.users;
     io.on('connection', function(socket) {
           // IO EMIT USERS
     }
  }
})

或......

io.on('connection', function(socket) {

  var request = require('request');
  request('/users', function (error, response, body) {
  if (!error && response.statusCode == 200) {

     var users = body.users;
           // IO EMIT USERS
     }
  })
}

答案 1 :(得分:0)

http-auth不会自动验证socket.io通信。您必须自己验证socket.io。

这样做,您可以重用isAuthenticated(req, callback)中的内部函数http-auth并使用io.use()将其实现为socket.io中间件:

io.use((socket, next) => {
    // the first argument should contain the request object
    // as the http-auth module only checks for a headers object inside the request object,
    // we're in luck because socket.handshake has the headers object as well
    //
    // see code on
    // https://github.com/http-auth/http-auth/blob/c7e078ad1d7d0def72ed198860d6352f262b90e6/src/auth/base.js#L82
    basic.isAuthenticated(socket.handshake, result => {
        if (result instanceof Error) {
            next(result);
        } else if (!result.pass) {
            next(new Error('Authentication error'));
        } else {
            socket.user = result.user; // make sure you can access the user later
            next();
        }
    });
});

然后您可以通过以下方式访问用户:

io.on('connection', function(socket) {
    console.log(socket.user);
});