Search code examples
aws-api-gatewayamazon-cognitochalice

Api created with Chalice and a Cognito authorizer returns “Unauthorized”


I'm trying to integrate Cognito using the built-in login dialog with AWS Chalice. This is what I tried:

# This passes in correct arn for my pool, not xxxx
authorizer = CognitoUserPoolAuthorizer(
    'end_users_dev', provider_arns=['arn:aws:cognito-idp:us-west-2:xxxx])

@app.route('/test', cors=True, authorizer=authorizer)
def test():
    return {"result": "Success with authorizer"}

@app.route('/test2', cors=True)
def test2():
    return {"result": "Success without authorizer"}

The second method (test2) works but the first method (test) returns (as expected):

{
    "message": "Unauthorized"
}

Now I attempt to make the test with authorization work by passing in a header:

Authorization: <the token I get passed in from the 
built in login page callback as "id_token">

I can verify the JWT token contents and signature manually and that the user pool is showing up in API Gateway as "Authorization" for the test resource, but I'm still getting the same "Unauthorized" message. What am I missing?

(Note: I also posted this at https://forums.aws.amazon.com/message.jspa?messageID=871715#871715 but haven't received any response in 2 days)


Solution

  • I would check to make sure your IAM policy chalice is running allows access to cognito.

    You can add these as needed from the AmazonCognitoPowerUser policy to your policy.

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "cognito-identity:*",
                    "cognito-idp:*",
                    "cognito-sync:*",
                    "iam:ListRoles",
                    "iam:ListOpenIdConnectProviders",
                    "sns:ListPlatformApplications"
                ],
                "Resource": "*"
            }
        ]
    }
    

    As see at the link below "

    Whenever your application is deployed using chalice, the auto generated policy is written to disk at /.chalice/policy.json. When you run the chalice deploy command, you can also specify the --no-autogen-policy option. Doing so will result in the chalice CLI loading the /.chalice/policy.json file and using that file as the policy for the IAM role. You can manually edit this file and specify --no-autogen-policy if you'd like to have full control over what IAM policy to associate with the IAM role.

    "

    As seen under the policy section here: https://github.com/aws/chalice

    $ chalice gen-policy
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Action": [
            "s3:ListAllMyBuckets"
          ],
          "Resource": [
            "*"
          ],
          "Effect": "Allow",
          "Sid": "9155de6ad1d74e4c8b1448255770e60c"
        }
      ]
    }