我正在寻找在我的KOA NodeJS应用程序中实现JWT身份验证与Socket.io的最佳方向。
我发现了一个很棒的repo,它涉及socketio + jwt,但作者没有使用passport或koa。我认为我已经有了一个良好的开端,但我想知道是否在这个点上使用Passport过于复杂,因为我正在使用JWT。以下是我的代码。
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){
// https://dev59.com/bGcs5IYBdhLWcg3wJQm8
// https://dev59.com/94Tba4cB1Zd3GeqP97jN
//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}`);
});
});
}
}
谢谢您的帮助。