amazon-web-servicesaws-authorizeraws-websocket-api

What WebSocket API custom lambda authorizer should return in AWS API Gateway?


I'm trying to add a custom Lambda authorizer to my WebSocket API, but I'm stuck on what response needs to be returned.

My custom Lambda authorizer for the HTTP API looks like this. Based on the event, I simply return a result object, as shown in the example below.

function customHttpLambdaAuthorizer(event) {
    const isValid = validate(event);
    
    const result = {
        isAuthorized: isValid === true,
        context: {
          message: "User authenticated"
        }
    };
    
    return result;
}

When I tried to add a custom authorizer for a WebSocket and attempted to return a similar result, it didn't work. I found this example in the AWS documentation, but they use a policy, which I don't fully understand. I also have a feeling that the example is outdated because it uses callbacks, etc.

function customWebSocketLambdaAuthorizer(event) {
  const isValid = validate(event);
  
  const result =  /* ? */;
  
  return result;
}

Could someone clearly explain what a custom WebSocket Lambda authorizer should return, and why?

Thanks!


Solution

  • That documentation you listed is correct and shows the correct example for what it should return. When an authorizer is configured, AWS will add a processing step in the request pipeline that will call the authorizer and evaluate the result. It needs a policy to do this evaluation--that is just how the behind-the-scenes logic works to evaluate if something is authorized. If the returned policy indicates that the request is allowed, then the request continues through the rest of the pipeline.

    From https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html: Authorizer flow

    This documentation talks about the output of the authorizer lambda and shows the response, such as this example:

    {
      "principalId": "user",
      "policyDocument": {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Action": "execute-api:Invoke",
            "Effect": "Deny",
            "Resource": "arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/dev/GET/"
          }
        ]
      }
    }