Securing API access

To begin securing API access, go to API Gateway console, choose the RESTful API that we built in the previous chapters, and click on Authorizers from the navigation bar:

Click on the Create New Authorizer button and select Cognito. Then, select the user pool that we created earlier and set the token source field to Authorization. This defines the name of the incoming request header containing the API caller's identity token for Authorization:

Once the form has been filled in, click on Create to integrate the Cognito User Pool with the API Gateway:

You can now secure all of the endpoints, for example, in order to secure the endpoint responsible for listing all movies. Click on the corresponding GET method under the /movies resource:

Click on the Method Request box, then on Authorization, and select the user pool we created previously:

Leave the OAuth Scopes option as None, and repeat the preceding procedure for the remaining methods to secure them:

Once done, redeploy the API and point your browser to the API Gateway invocation URL:

This time, the endpoint is secured and requires authentication. You can confirm the behavior by checking the frontend we built previously. If you inspect the network requests, the API Gateway request should return a 401 Unauthorised error:

In order to fix this error, we will need to update the client (web application) to do the following:

The identity token returned has an expiration date of 1 hour. Once expired, you need to use a refresh token to refresh the session.