Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I use middleware for verify jwt token for socket-io in nestjs project?

I have a nestjs project that I am using socket-io in it. there is a problem in my middleware (socketJwtMiddleware), it doesn't throw error, but doesn't work.I declare a socketjwtMiddleware which verify jwt token, actually when socket is connected, the middleware doesn't execute

import {
  Injectable,
  NestMiddleware,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request, Response, NextFunction } from 'express';
import { Socket } from 'socket.io';

@Injectable()
export class SocketJwtMiddleware implements NestMiddleware {
  constructor(private readonly jwtService: JwtService) {}
  use(socket:Socket, next: NextFunction) {
    console.log('+++++++++++++++++');

    const token = socket.handshake.auth?.token;
    try {
      if (token) {
        const decode = this.jwtService.verify(token, {
          secret: process.env.JWT_SECRET,
        });
        socket['user'] = decode;
      }
      console.log('Request...');
    } catch (error) {
      return next(new UnauthorizedException());
    }

    next();
  }
}

my socket gateway is

import {
  MiddlewareConsumer,
  NestModule,
  OnModuleInit,
  UseGuards,
} from '@nestjs/common';
import {
  ConnectedSocket,
  MessageBody,
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { SocketJwtMiddleware } from './socketJwt.middleware';

@WebSocketGateway({
  cors: {
    path: '*',
    method: ['GET', 'POST'],
  },
})
export class SocketGateway implements OnModuleInit {
  @WebSocketServer()
  server: Server;

  onModuleInit() {
    this.server.on('connection', (socket: any) => {
      console.log('connection', socket.id);
    });
  }

  @SubscribeMessage('message')
  handleEvent(
    @MessageBody() data: string,
    @ConnectedSocket() client: Socket,
  ): string {
    console.log('message', data);
    console.log(client.id);

    return data;
  }
}

and socketModule is

import {
  MiddlewareConsumer,
  Module,
  NestMiddleware,
  NestModule,
} from '@nestjs/common';
import { SocketJwtMiddleware } from './socketJwt.middleware';
import { SocketGateway } from './socket.gateway';

@Module({
  providers: [SocketGateway],
})
export class SocketModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(SocketJwtMiddleware).forRoutes("");
  }
}

my socket is connected but my middleware doesn't work, please help me

like image 707
farshid.chegini Avatar asked Nov 30 '25 17:11

farshid.chegini


1 Answers

Middleware is called only in http requests. Instead you can use Guards and check message data there or you can check initial request object (request to establish WS connection) which attaches to the Socket object:

@Injectable()
export class SocketAuthGuard implements CanActivate {
  constructor(private reflector: Reflector) { }

  canActivate(
    context: ExecutionContext,
  ): boolean {
    const token = context
      .switchToWs()
      .getClient()
      .handshake.auth.token;

    return token === '[some_token]';
  }
}
like image 180
Vasily Avatar answered Dec 02 '25 07:12

Vasily



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!