使用socket.io进行用户身份验证 [英] user authentication using socket.io
问题描述
我已将此教程改成红色: http://howtonode.org/socket-io-auth . 它显示了如何使用express和socket.io对用户进行身份验证. 但是,有没有一种方法可以只使用socket.io来认证用户,而无需进行表达?
I've red this tutorial: http://howtonode.org/socket-io-auth. It shows how to authenticate users using express and socket.io. But is there a way to authenticate users using only socket.io without the need for express?
对于会话处理,我使用RedisStore( https://github.com/LearnBoost/Socket. IO/wiki/Configuring-Socket.IO ). 剩下的是一个用于创建身份验证Cookie的模块. 有谁知道我可以用来创建身份验证Cookie的socket.io实现,就像您可以使用会话处理一样?
For session handling I use RedisStore (https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO). Whats left is a module to create authentication cookies. Does anyone know of a socket.io implementation I can use to create an authentication cookie like you can do with session handling?
推荐答案
我知道这有点陈旧,但对于将来的读者来说,除了解析cookie和从存储中检索会话的方法(例如passport.socketio ),您也可以考虑使用基于令牌的方法.
I know this is bit old, but for future readers in addition to the approach of parsing cookie and retrieving the session from the storage (eg. passport.socketio ) you might also consider a token based approach.
在此示例中,我使用了非常标准的JSON Web令牌.您必须向客户端页面提供令牌,在此示例中,假设返回JWT的身份验证端点:
In this example I use JSON Web Tokens which are pretty standard. You have to give to the client page the token, in this example imagine an authentication endpoint that returns JWT:
var jwt = require('jsonwebtoken');
// other requires
app.post('/login', function (req, res) {
// TODO: validate the actual user user
var profile = {
first_name: 'John',
last_name: 'Doe',
email: 'john@doe.com',
id: 123
};
// we are sending the profile in the token
var token = jwt.sign(profile, jwtSecret, { expiresInMinutes: 60*5 });
res.json({token: token});
});
现在,您的socket.io服务器可以配置如下:
Now, your socket.io server can be configured as follows:
var socketioJwt = require('socketio-jwt');
var sio = socketIo.listen(server);
sio.set('authorization', socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));
sio.sockets
.on('connection', function (socket) {
console.log(socket.handshake.decoded_token.email, 'has joined');
//socket.on('event');
});
socket.io-jwt中间件需要查询字符串中的令牌,因此从客户端只需要在连接时将其附加:
The socket.io-jwt middleware expects the token in a query string, so from the client you only have to attach it when connecting:
var socket = io.connect('', {
query: 'token=' + token
});
我在此处上对此方法和cookie进行了更详细的说明.
I wrote a more detailed explanation about this method and cookies here.
这篇关于使用socket.io进行用户身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!