socket.io身份验证
-
15-10-2019 - |
题
我正在尝试在node.js中使用socket.io,并试图允许服务器为每个socket.io端客户提供身份。由于套接字代码不在HTTP服务器代码的范围之外,因此它不容易访问发送的请求信息,因此我假设在连接期间需要发送它。什么是最好的方法
1)将信息获取有关谁通过socket.io连接的信息
2)验证他们说的是谁(我目前正在使用Express,如果这使事情变得更容易)
解决方案
使用Connect-Redis,并将REDIS作为所有身份验证用户的会话商店。确保身份验证您将密钥(通常是重新定义)发送给客户端。将客户端存储在cookie中。
在套接字连接(或稍后随时)上,从cookie获取此键,然后将其发送回服务器。使用此密钥在REDIS中获取会话信息。 (获取钥匙)
例如:
服务器端(Redis作为会话商店):
req.session.regenerate...
res.send({rediskey: req.sessionID});
客户端:
//store the key in a cookie
SetCookie('rediskey', <%= rediskey %>); //http://msdn.microsoft.com/en-us/library/ms533693(v=vs.85).aspx
//then when socket is connected, fetch the rediskey from the document.cookie and send it back to server
var socket = new io.Socket();
socket.on('connect', function() {
var rediskey = GetCookie('rediskey'); //http://msdn.microsoft.com/en-us/library/ms533693(v=vs.85).aspx
socket.send({rediskey: rediskey});
});
服务器端:
//in io.on('connection')
io.on('connection', function(client) {
client.on('message', function(message) {
if(message.rediskey) {
//fetch session info from redis
redisclient.get(message.rediskey, function(e, c) {
client.user_logged_in = c.username;
});
}
});
});
其他提示
生成一个唯一的套接字ID并通过推动器发送到浏览器。这将通过AJAX请求发送到您的应用程序(1),该请求授权用户针对您现有的身份验证系统访问频道。如果成功,您的应用程序将将授权字符串返回到与您的Pusher Secret签名的浏览器。这将通过Websocket发送给推杆,如果授权字符串匹配,则完成授权(2)。
因为也是 socket.io
每个插座都有唯一的socket_id。
socket.on('connect', function() {
console.log(socket.transport.sessionid);
});
他们用 签名的授权字符串 授权用户。
我还没有把它镜像 socket.io
, ,但我认为这可能是非常有趣的概念。
我知道这有点古老,但是对于未来的读者来说,除了解析cookie和从存储中检索会话的方法(例如。 Passport.Socketio )您还可能考虑一种基于令牌的方法。
在此示例中,我使用JSON Web令牌,这是非常标准的。您必须给客户页面的令牌,在此示例中,想象一下返回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服务器可以配置如下:
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中间件期望查询字符串中的令牌,因此,从客户端,您只需要在连接时附加它:
var socket = io.connect('', {
query: 'token=' + token
});
我写了一个关于这种方法和饼干的更详细的解释 这里.
本文 (http://simplapi.wordpress.com/2012/04/13/php-and-node-js-session-share-redi/)显示如何
- 将HTTP服务器的会话存储在REDIS中(使用Predis)
- 从cookie中发送的会话ID中的会话ID中从redis中获取这些会话
使用此代码,您也可以将它们放在socket.io中。
var io = require('socket.io').listen(8081);
var cookie = require('cookie');
var redis = require('redis'), client = redis.createClient();
io.sockets.on('connection', function (socket) {
var cookies = cookie.parse(socket.handshake.headers['cookie']);
console.log(cookies.PHPSESSID);
client.get('sessions/' + cookies.PHPSESSID, function(err, reply) {
console.log(JSON.parse(reply));
});
});
这是我尝试进行以下工作的尝试:
- 表示: 4.14
- socket.io: 1.5
- 护照 (使用会议):0.3
- Redis: :2.6(非常快速的数据结构来处理会话;但是您也可以使用MongoDB之类的其他人。但是,我鼓励您将其用于会话数据 + MongoDB来存储其他持久数据,例如用户)
由于您可能还想添加一些API请求,我们也会使用 http 包含HTTP和Web套接字在同一端口中工作的软件包。
server.js
以下提取物仅包含设置先前技术所需的一切。您可以在我的一个项目中看到完整的server.js版本 这里.
import http from 'http';
import express from 'express';
import passport from 'passport';
import { createClient as createRedisClient } from 'redis';
import connectRedis from 'connect-redis';
import Socketio from 'socket.io';
// Your own socket handler file, it's optional. Explained below.
import socketConnectionHandler from './sockets';
// Configuration about your Redis session data structure.
const redisClient = createRedisClient();
const RedisStore = connectRedis(Session);
const dbSession = new RedisStore({
client: redisClient,
host: 'localhost',
port: 27017,
prefix: 'stackoverflow_',
disableTTL: true
});
// Let's configure Express to use our Redis storage to handle
// sessions as well. You'll probably want Express to handle your
// sessions as well and share the same storage as your socket.io
// does (i.e. for handling AJAX logins).
const session = Session({
resave: true,
saveUninitialized: true,
key: 'SID', // this will be used for the session cookie identifier
secret: 'secret key',
store: dbSession
});
app.use(session);
// Let's initialize passport by using their middlewares, which do
//everything pretty much automatically. (you have to configure login
// / register strategies on your own though (see reference 1)
app.use(passport.initialize());
app.use(passport.session());
// Socket.IO
const io = Socketio(server);
io.use((socket, next) => {
session(socket.handshake, {}, next);
});
io.on('connection', socketConnectionHandler);
// socket.io is ready; remember that ^this^ variable is just the
// name that we gave to our own socket.io handler file (explained
// just after this).
// Start server. This will start both socket.io and our optional
// AJAX API in the given port.
const port = 3000; // Move this onto an environment variable,
// it'll look more professional.
server.listen(port);
console.info(`🌐 API listening on port ${port}`);
console.info(`🗲 Socket listening on port ${port}`);
插座/索引
我们的 socketConnectionHandler
, ,我只是不喜欢将所有内容都放在server.js中(即使您完全可以),尤其是因为此文件最终可能很快包含了很多代码。
export default function connectionHandler(socket) {
const userId = socket.handshake.session.passport &&
socket.handshake.session.passport.user;
// If the user is not logged in, you might find ^this^
// socket.handshake.session.passport variable undefined.
// Give the user a warm welcome.
console.info(`⚡︎ New connection: ${userId}`);
socket.emit('Grettings', `Grettings ${userId}`);
// Handle disconnection.
socket.on('disconnect', () => {
if (process.env.NODE_ENV !== 'production') {
console.info(`⚡︎ Disconnection: ${userId}`);
}
});
}
额外的材料(客户):
只是JavaScript socket.io客户端可能是:
import io from 'socket.io-client';
const socketPath = '/socket.io'; // <- Default path.
// But you could configure your server
// to something like /api/socket.io
const socket = io.connect('localhost:3000', { path: socketPath });
socket.on('connect', () => {
console.info('Connected');
socket.on('Grettings', (data) => {
console.info(`Server gretting: ${data}`);
});
});
socket.on('connect_error', (error) => {
console.error(`Connection error: ${error}`);
});
参考:
我只是无法在代码中引用,所以我将其移到了这里。
1:如何设置护照策略: https://scotch.io/tutorials/easy-node-authentication-setup-and-local#handling-signupregistration
使用C/S之间的会话和重新介绍
// 服务器端
io.use(function(socket, next) {
console.log(socket.handshake.headers.cookie); // get here session id and match from redis session data
next();
});
这应该做到
//server side
io.sockets.on('connection', function (con) {
console.log(con.id)
})
//client side
var io = io.connect('http://...')
console.log(io.sessionid)