【问题标题】:Socket authentication with node.js & socket.io (using DaftMonk's generator-angular-fullstack)使用 node.js 和 socket.io 进行套接字身份验证(使用 DaftMonk 的 generator-angular-fullstack)
【发布时间】:2015-02-11 11:35:17
【问题描述】:

我将DaftMonk's generator-angular-fullstack 用于所有设置为默认值的项目, 我发现自己需要使用它进行套接字身份验证,所以我在 socketio.js 上启用了“socketio-jwt” 在 Angular 服务上。 这就是我的 Angular 服务的样子:

/* global io */
'use strict';

angular.module('myApp')
  .factory('socket', function(socketFactory, Auth) {

    // socket.io now auto-configures its connection when we ommit a connection url
    var ioSocket = io('', {
      // Send auth token on connection, you will need to DI the Auth service above
      query: 'token=' + Auth.getToken(),
      path: '/socket.io-client'
    });

    var socket = socketFactory({
      ioSocket: ioSocket
    });

    return {
      socket: socket,

      /**
       * Register listeners to sync an array with updates on a model
       *
       * Takes the array we want to sync, the model name that socket updates are sent from,
       * and an optional callback function after new items are updated.
       *
       * @param {String} modelName
       * @param {Array} array
       * @param {Function} cb
       */
      syncUpdates: function (modelName, array, cb) {
        cb = cb || angular.noop;

        /**
         * Syncs item creation/updates on 'model:save'
         */
        socket.on(modelName + ':save', function (item) {
          var oldItem = _.find(array, {_id: item._id});
          var index = array.indexOf(oldItem);
          var event = 'created';

          // replace oldItem if it exists
          // otherwise just add item to the collection
          if (oldItem) {
            array.splice(index, 1, item);
            event = 'updated';
          } else {
            array.push(item);
          }

          cb(event, item, array);
        });

        /**
         * Syncs removed items on 'model:remove'
         */
        socket.on(modelName + ':remove', function (item) {
          var event = 'deleted';
          _.remove(array, {_id: item._id});
          cb(event, item, array);
        });
      },

      /**
       * Removes listeners for a models updates on the socket
       *
       * @param modelName
       */
      unsyncUpdates: function (modelName) {
        socket.removeAllListeners(modelName + ':save');
        socket.removeAllListeners(modelName + ':remove');
      }
    };
  });

这是我在服务器上的 socketio 文件的样子:

/**
 * Socket.io configuration
 */

'use strict';

var config = require('./environment');

// When the user disconnects.. perform this
function onDisconnect(socket) {
}

// When the user connects.. perform this
function onConnect(socket) {
  //I dont have any decoded_token here
  console.log(socket.handshake.decoded_token._id, 'connected');

  // When the client emits 'info', this listens and executes
  socket.on('info', function (data) {
    console.info('[%s] %s', socket.address, JSON.stringify(data, null, 2));
  });

  // Insert sockets below
  require('../api/conversation/conversation.socket').register(socket);
}

module.exports = function (socketio) {
  // socket.io (v1.x.x) is powered by debug.
  // In order to see all the debug output, set DEBUG (in server/config/local.env.js) to including the desired scope.
  //
  // ex: DEBUG: "http*,socket.io:socket"

  // We can authenticate socket.io users and access their token through socket.handshake.decoded_token
  //
  // 1. You will need to send the token in `client/components/socket/socket.service.js`
  //
  // 2. Require authentication here:
  // socketio.use(require('socketio-jwt').authorize({
  //   secret: config.secrets.session,
  //   handshake: true
  // }));

  socketio.use(require('socketio-jwt').authorize({
    secret: config.secrets.session,
    handshake: true
  }));

  socketio.on('connection', function (socket) {
    socket.address = socket.handshake.address !== null ?
            socket.handshake.address.address + ':' + socket.handshake.address.port :
            process.env.DOMAIN;

    socket.connectedAt = new Date();

    // Call onDisconnect.
    socket.on('disconnect', function () {
      onDisconnect(socket);
      console.info('[%s] DISCONNECTED', socket.address);
    });

    // Call onConnect.
    onConnect(socket);
    console.info('[%s] CONNECTED', socket.address);
  });
};

我已阅读 this 关于套接字身份验证的博客文章,并希望我的套接字具有 decoded_token 值但它没有,我验证 jwt 符号将 userId 附加到令牌 但我还是没看到……

这是我的 jwt 标志:

/**
 * Returns a jwt token signed by the app secret
 */
function signToken(id) {
  return jwt.sign({ _id: id }, config.secrets.session, { expiresInMinutes: 60*5 });
}

/**
 * Set token cookie directly for oAuth strategies
 */
function setTokenCookie(req, res) {
  if (!req.user) return res.json(404, { message: 'Something went wrong, please try again.'});
  var token = signToken(req.user._id, req.user.role);
  res.cookie('token', JSON.stringify(token));
}

我的问题是,如何获取附加到套接字的当前用户信息? (只是 id 很好)。

【问题讨论】:

    标签: angularjs node.js socket.io


    【解决方案1】:

    我真傻,好像我在错误的地方寻找解码的令牌,它就在这里: socket.decoded_token._id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 2022-07-11
      • 2018-08-03
      • 1970-01-01
      • 2013-11-02
      • 2014-08-18
      • 2014-12-01
      相关资源
      最近更新 更多