Passport + JWT + Socket.IO身份validation

我正在寻找在我的KOA NodeJS应用程序中使用Socket.io实现JWT身份validation的最佳方向。

我在socketio + jwt上find了一个很好的回购 ,但是作者并没有使用护照也没有使用koa。 我想我已经有了一个好的开始,但是我想知道在使用智威汤逊之后,护照是否过分了。 以下是我的代码。

Koa.js

import koa from 'koa'; import router from 'koa-router'; import json from 'koa-json'; import bodyParser from 'koa-bodyparser'; import passport from './passport'; import session from './session'; import { config } from './env/env'; export class Koa { constructor(){ this.app = koa(); this.initMiddleware(); } initMiddleware(){ this.app.use(json()); this.app.use(bodyParser()); this.app.keys = config.secret; this.app.use(session); this.app.use(passport.initialize()); this.app.use(passport.session()); } } 

Session.js

 import session from 'koa-generic-session'; // todo: configure for db backed store export default session(); 

Passport.js

 import passport from 'koa-passport'; import { config } from './env/env'; import { Strategy } from 'passport-jwt'; // todo! var user = { id: 1, username: 'test' } passport.serializeUser((user, done) => { done(null, user.id) }); passport.deserializeUser((id, done) => { done(null, user) }); const opts = { secretOrKey: config.secret }; passport.use(new Strategy(opts, (jwt_payload, done) => { // User.findOne({id: jwt_payload.sub}, function(err, user) { if (username === 'test' && password === 'test') { done(null, user) } else { done(null, false) } })); export default passport; 

socketio.js

 import io from 'socket.io'; import session from './session'; export class SocketIO { constructor(application){ this.io = io(application.server); // authenticate middleware this.io.use(function(socket, next){ // http://stackoverflow.com/questions/13095418/how-to-use-passport-with-express-and-socket-io // http://stackoverflow.com/questions/26643370/get-user-id-socket-io-passport-koa //var sid = cookie.parse(socket.handshake.headers.cookie)['koa.sid']; session.apply(socket.request, next); }); this.buildEvents(); } buildEvents(){ this.io.on('connection', (socket) => { console.log(`new connection: ${socket.id}`); // accessible through a api route application.app.socket = socket; socket.on('disconnect', () => { console.log(`disconnected: ${socket.id}`); }); }); } } 

谢谢你的帮助。

       

网上收集的解决方案 "Passport + JWT + Socket.IO身份validation"