Authenticating API calls

For our application, authenticating API calls has an important place. Since we have a forum application, it is very normal that while some endpoints are public (for example, forum topics), some of them are private and should be authenticated and the user should be authorized before they are called. For example, only the authorized user should be able to change their personal details or password or their profile picture.

So far, it might seem to be a very simple task to implement authentication. With the knowledge we have obtained in this chapter, we could extract credentials from the HTTP request and our Lambda handler could verify them against a data layer and decide to allow or not to allow the request. However, although it is technically possible, with this approach, there are some caveats, such as the following:

The very first example of the second case is when you proxy AWS calls using API Gateway. We have already mentioned that we will be implementing an S3 API proxy to let users update their profile pictures. In this case, we will not have a Lambda backend because it is sufficient to manipulate the request and pass it through to the S3 API. On the other hand, we must be sure that an authenticated user is sending this profile picture change request and we need this user's ID to save to the S3 bucket.

At this point, API Gateway provides a very useful feature and lets us define custom authorizers for endpoints. Custom authorizers are called automatically by API Gateway just before the actual request is processed and they can allow or disallow the request. If the custom authorizer sends a block signal, the API Gateway automatically sends 4xx response code, indicating that the caller user is not allowed to call the endpoint. If the authorizer decides that the caller credentials are valid, it sends an approval signal to API Gateway along with a principal ID (for example, user ID, username, or any unique identifier for the caller entity) and this value is also passed through the backend. In this way, the Lambda function that includes the business logic does not have to deal with the authentication and authorization process.