我正在尝试将JWT身份验证添加到nestJs WebSockets。
我可以从客户端连接并发送标头。
但是,在使用防护设置nestJs WebSocket时出现错误TypeError: host.setType is not a function
。
错误源自ws-proxy.js
ExecutionContextHost
的返回值没有名为setType
的属性/方法,但在第27行:已使用
我的Guard.ts文件如下。
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import * as configs from 'config';
import { Socket } from 'socket.io';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from '../jwt-payload.interface';
import { WsException } from '@nestjs/websockets';
@Injectable()
export class JwtGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) { }
async canActivate(context: ExecutionContext): Promise<boolean> {
try {
const client: Socket = context.switchToWs().getClient<Socket>();
const authHeader: string = client.handshake.headers.authorization;
const authToken = authHeader.substring(7, authHeader.length);
const jwtPayload: JwtPayload = await this.jwtService.verifyAsync(authToken, configs.get('JWT.publicKey'));
const user: any = this.validateUser(jwtPayload);
context.switchToWs().getData().user = user;
return Boolean(user);
} catch (err) {
throw new WsException(err.message);
}
}
validateUser(payload: JwtPayload): any {
return payload;
}
}
套接字文件是
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import { Socket } from 'socket.io';
import { UseGuards} from '@nestjs/common';
import { JwtGuard } from '../../../common/authentication/jwt-guard/jwt.guard';
@UseGuards(JwtGuard)
@WebSocketGateway()
export class ContractGateway {
@SubscribeMessage('message')
handleMessage(client: Socket, payload: any): Boolean {
return true;
}
}
有人遇到这种错误以及如何解决吗?
答案 0 :(得分:0)
发现了问题,"@nestjs/websockets": "^6.8.2"
和"@nestjs/core": "^6.0.0",
之间的程序包冲突。我需要升级所有@nestjs软件包