WebSocket Support

This guide explains how to implement WebSocket authentication with AWS Cognito in your NestJS application using @nestjs-cognito/auth and @nestjs-cognito/core packages.

Overview

The WebSocket support in NestJS-Cognito allows you to authenticate WebSocket connections using JWT tokens from AWS Cognito. This is particularly useful for real-time applications that require secure, authenticated connections.

Implementation

Gateway Setup

First, create a WebSocket gateway that implements the necessary interfaces and injects the CognitoJwtVerifier:

import { WebSocketGateway, WebSocketServer, OnGatewayConnection } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { CognitoJwtVerifier, InjectCognitoJwtVerifier } from '@nestjs-cognito/core';
import { Logger } from '@nestjs/common';

@WebSocketGateway()
export class MessagesGateway implements OnGatewayConnection {
  private logger = new Logger('MessagesGateway');

  constructor(
    @InjectCognitoJwtVerifier()
    private readonly jwtVerifier: CognitoJwtVerifier
  ) {}

  @WebSocketServer()
  wss: Server;

  async handleConnection(client: Socket, ...args: any[]) {
    try {
      const token = client.handshake.headers.authorization?.replace('Bearer ', '');
      if (!token) {
        this.logger.error('No authorization token provided');
        client.disconnect();
        return;
      }

      const payload = await this.jwtVerifier.verify(token);
      this.logger.log(`Client connected: ${client.id}`);
      this.logger.log('JWT Payload:', payload);

      // Store user information in socket
      client.data.user = payload;

    } catch (error) {
      this.logger.error('Authentication failed:', error);
      client.disconnect();
    }
  }
}

Client Connection

On the client side, include the JWT token in the connection headers:

import { io } from 'socket.io-client';

const socket = io('http://localhost:3000', {
  extraHeaders: {
    authorization: `Bearer ${jwtToken}`
  }
});