English 中文(简体)
Socket. IO Authentication
原标题:Socket.IO Authentication

I am trying to use Socket.IO in Node.js, and am trying to allow the server to give an identity to each of the Socket.IO clients. As the socket code is outside the scope of the http server code, it doesn t have easy access to the request information sent, so I m assuming it will need to be sent up during the connection. What is the best way to

(1) 向服务器获取有关谁通过Socket连接的信息。 IO

2) 认证他们说是谁(目前使用快递,如果这样会更容易的话)

最佳回答

将所有经认证的用户使用连接处理,并重新作为本届会议的储存。 • 确保你向客户发送钥匙(通常是再q.sessionID)。 客户在一个厨师中储存这一钥匙。

接线(或后来)从厨师手中夺走这一钥匙,将其送回服务器。 召集会议是为了重新使用这一钥匙。 (GET key)

例如:

服务器方面(作为会议储存重置):

req.session.regenerate...
res.send({rediskey: req.sessionID});

Client side:

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

  });
});
问题回答

我知道这种情况是老的,但对于未来的读者来说,除了从储存中回收(例如passport.socketio)外,你还可以考虑一种象征性的做法。

在这种例子中,我使用的是JSON Web Tokens。 您必须贴上象征性的客户网页,在这种例子中,可以想象出一个真实的终点,回报金字塔:

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

现在,你的发言。 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 );
  });

ocket-jwt中华预计会在电梯中标出,因此,在连接:

var socket = io.connect(  , {
  query:  token=  + token
});

我就这一方法做了更详细的解释,并做了如下文.:here

我在此试图开展以下工作:

  • express: 4.14
  • socket.io: 1.5
  • passport (using sessions): 0.3
  • redis: 2.6 (Really fast data structure to handle sessions; but you can use others like MongoDB too. However, I encourage you to use this for session data + MongoDB to store other persistent data like Users)

由于你可能希望增加一些APIC申请,我们也使用<>strong>http://的包裹,使吉大港山区和网络的袖珍在同一港口工作。


server.js

下面的摘录仅包括你需要建立以前技术的一切。 你可以看到完整的服务器。 jjs edition which I used in one of my projects

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

sockets/index.js

我们的<代码>socketConnectionHandler,我不喜欢把一切放在服务器内(尽管你完全可以做到这一点),特别是因为这一档案能够很快地包含大量的代码。

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

Extra material (client):

简言之,简言之,简言之。 用户可以是:

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

References:

I 只是略微提及该守则,因此我在此提出。

1. 如何制定你的护照战略: https://scotch.io/tutorials/easy-node-authentication-setup-and- local#handling-signup Registration

c/c

www.un.org/Depts/DGACM/index_spanish.htm 页: 1

io.use(function(socket, next) {
    // get here session id 
    console.log(socket.handshake.headers.cookie); and match from redis session data
    next();
});




相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Remotely authenticating client Windows user on demand

Suppose I am writing a server for a particular network protocol. If I know that the client is running on a Windows machine, is it possible for my server to authenticate the Windows user that owns the ...

Role/Permission based forms authorizing/authentication?

While looking into forms authorizing/authentication, I found that it is possible to do role based authorizing by adding an array of roles to a FormsAuthenticationTicket. That way I can write User....