Socket.IO身份验证

Rya*_*yan 115 authentication node.js express socket.io

我试图在Node.js中使用Socket.IO,并试图让服务器为每个Socket.IO客户端提供一个标识.由于套接字代码超出了http服务器代码的范围,因此它无法轻松访问发送的请求信息,因此我假设它需要在连接期间发送.什么是最好的方法

1)通过Socket.IO获取有关谁连接的信息

2)验证他们说自己是谁(我目前正在使用Express,如果这让事情变得更容易)

Shr*_*hna 103

使用connect-redis并将redis作为所有经过身份验证的用户的会话存储.确保在身份验证时将密钥(通常为req.sessionID)发送给客户端.让客户端将此密钥存储在cookie中.

在套接字连接上(或以后的任何时间)从cookie中获取此密钥并将其发送回服务器.使用此密钥以redis格式获取会话信息.(GET键)

例如:

服务器端(使用redis作为会话存储):

req.session.regenerate...
res.send({rediskey: req.sessionID});
Run Code Online (Sandbox Code Playgroud)

客户端:

//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});
});
Run Code Online (Sandbox Code Playgroud)

服务器端:

//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;
      });
    }

  });
});
Run Code Online (Sandbox Code Playgroud)

  • 关于这个有一个新的有趣的链接=> http://www.danielbaulig.de/socket-ioexpress/ (3认同)

Alf*_*red 32

我也很喜欢pusherapp私人频道的方式.在此输入图像描述

Pusher生成一个唯一的套接字ID并将其发送到浏览器.这将通过AJAX请求发送到您的应用程序(1),该请求授权用户针对您现有的身份验证系统访问该通道.如果成功,您的应用程序会向使用Pusher secret签名的浏览器返回授权字符串.这是通过WebSocket发送给Pusher的,如果授权字符串匹配,则完成授权(2).

因为socket.io每个套接字也有唯一的socket_id.

socket.on('connect', function() {
        console.log(socket.transport.sessionid);
});
Run Code Online (Sandbox Code Playgroud)

他们使用签名授权字符串来授权用户.

我还没有反映过这个socket.io,但我认为它可能是非常有趣的概念.

  • 这太棒了.但如果您的应用服务器和websocket服务器没有分开,那么使用cookie会更容易.但是您通常希望将两者分开(如果分开,将更容易扩展套接字服务器).所以这很好:) (3认同)

Jos*_*llo 25

我知道这有点旧,但对于未来的读者,除了解析cookie和从存储中检索会话的方法(例如passport.socketio)之外,您还可以考虑基于令牌的方法.

在这个例子中,我使用非常标准的JSON Web Tokens.您必须向客户端页面提供令牌,在此示例中,假设一个返回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});
});
Run Code Online (Sandbox Code Playgroud)

现在,您的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');
  });
Run Code Online (Sandbox Code Playgroud)

socket.io-jwt中间件期望查询字符串中的令牌,因此从客户端您只需在连接时附加它:

var socket = io.connect('', {
  query: 'token=' + token
});
Run Code Online (Sandbox Code Playgroud)

在这里写了一个关于这个方法和cookie的更详细的解释.


zur*_*fyx 5

这是我尝试进行以下工作:

  • 快递:4.14
  • socket.io:1.5
  • 护照(使用会话):0.3
  • redis : 2.6(处理会话的数据结构非常快;但您也可以使用其他像 MongoDB 这样的结构。不过,我鼓励您将其用于会话数据 + MongoDB 来存储其他持久性数据,例如用户)

由于您可能还想添加一些 API 请求,我们还将使用http包让 HTTP 和 Web 套接字在同一端口工作。


服务器.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}`);
Run Code Online (Sandbox Code Playgroud)

套接字/ index.js

我们的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}`);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

额外材料(客户):

只是 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}`);
});
Run Code Online (Sandbox Code Playgroud)

参考:

我只是无法在代码内部引用,所以我把它移到了这里。

1:如何设置您的 Passport 策略:https : //scotch.io/tutorials/easy-node-authentication-setup-and-local#handling-signupregistration