【发布时间】: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 ... }} 但没有办法得到...