Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JWT support for SocketIO #1205

Open
everythingspirals opened this issue Jan 31, 2023 · 1 comment
Open

JWT support for SocketIO #1205

everythingspirals opened this issue Jan 31, 2023 · 1 comment

Comments

@everythingspirals
Copy link

Is there a way we can integrate JWT into the SocketIO controller. One recommendation is to add a middleware like so:

io.use(function(socket, next){
  if (socket.handshake.query && socket.handshake.query.token){
    jwt.verify(socket.handshake.query.token, 'SECRET_KEY', function(err, decoded) {
      if (err) return next(new Error('Authentication error'));
      socket.decoded = decoded;
      next();
    });
  }
  else {
    next(new Error('Authentication error'));
  }    
})

How can we access the io object to connect such a middleware?

@warren-gallagher
Copy link

I implemented support for JWT upon connection in the onConnection() method like the following.

export class ConnectionErrorException extends Error {

    constructor(statusCode: number, message: string) {
        super(JSON.stringify({status: statusCode, message: message}));
    }
}

export class WebsocketService extends SocketIOController {
    async onConnection(ctx: WebsocketContext) {
        const logPrefix = `${new Date().toISOString()} onConnection`;
        const authorizationHeader = ctx.socket.handshake.headers['authorization'];
        if( authorizationHeader == null || authorizationHeader == "" || !authorizationHeader.startsWith('Bearer ') ) {
            const msg = 'BadRequest - missing or invalid Authorization header. Disconnecting.';
            console.error(`${logPrefix} ${msg}`);
            throw new ConnectionErrorException(400, msg);
        }
        const token = authorizationHeader.split(' ')[1];
        /// the following is pseudo code for verification, replace as appropriate
        const verified = verifyJwt( token, secret );
        if( !verified ) {
            const msg = 'Unauthorized - verify Authorization Bearer token failed. Disconnecting.';
            console.error(`${logPrefix} ${msg}`);
            throw new ConnectionErrorException(401, msg);
        }
   }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants