2
votes

I'm following this tutorial to use Cognito to authorize the access to my lambda function through API Gateway.

I already create my user pool with a validated user, an API Gateway authorizer and a lambda function to login and get the token ID.

When I get the token ID with my lambda function and test it in AWS console, the authorizer returns 200, so I think it is working, but when I try to send the token to my lambda function it returns "401 Unauthorized"

My YML configuration:

teste:
  handler: handler.teste
  memorySize: 128
  events:
    - http:
        path: teste
        method: get
        authorizer:
          name: api-authorizer
          arn: arn:aws:cognito-idp:XXXXXXXXX:XXXXXXXXXX:userpool/XXXXXXX_XXXXXXX
          type: token

EDIT

I looked at AWS Console how was my lambda function and API Gateway trigger had this details:

Autorização: COGNITO_USER_POOLS
Caminho do recurso: /teste
Endpoint de API: https://XXXXXXXXX.execute-api.XXXXXXXXX.amazonaws.com/dev/teste
Estágio: dev
Método: GET

EDIT 2

I also discovery that my serverless version is 1.47 and it looks like it is the most updated although I've read some questions on Stack where they said that serverless is in 1.5

1
When you define an Authorizer, it asks the user to define a header which will be passed through along with the token. Are you sending this header? Can you share the client code executing the API call?Thales Minussi
I'm using Postman to send my request and I'm adding this header: x-api-token, which is indicated in API Gateway Authorizer test. Is that the right one?Nathália Pissuti
And what is the value for that header? What I am trying to understand is how you get this token. So by client code I meant: how are you currently authenticating against cognito? In the authorizer itself, there is a Token Source attribute which you define it yourself. Usually, people stick with Authorization. Once you are authenticated, you need to grab the token sent from Cognito and pass it on the header you defined.Thales Minussi
My authorizer isn't a lambda function, it was actually created in AWS console > API Gateway > Authorizers > Create new authorizer. Does it affect something?Nathália Pissuti
I'm using a lambda function to login into cognito and send me the token. This function is the answers I gave in my own question here: stackoverflow.com/questions/56937337/…Nathália Pissuti

1 Answers

2
votes

I read this page a few times and I realize that I wasn't using the correct way, so I change my YML code to this:

  functions:
teste:
  handler: handler.teste
  memorySize: 128
  events:
    - http:
        path: teste
        method: get
        type: COGNITO_USER_POOLS
        authorizer:
          arn: arn:aws:cognito-idp:XXXXXXXX:XXXXXXXXX:userpool/XXXXXXXX_XXXXXXXXX
          authorizerId:
            Ref: api-authorizer

And I also change my authorizer source to Authorization.