TIL - Cognito authorization with access tokens in API Gateway
I’m currently working on the v3 of ngnr.club, which should hopefully ship by the end of the month. As part of this, I decided to offload the user authentication process to Cognito since they have a surprisingly generous free tier.
The authentication process happens on the front end, inside the React app. When a user signs in, Cognito returns JWT tokens to the client that can then be used to authorize access to certain resources.
The issue I was having is that with the default settings of my user pool, I couldn’t authorize requests using the accessToken
returned by
After a bit of head scratching and Google-Fu, I was finally able to find the solution.
The JWT tokens you get from Cognito, contain scopes in their payload. This list of scopes has to correspond to the authorization scopes of the method integration in API Gateway for the request to go through (or at least it is my understanding at the time of writing this).
By default, when you create a basic user pool with CloudFormation like I did, the scopes
attributes of the tokens is aws.cognito.signin.user.admin
.
In order to be able to use the accessToken
instead of the idToken
, you simply have to update your api gateway method on CloudFormation
to add the AuthorizationScopes
field like so:
SomeMethod:
Type: AWS::ApiGateway::Method
Properties:
# ... properties
AuthorizationType: COGNITO_USER_POOLS
AuthorizerId: !Ref RestAPIAuthorizer
And boom !