Search code examples
node.jscookiessocket.ionestjsnestjs-gateways

Nestjs websocket gateway, how to parse signed cookies from handshake for guard authorization?


My guard contains the following code:

    let client: Socket = context.switchToWs().getClient();
    const sessionCookie = client.handshake.headers.cookie
      .split('; ')
      .find((cookie: string) => cookie.startsWith('session'))
      .split('=')[1];

    const sessionId = cookieParser.signedCookie(
      sessionCookie,
      process.env.CryptoKey,
    );

    console.log('SESSION ID',sessionId);

The resulting sessionId is still signed after calling cookieParse.signedCookie();

client.request.cookies and signedCookies are both undefined.

The session id is there and the cookie is being sent by the browser but I am unable to parse it in the gateway.


Solution

  • I had the same issue and found the answer. Your code is close, but the reason cookieParser.signedCookie(...) returns the signed cookie again is because some characters in the cookie value are encoded. So it doesn't detect the string as a signed cookie.

    To fix this, you have to pass decodeURIComponent(sessionCookie) to the cookieParser instead.

        let client: Socket = context.switchToWs().getClient();
        const sessionCookie = client.handshake.headers.cookie
          .split('; ')
          .find((cookie: string) => cookie.startsWith('session'))
          .split('=')[1];
    
        const sessionId = cookieParser.signedCookie(
          decodeURIComponent(sessionCookie),
          process.env.CryptoKey,
        );
    
        console.log('SESSION ID',sessionId);