【问题标题】:How to use guards with NestJs gateway(web sockets)?如何将守卫与 NestJs 网关(网络套接字)一起使用?
【发布时间】:2022-12-24 01:33:05
【问题描述】:

在我的 NestJS API 中,我是 JWT 令牌,存储在 cookie 中以验证我的用户。

用户必须调用我的登录控制器:

  @UseGuards(LocalAuthenticationGuard)
  @Post('login')
  async logIn(@Req() request: RequestWithUser) {
    const { user } = request;
    const cookie = this.authenticationService.getCookieWithJwtToken(user._id);
    request.res?.setHeader('Set-Cookie', cookie);
    return user;
  }

LocalAuthenticatedGuard 验证用户名密码并填写用户请求,然后将 cookie 提供给客户端,并将与我的其他警卫一起验证是否有任何进一步的请求:

@Injectable()
export default class JwtAuthenticationGuard extends AuthGuard('jwt') {}

及其相关策略:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    private readonly userService: UsersService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (request: Request) => {
          return request?.cookies?.Authentication;
        },
      ]),
      secretOrKey: configService.get('JWT_SECRET'),
    });
  }

  async validate(payload: TokenPayload) {
    return this.userService.getById(payload.userId);
  }
}

这非常适合我的发布/获取方法。

但是现在我对网络套接字有一些需求,所以我尝试了以下方法:

@WebSocketGateway({
  cors: {
    origin: '*',
  },
})
export class PokerGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer() server: Server;
  private logger: Logger = new Logger('AppGateway');

  @SubscribeMessage('msgToServer')
  handleMessage(client: Socket, payload: string): void {
    this.logger.log(`Client ${client.id} sent message: ${payload}`);
    this.server.emit('msgToClient', payload);
  }

  afterInit(server: Server) {
    this.logger.log('Init');
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`Client disconnected: ${client.id}`);
  }

  @UseGuards(JwtAuthenticationGuard)
  handleConnection(
    client: Socket,
    @Req() req: RequestWithUser,
    ...args: any[]
  ) {
    this.logger.log(`Client connected: ${client.id}`);
    this.logger.log(client.handshake.query['poker-id']);
    this.logger.log(req);
  }
}

但:

  1. 即使我没有连接,连接也会建立
  2. 用户未设置为我的请求

    会是什么:

    1. 如何使用我的auth guard并接收匹配的用户?
    2. 对于进一步的消息,我是否应该只在网关中保留 client.id <--> 我的用户的字典?或者有没有办法在每条消息中也接收用户?

【问题讨论】:

    标签: authentication websocket nestjs nestjs-jwt nestjs-gateways


    【解决方案1】:

    请参阅this 回答。

    如果您提供有关客户端的一些信息,那将提供更多信息。

    我脑子里出现了一些问题,比如“你如何通过 websocket 将请求上下文作为数据发送?”,“你在另一个 http 控制器中调用这个事件吗?”

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 2013-03-18
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多