使用 Lambda Authorizer 的 AWS Cognito 和 Websocket Api

AWS Cognito and Websocket Api using Lambda Authorizer

我在尝试为 WebSocket 设置 lambda 授权时遇到问题 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'

在前端,我想发送一个 tokenId 或 accessToken 以在授权方中使用

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

你们可以给我一个使用 python 为我的 websocket api.

创建 lambda 授权器的示例代码吗

我目前正在看这些文章:https://github.com/awslabs/aws-support-tools/blob/master/Cognito/decode-verify-jwt/decode-verify-jwt.py

所以我所做的就是将这段代码复制到我的授权处理程序中:https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/blob/master/blueprints/python/api-gateway-authorizer-python.py

然后基于此文档https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-lambda-auth.html

我改了代码

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

resourceArn = self.methodArn

您还需要在 AuthPolicy Class 中指定 methodArn,如下所示:

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 = '*'
    ....

然后最后在创建 AuthPolicy 时添加来自 lambda 事件的 methodArn 值:

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