0
votes

I am having trouble trying to set up a lambda authorizations for a WebSocket API.

Serverless.yml

functions:
  sample-web-socket-authorizer:
    iamRoleStatementsName: stack-${opt:stage}-web-socket-authorizer
    iamRoleStatementsInherit: true
    iamRoleStatements:
      - Effect: "Allow"
        Action:
          - 'cognito-idp:*'
        Resource: '*'
    handler: sample-web-socket-authorizer/handler.handler
    environment:
      JWK_URL: ${self:custom.jwkUrl}
      CLIENT_ID: ${self:custom.cognitoClientId}
  ...
  connectionHandler:
    handler: handler.connectionHandler
    events:
      - websocket:
          route: $connect
          authorizer:
            name: sample-web-socket-authorizer
            identitySource:
              - 'route.request.querystring.Authorizer'

in frontend i want to send a tokenId or accessToken to use in authorizer

wss://abcd1234.execute-api.ap-region-1.amazonaws.com/pre?Authorizer=${token}

Can u guys please give me a sample code using python to create a lambda authorizer for my websocket api.

I am currently looking at these article: https://github.com/awslabs/aws-support-tools/blob/master/Cognito/decode-verify-jwt/decode-verify-jwt.py

1

1 Answers

1
votes

So what i do is that i literally copy this code to my authorizer handler: https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/blob/master/blueprints/python/api-gateway-authorizer-python.py

and then base on this docs https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-lambda-auth.html

I changed the code

resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)        

to

resourceArn = self.methodArn

also you need to specify the methodArn in the AuthPolicy Class that look like this:

class AuthPolicy(object):
    # The AWS account id the policy will be generated for. This is used to create the method ARNs.
    awsAccountId = ''
    # The principal used for the policy, this should be a unique identifier for the end user.
    principalId = ''
    # The policy version used for the evaluation. This should always be '2012-10-17'
    version = '2012-10-17'
    # The regular expression used to validate resource paths for the policy
    pathRegex = '^[/.a-zA-Z0-9-\*]+$'

    methodArn = '*'
    ....

And then lastly upon creating the AuthPolicy add the methodArn Value comming from lambda event:

policy = AuthPolicy(principalId, awsAccountId)
        policy.restApiId = apiGatewayArnTmp[0]
        policy.region = tmp[3]
        policy.stage = apiGatewayArnTmp[1]
        policy.methodArn = event["methodArn"]
        policy.allowAllMethods()