【问题标题】:@nestjs/websockets with Guards fails with host.setType@nestjs/websockets with Guards 因 host.setType 而失败
【发布时间】:2020-02-07 13:15:32
【问题描述】:

我正在尝试将 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;
  }
}

socket文件是

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

有没有人遇到过这样的错误以及如何解决?

【问题讨论】:

  • 我正在尝试完成相同的操作,但是您如何在客户端套接字中连接标头?我正在添加选项对象 { header: { Authorization: Bearer ... }} 但没有办法得到...

标签: websocket nestjs


【解决方案1】:

发现问题,"@nestjs/websockets": "^6.8.2""@nestjs/core": "^6.0.0", 之间的包冲突。我需要升级所有@nestjs 包

【讨论】:

  • 你能解释一下升级是什么意思吗?如何升级?我有同样的问题
  • @nestjs/websockets & @nestjs/core 需要或多或少在同一个版本上,在我的例子中是 6.8.2
猜你喜欢
  • 2020-02-11
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
  • 2012-10-03
相关资源
最近更新 更多