【问题标题】:AWS Cognito and Websocket Api using Lambda Authorizer使用 Lambda Authorizer 的 AWS Cognito 和 Websocket Api
【发布时间】:2021-02-02 23:36:09
【问题描述】:

我在尝试为 WebSocket API 设置 lambda 授权时遇到问题。

无服务器.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

【问题讨论】:

    标签: amazon-web-services aws-lambda aws-api-gateway lambda-authorizer aws-jwt-authorizer


    【解决方案1】:

    所以我所做的就是将这段代码复制到我的授权处理程序: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 类中指定 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()
    

    【讨论】:

      猜你喜欢
      • 2019-08-20
      • 2022-12-28
      • 2020-03-17
      • 2022-11-05
      • 2018-03-02
      • 2018-02-16
      • 2019-11-18
      • 2022-10-01
      • 2021-04-18
      相关资源
      最近更新 更多