FurkanO
FurkanO

Reputation: 7308

Serverless function with authorizer arn provided returns 401

I am using serverless.

When I setup one of my functions as the following, which includes authorizer, on the client, I receive 401.

However when I remove it, there are no problems.

provider:
  name: aws
  runtime: nodejs8.10
  region: eu-west-1
  environment:
    USER_POOL_ARN: "arn:aws:cognito-idp:eu-west-1:974280.....:userpool/eu-west-1........"

functions:
  create:
    handler: handlers/create.main
    events:
      - http:
          path: create
          method: post
          cors: true
          authorizer:
            type: COGNITO_USER_POOLS
            name: serviceBAuthFunc
            arn: ${self:provider.environment.USER_POOL_ARN}

On the client, I expect a logged in user of the same user pool could get expected response. However it returns 401.

Any help is appreciated. Thanks.

Upvotes: 0

Views: 509

Answers (1)

FurkanO
FurkanO

Reputation: 7308

After desperate hours spent, I have come up with the solution.

For anyone who comes across the same issue, here is a solution that worked for me.


  1. Add integration: lambda after cors: true (though the order doesn't matter).

Below is just demonstrating that.

functions:
  create:
    handler: handlers/create.main
    events:
      - http:
          path: create
          method: post
          cors: true
          integration: lambda   // this solves the problem
          authorizer:
            type: COGNITO_USER_POOLS
            name: serviceBAuthFunc
            arn: ${self:provider.environment.USER_POOL_ARN}

  1. Send Authorization header with the value of Auth.currentSession().idToken.jwtToken while making the request.

Below is an example for sending headers using API of @aws-amplify/api and Auth of @aws-amplify/auth.

const currentSession = await Auth.currentSession() 
await API.post(
  'your-endpoint-name', 
  "/your-endpoint-path/..",
  {
    headers: {
      'Authorization': currentSession.idToken.jwtToken
    }
  }
)

Upvotes: 1

Related Questions