I found the solution. You need to include the ID token in your API.get request, after logging in. It seems that AWS.API.get() does not include the ID token automatically, but you need to include it in the header yourself:
Docs are here: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html
Here’s a quick run-through on how to make authenticated API requests using AWS Amplify to API Gateways that use User Pools as a custom authorizer. Essentially the use case here is that you only want users who are logged into a User Pool to have access to an API endpoint.
Step 1: Enable User Pool Authorization for a Specific Serverless Function
In your serverless.yml file, you want to specify which functions you want to keep behind a user log-in “wall”:
functions:
unrestricted:
handler: src/test.unrestricted
events:
- http:
integration: lambda-proxy
path: unrestricted
method: get
cors: true
authorizer:
arn: arn:aws:cognito-idp:ap-northeast-2:118442442266:userpool/ap-northeast-2_5L5hLqjhS
Essentially the “authorizer” property allows you to specify a custom authorizer. In this case, we are using the default User Pool authorizer. the ARN is your User Pool’s ARN.
Once you deploy this function, you’ll find in your API Gateway Console that the relevant function now has an Authorizer, whose name should be (by default) your user pool.
- Make the API.get() request using idToken
As specified in the docs, you can either use accessToken or idToken. Simpler to just use idToken.
Sign in:
let idToken;
let await Auth.signIn("username", "password")
.then(data => idToken = data.signInUserSession.idToken.jwtToken);
API.get("dev", "/restrictedByUserPool", { headers: { Authorization: idToken }}).then(console.log);
That should be the gist of it. Took me quite a while to figure out, but if you read the AWS docs carefully (and really understand what customer authorizers are) then you should be good.
Feel free to ping me anytime about this. This community has helped me a ton, so I’ll try my best to give back what (limited) amount I can.