当我尝试从客户端调用AWS Amplify时,AWS SAM API Gateway引发UnauthorizedException错误

问题描述

我尝试在API网关上打开Cognito身份验证,但是当我从客户端调用端点时,总是在响应标头中得到带有x-amzn-errortype: UnauthorizedException的HTTP 401响应。它可以在我的本地计算机上运行,​​但是在我部署到AWS上之后无法运行。

在React客户端中,我基本上使用AWS Amplify进行认设置(我使用withAuthenticator HOC和API.get发送请求)

我的AWS SAM template.yaml看起来像这样:

AWstemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 10
  Api:
    Cors: '*'

Parameters:
  Environment:
    Type: String
    Description: Choose between local or AWS
    AllowedValues:
      - local
      - aws
  DDBTableName:
    Type: String
    Description: The name of the DynamoDB tablename

Resources:
###################
##    Lambdas    ##
###################
  # lambda function to fetch data from dynamodb
  GetWeeksFunction:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: functions/get-data/
      Handler: app.lambdaHandler
      Runtime: nodejs12.x
      FunctionName: GetWeeksFunction
      Events:
        GetDocument:
          Type: Api
          Properties:
            Path: /data
            Method: get
            RestApiId: !Ref MyApi
      Environment:
        Variables:
          Environment: !Ref Environment
          DDBTableName: !Ref DDBTableName
      Policies:
        - Version: '2012-10-17'
          Statement:
          - Effect: Allow
            Action:
            - logs:CreateLogGroup
            - logs:CreateLogStream
            - logs:PutLogEvents
            Resource: arn:aws:logs:*:*:*
          - Effect: Allow
            Action:
            - dynamodb:scan
            Resource: '*'

  # API stage
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: v1
      Cors:
        AllowMethods: "'*'"
        AllowHeaders: "'*'"
        AllowOrigin: "'*'"
      Auth:
        DefaultAuthorizer: MyCognitoAuthorizer
        AddDefaultAuthorizerToCorsPreflight: False
        Authorizers:
          MyCognitoAuthorizer:
            UserPoolArn: !GetAtt CognitoUserPool.Arn

##########################
##    DynamoDB Table    ##
##########################
  # DynamoDB table to store documentId,versionId and document location
  DocumentTable:
    Type: AWS::DynamoDB::Table
    Properties: 
      AttributeDeFinitions: 
        - 
          AttributeName: 'weekId'
          AttributeType: 'N'
      KeySchema: 
        - 
          AttributeName: 'weekId'
          KeyType: 'HASH'
      TableName: !Ref DDBTableName
      ProvisionedThroughput: 
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5

##########################
##   Static S3 webapp   ##
##########################
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead
      WebsiteConfiguration:
        IndexDocument: index.html
##########################
##    Cognito           ##
##########################
  # Cognito - User pool
  CognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: my_cognito_user_pool
  # Cognito - Client
  CognitoUserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      ClientName: my_cognito_client
      UserPoolId:
        Ref: CognitoUserPool
  # Cognito - Identity
  CognitoIdentityPool:
    Type: AWS::Cognito::IdentityPool
    Properties:
      IdentityPoolName: my_cognito_identity_pool
      AllowUnauthenticatedIdentities: false
      CognitoIdentityProviders:
        - ClientId:
            Ref: CognitoUserPoolClient
          ProviderName:
            Fn::GetAtt: [CognitoUserPool,ProviderName]
  # Cognito roles
  CognitoIdentityPoolRoles:
    Type: AWS::Cognito::IdentityPoolRoleAttachment
    Properties:
      IdentityPoolId:
        Ref: CognitoIdentityPool
      Roles:
        authenticated:
          Fn::GetAtt: [CognitoAuthRole,Arn]
        unauthenticated:
          Fn::GetAtt: [CognitoUnauthRole,Arn]
  CognitoAuthRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: appAuthRole
      Path: /
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Federated: "cognito-identity.amazonaws.com"
            Action:
              - "sts:AssumeRoleWithWebIdentity"
            Condition:
              StringEquals:
                "cognito-identity.amazonaws.com:aud":
                  Ref: CognitoIdentityPool
              "ForAnyValue:StringLike":
                "cognito-identity.amazonaws.com:amr": authenticated
      Policies:
        - PolicyName: "CognitoAuthorizedPolicy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: "Allow"
                Action:
                  - "mobileanalytics:PutEvents"
                  - "cognito-sync:*"
                  - "cognito-identity:*"
                Resource: "*"
              - Effect: "Allow"
                Action:
                  - "execute-api:Invoke"
                Resource: "*"
  CognitoUnauthRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: appUnauthRole
      Path: /
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Federated: "cognito-identity.amazonaws.com"
            Action:
              - "sts:AssumeRoleWithWebIdentity"
            Condition:
              StringEquals:
                "cognito-identity.amazonaws.com:aud":
                  Ref: CognitoIdentityPool
              "ForAnyValue:StringLike":
                "cognito-identity.amazonaws.com:amr": unauthenticated
      Policies:
        - PolicyName: "CognitoUnauthorizedPolicy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: "Allow"
                Action:
                  - "mobileanalytics:PutEvents"
                  - "cognito-sync:*"
                  - "cognito-identity:*"
                Resource: "*"

Outputs:
  GetDocumentApi:
    Description: API Gateway endpoint URL to get data
    Value: !Sub https://${MyApi}.execute-api.${AWS::Region}.amazonaws.com/v1/data

有人知道这里可能是什么问题吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)