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
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]';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With