How To Secure Your AWS API Gateway Using Cognito Authorizer

Author Image
Kelvin Onuchukwu
May 23, 2024

An API Gateway is an API management solution that interfaces between a client and some backend services. It is mostly a software service that acts as a single point of entry for client traffic into your backend services or microservices application.

So an API Gateway essentially acts as a reverse proxy, accepting requests from clients, streamlining and trasnporting them to the appropirate services.

API Gateways help with the following:

  • Security: They provide authentication, authorization and encryption.

  • Monetization: It is an easy way of monetizing your applications by providing services only to auhthenticated, paying customers.

  • Traffic management: With API Gateways you can control traffic routing, data transformation, rate limiting load balancing and flexible deployment options.

  • Monitoring: They provide logging capabilities, with real time metrics. this can be enormously helpful during a downtime event.

AWS API Gateway is a fully managed Cloud-based API gateway solution that makes it easy to create, publish and manage APIs at scale.

For the most part, if you are using AWS API Gateway, you want a way to control access to your APIs. You want to implement authentication and access control. Probably for reasons related to monetization or simply protecting your APIs from abuse.
No matter what your reasons are for wanting to protect your APIs, AWS provides two broad methods for securing access to your API Gateway - Cognito authorizer and Lambda authorizer.

An authorizer is nothing more than a validation mechanism to check if the user making the API calls have the necessary permissions to so. A request to the API gateway is first directed to the authorizer for validations before making its way to the backend services - if approved.

AWS Cognito Authorizer

AWS Cognito is a service that helps you manage user authentication, authorization, and sign-in for your web and mobile applications. It provides features like user registration, sign-in, and sign-out, as well as access control to your application resources.

This is an authorisation mechanism supported by  AWS Cognito user pools.

Cognito authorizers are a type of AWS IAM authorization mechanism that you can use to control access to your API Gateway APIs. They work by verifying the authorization tokens provided by users in their API requests against a Cognito user pool. Based on the verification results, the authorizer allows or denies access to the API.

Cognito Authorizer workflow

  1. Client Makes API Request: A client application includes an authorization token (usually an ID or access token) in the request header when calling an API Gateway API.
  2.  API Gateway Receives Request: API Gateway intercepts the request and forwards it to the Cognito authorizer.
  3.  Cognito Authorizer Validates Token: The Cognito authorizer receives the token and validates it against the configured Cognito user pool. This validation involves checking the token's signature, expiration, and issuer.
  4.  Authorization Decision: Based on the validation results, the authorizer issues an authorization response to API Gateway. The response indicates whether the token is valid and, if so, includes information about the authenticated user (e.g., username, groups).
  5.  API Gateway Allows or Denies Access: API Gateway considers the authorization response. If valid, it forwards the request to the API backend. If invalid, it returns an unauthorized error to the client.

Let's practicalze this.

Here, I am in the API gateway Console. I am creating a resource called users and a GET method for my resource.
 

I have also created a basic Node.js Lambda function with the following code:
 

export const handler = async(event) => {

    console.log('event', event)
    const response = {
        statusCode: 200,
        body: JSON.stringify('Testing Lambda from API Gateway'),
    };
    return response;
};

 

This is the Lambda function I am using for the GET method.
Now my console looks like this:
 

When I click on Test, I can see clearly that everything works great.
 

To get a URL endpoint, I am going to deploy the API. You do this by clicking on the GET method and selecting Deploy API from the Actions tab.

When I copy the URL and paste into a browser, I can clearly see that everything works great.

Now here is the problem. As it is, anybody who has the URL can access my Lambda function. What I want to do is to create an authentication mechanism such that only authorized users are allowed access.

I am going to click on the authorizers tab and create a new authorizer.
 


As you can see, there are two authroizers to choose from - lambda or Cognito, here I am selecting Cognito Authorizer.

To proceed, I will enter my user pool name. You can create your own user pool. Any user pool will do.
 

I will then click on "create".

Now we need to integrate this authorizer with our gateway.
Click on the Resources and go to the GET method. Click on the "Method Request". Select the authorizer that you just created.
It should look like this:
 

Now because we've made changes to the method, we must redeploy our API. So, click on "resources", click on the GET method and under the "Actions" tab, select Deploy API.

Here is the URL
 


But you notice that when you visit this URL now, what you get is "{"message":"Unauthorized"}".

So any person trying to access our API gateway from now on must be an authorized user - having been authorized by the Cognito authorizer using our selected user pool.

To fully test this out, use  Insomnia or Postman.
By providing the Token Source (which we added while creating the authorizer) and the access token (which you can get from the URL in the Cognito Hosted UI), we get a response from our Lambda function.

Scenario-Based Cases for Cognito Authorizers

  • Social Logins:  Cognito can be integrated with social identity providers like Facebook, Google, and Amazon to enable social logins for your app. Cognito authorizers can then be used to verify the social login tokens and grant access to authorized users.
  •  Mobile App Authentication:  For mobile apps, Cognito provides SDKs to handle user registration, sign-in, and token management. Cognito authorizers can be used to verify the tokens from your mobile app and grant access to authorized app functionalities.
  •  Custom Authentication Flows:  You can create custom authentication flows for your app using Cognito. Cognito authorizers can be used to verify tokens generated through these custom flows and grant access to authorized users.

By using Cognito authorizers, you can implement robust and secure authorization for your API Gateway APIs, ensuring that only authorized users can access your application resources.

I hope this helps you as you continue your sojourn into the Cloud.


Happy Clouding!!!


Did you like this post?

If you did, please buy me coffee 😊


Check out other posts under the same category