Passing Cognito JWT via Websockets

api-gateway

#1

I’m just really trying to figure out how serverless expects the Cognito auth token to be passed with a websockets connection.

I have an authoriser lambda on my websocket paths:

  connectionHandler:
    handler: handler.connectionHandler
    events:
      - websocket:
          route: $connect
          authorizer:
            arn: ${self:provider.environment.authoriserArn}
      - websocket:
          route: $disconnect
          authorizer:
            arn: ${self:provider.environment.authoriserArn}

I was wondering how I actually pass the token from the client over the connection in order for the auth to trigger correctly.

I’ve tried with rxjs websocket and with protocols, but not really sure how the authoriser should handle the request (I cannot see any token in the params passed in). I don’t believe we can add headers to websockets:

private setupWebsockets(token: string) {
    const subjectConfig: WebSocketSubjectConfig<any> = {
      url: 'wss://abcd1234.execute-api.ap-southeast-1.amazonaws.com/pre',
      protocol: [
        `${token}`
      ]
    };

    this.subject = webSocket(subjectConfig);

    this.subject.subscribe(
        (msg) => console.log('message received: ' + msg),
        (err) => console.error(err),
        () => console.log('complete')
      );
  }

Cheers


#2

It actually doesn’t look like my authorizer is being created when I login and check it manually. When I try to, I cannot use Cognito directly. If this is the case, that we cannot use Cognito directly, it should state in the docs (https://serverless.com/framework/docs/providers/aws/events/websocket#using-authorizers).


#3

In my experience,
(a) Amazon Websockets does not support modifying the subprotocol as you are doing in your example, as shown here, https://forums.aws.amazon.com/thread.jspa?messageID=883536&tstart=0. That is why you are not seeing the token in your authorizer.
(b) Also your authorizer is not being created if you are using the latest version of severless(1.38). You might have to use the master. Full support for authorizer is for the 1.39 release.


#4

Thanks! Looks to be the case :slight_smile: https://github.com/serverless/serverless/issues/5910