与Node.js的&安培插座认证; socket.io(使用DaftMonk的发电机角fullstack) [英] Socket authentication with node.js & socket.io (using DaftMonk's generator-angular-fullstack)
问题描述
我使用 DaftMonk的发电机角fullstack 获得的一切项目设置为默认值,
我发现自己需要插座身份验证,所以我已经启用了socketio,智威汤逊关于socketio.js
和对角的服务。
这是我的角度服务的样子:
I'm using DaftMonk's generator-angular-fullstack for a project with everything set as default, I find myself needing socket authentication with it so I have enabled "socketio-jwt" on the socketio.js and on the Angular service. This is how my Angular service looks like:
/* 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文件的样子:
This is how my socketio file on the server looks like:
/**
* 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);
});
};
我已阅读这的博客文章插座认证,并且预期我的插座有一个代coded_token值,但它不,我验证了JWT符号附加的用户id令牌
但我仍然没有看到它...
I have read this blog post about socket authentication, and expected my socket to have a decoded_token value but it does not, I verified that the jwt sign attaches the userId to the token but I still don't see it...
这是我的智威汤逊的迹象:
This is my jwt sign:
/**
* 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是罚款)。
My question is this, how do I get the current user info attached to the socket? (just the id is fine).
推荐答案
我傻,就好像我一直在寻找在错误的地方去codeD的道理,正是在这里:
socket.de coded_token._id
Silly me, it seems like I was looking for the decoded token in the wrong place, it was here: socket.decoded_token._id
这篇关于与Node.js的&安培插座认证; socket.io(使用DaftMonk的发电机角fullstack)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!