微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Lambda Authorizer的AWS Cognito和Websocket Api

如何解决使用Lambda Authorizer的AWS Cognito和Websocket Api

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

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类中指定如下所示的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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。