SAM Cognito authorization error

0

My template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-myshop
  
  Sample SAM Template for sam-myshop

Globals:
  Function:
    Timeout: 5
    MemorySize: 128

Parameters:
  CognitoDomain:
    Type: String
    MinLength: "3"
    MaxLength: "63"
    AllowedPattern: ^[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?$
    Description: Enter a string. Must be alpha numeric 3-63 in length.

Resources:
  UserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      AliasAttributes:
        - email
      AutoVerifiedAttributes:
        - email
      EmailConfiguration:
        EmailSendingAccount: COGNITO_DEFAULT
        SourceArn: <ARN of SES>
      UserPoolName: !Sub ${CognitoDomain}-user-pool
      Schema:
        - Name: email
          AttributeDataType: String
          Mutable: false
          Required: true
        - Name: name
          AttributeDataType: String
          Mutable: true
          Required: true
  
  UserPoolClient:
    DependsOn: MyShopApi
    Type: AWS::Cognito::UserPoolClient
    Properties:
      UserPoolId: !Ref UserPool
      AllowedOAuthFlowsUserPoolClient: true
      CallbackURLs:
        - !Sub "https://${MyShopApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/locations"
      AllowedOAuthFlows:
        - code
        - implicit
      AllowedOAuthScopes:
        - phone
        - email
        - openid
        - profile
        - aws.cognito.signin.user.admin
      SupportedIdentityProviders:
        - COGNITO
  UserPoolDomain:
    Type: AWS::Cognito::UserPoolDomain
    Properties:
      Domain: !Ref CognitoDomain
      UserPoolId: !Ref UserPool
  
  MyShopApi:
    DependsOn: UserPool
    Type: AWS::Serverless::Api
    Properties:
      Name: MyShopApi
      StageName: Prod
      Cors:
        AllowMethods: "'*'"
        AllowHeaders: "'*'"
        AllowOrigin: "'*'"
      Auth:
        Authorizers:
          CognitoAuthorizer:
            UserPoolArn: !GetAtt UserPool.Arn
  FunctionLocations:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/locations
      Handler: locations
      Runtime: go1.x
      Architectures:
        - x86_64
      Events:
        CatchAll:
          Type: Api
          Properties:
            RestApiId: !Ref MyShopApi
            Path: /locations
            Method: GET
            Auth:
              Authorizer: CognitoAuthorizer
      Environment:
        Variables:
          PARAM1: VALUE


  FunctionUsers:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/users
      Handler: locations
      Runtime: go1.x
      Architectures:
        - x86_64
      Events:
        CatchAll:
          Type: Api
          Properties:
            RestApiId: !Ref MyShopApi
            Path: /users
            Method: GET
      Environment:
        Variables:
          PARAM1: VALUE

Outputs:
  UserPoolId:
    Description: "Id for MyShop user pool"
    Value: !Ref UserPool
  ApiEndpoint:
    Description: "URL of API"
    Value:  !Sub "https://${MyShopApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/locations"
  HostedUIURL:
    Value: !Sub https://${CognitoDomain}.auth.${AWS::Region}.amazoncognito.com/login?client_id=${UserPoolClient}&response_type=token&scope=email+openid+phone+profile&redirect_uri=https://${MyShopApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/locations
    Description: The hosted UI URL

ERROR Message

After signin, I'm getting error {"message":"Unauthorized"}

please help. thanks

asked 9 months ago242 views
1 Answer
1
Accepted Answer

I can see you're trying to use a Cognito Authorizer in the CF template, but I do not see where you are setting the scopes. Have you set that directly in API Gateway? Have you tested the APIGW with a token in the console to confirm it's working as expected?

If using SAM, check this as a resource for configuring : https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-api-cognitoauthorizer.html.

Check here for an example SAM CF template that creates a Cognito authorizer: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-controlling-access-to-apis-cognito-user-pool.html

And lastly, here's an article to help troubleshoot the {"message":"Unauthorized"} error: https://repost.aws/knowledge-center/api-gateway-cognito-401-unauthorized

profile pictureAWS
answered 9 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions