'Getting 401 Unauthorized from AWS Cognito + API Gateway when accessing from Postman or cURL

I'm trying to use the token provided by AWS Cognito to access a URL via Postman or cURL, but I'm failing to.

I have used the CloudFormation template bellow to create an API with a JWT authentication.

https://github.com/awsdocs/amazon-api-gateway-developer-guide/blob/main/cloudformation-templates/HTTP/http-with-jwt-auth.yaml

After signing-in, I can access the lambda function using the returned URL and access_token. This works just as expected:

http://<api_url>/?access_token=<token>

But when I try to access it from Postman or cURL using the access_token in the header, it outputs a 401. I was expecting to have access granted.

$ curl -v -X GET <url> -H "Authorization: <token>"
{"message":"Unauthorized"}

What have I tried:

  • I have tried to add 'Content-Type: application/json', but still get 401.
  • I have tried to use Authorization: Bearer <token>, but still get 401.
  • This template only return the access_token, but another stack I have also returns the id_token, and a 401 is returned for both
  • The complete returned header is:
HTTP/2 401
date: Thu, 03 Mar 2022 20:12:58 GMT
content-type: application/json
content-length: 26
www-authenticate: Bearer
apigw-requestid: ObIjqhmPIAMEJtA=
* Connection #0 to host <url> left intact
{"message":"Unauthorized"}


Solution 1:[1]

Answering my own question because I finally found it after a day of pain and suffering.

The JWT Authorizer is configured as:

JWTAuthorizer:
    Type: AWS::ApiGatewayV2::Authorizer
    Properties: 
      ApiId: !Ref MyAPI
      AuthorizerType: JWT
      IdentitySource: 
        - '$request.querystring.access_token'
      JwtConfiguration: 
        Audience: 
        - !Ref AppClient
        Issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${UserPool}
      Name: test-jwt-authorizer

The IdentitySource must be '$request.header.Authorization' in order for it to read from header.Authorization.

It is pretty simple, I hope nobody has to have a bad day because of it, as I had.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rvbarreto