Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport + JWT + Socket.IO Authentication

I'm looking for the best direction on implementing JWT Authentication with Socket.io in my KOA NodeJS application.

I found a great repo on socketio + jwt but the author does not use passport nor koa. I think I've got a good start but I'm wondering if Passport is overkill at this point since I'm using JWT. Below is my code.

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

}

Thanks for your help.

like image 287
amcdnl Avatar asked May 10 '26 03:05

amcdnl


1 Answers

You may be right in that passport may be overkill. Maybe check out jsonwebtoken on npm?

Then you can add the .verify() function to your authenticating middleware, and just use .sign() when creating your session in order to designate a user as authenticated.

like image 70
Kassandra Perch Avatar answered May 12 '26 12:05

Kassandra Perch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!