Display ad
HomeTechnologyInternetHow to Secure AWS API Gateway With Cognito User Pool - DZone...

How to Secure AWS API Gateway With Cognito User Pool – DZone Cloud

In this weblog, you’ll learn to configure an AWS API Gateway backed by an AWS Java Lambda. Next, you’ll learn to safe the API via an AWS Cognito User Pool. Enjoy!

1. Introduction

AWS API Gateway is a managed service which lets you handle your API. It has many options obtainable like creating the API, publishing it, securing it, versioning it, and so on. Some of the options can be lined on this weblog, however actually not all of them.

AWS Cognito lets you add authentication to your API. Cognito can be used on this weblog to safe your API.

As a prerequisite for following this weblog, you’ll need three AWS lambda aliases. This might be achieved by following a  previous blog. The jar-files for the lambda can be found at GitHub. Assuming that you simply use these jar-files, your beginning place is:

  • Lambda alias PROD pointing to model v1.0;
  • Lambda alias TEST pointing to model v2.0;
  • Lambda alias DEV pointing to model v3.0.

First, you’ll configure the API Gateway with out authentication, secondly, authentication via Cognito can be added.

2. Create API Gateway

The first setup you’ll create is visualized within the determine beneath.

  1. A shopper sends a request to the REST API configured within the API Gateway;
  2. The API Gateway sends the request to the lambda operate;
  3. The lambda operate executes and sends its response to the API Gateway;
  4. The API Gateway sends the response to the shopper.

In this setup, not authentication is required to entry the REST API.

2.1 Create API

Navigate to the API Gateway service and click on the Create API button. You will create a REST API thus click on the Build button.

Leave the defaults and select MyFirstAPI as API identify. Click the Create API button.

You now have an empty API created.

2.2 Create Resource

Choose within the Actions menu for Create useful resource. This will assist you to create a toddler useful resource in your API.

Give the useful resource the identify myjavalambda and click on the Create Resource button.

Via the Actions menu, select Create Method and select for a GET methodology. Next, enter the lambda operate identify MyJavaLambda within the Lambda Function discipline and click on the Save button.

A popup window is proven for granting the API Gateway the permission to invoke your lambda operate. Click the OK button so as to take action.

The API with a GET methodology is now created. Click the TEST button with a purpose to confirm that the API works. The response "Version 3" is returned.

When you navigate to the lambda definition, you’ll discover that the API Gateway is added as a set off for the lambda operate.

2.3 Create Stage Variable

When you invoke the lambda, you all the time get the event lambda model returned. However, you probably did create aliases for DEV, TEST, PROD. You can create totally different phases of your API for invoking every alias. You will achieve this via a stage variable. Click the Integration Request hyperlink within the GET – Method Execution display screen. Add the textual content :$stageVariables.lambdaAlias to the lambda operate identify.

Clicking the v-icon will present a popup for executing a CLI command for including the mandatory permissions to your lambda operate. Execute the CLI command the place you change $stageVariables.lambdaAlias with every alias (DEV, TEST, PROD).

When you wish to take a look at the GET methodology, you’ll discover that an additional discipline is out there with a purpose to enter the lambda alias (it is perhaps that you want to refresh the web page with a purpose to make it seen). Enter after eachother DEV, TEST, PROD and a special response can be returned.

2.4 Deploy API and Create Stages

In this paragraph, you’ll create totally different phases for every alias. This means, it is going to be attainable to make your API obtainable at totally different URL’s for every alias.

First step is to deploy the API so that it’s going to change into obtainable to the surface world. In the Actions menu, select Deploy API. Choose [New Stage] as Deployment stage and dev as Stage identify. Click the Deploy button.

Navigate to the Stage Variables tab and add a stage variable lambdaAlias with worth DEV.

Now you may entry the GET methodology by way of the dev URL (don’t forget so as to add the useful resource myjavalambda to the URL). As anticipated, “Version 3” is returned as a response.

$ curl https://irysdyxhm2.execute-api.eu-west-3.amazonaws.com/dev/myjavalambda
"Version 3"

Create phases for take a look at and prod. Navigate within the left menu to the Stages web page and click on the Create button.

Give the Stage identify the worth take a look at and select the newest deployment. Click the Create button.

Again, add the stage variable similar to you probably did for the dev stage. Only the worth can be TEST this time.

Finally, create a prod stage in an analogous means.

2.5 Change Lambda Alias

When you alter the model of a lambda alias, this transformation can be made seen instantly on the specified stage. Navigate to the lambda service to the lambda operate. Change the model of the PROD alias to the model of the TEST alias and execute the prod URL. It returns “Version 2” as a substitute of “Version 1”.

$ curl https://irysdyxhm2.execute-api.eu-west-3.amazonaws.com/prod/myjavalambda
"Version 2"

2.6 Change Response

API Gateway has plenty of options. One characteristic is to vary the response acquired from the lambda operate.

Click the Integration Response hyperlink within the GET – Method Execution display screen (Resources part). Click the arrow with a purpose to develop the primary report.

In the Mapping Templates part, depart the Content-type to the default and click on software/json hyperlink.

Choose Empty as Generate template and add the next within the textual content field.

#set($inputRoot = $enter.path('$'))
 
    "newVersion": "$inputRoot"

This will solely convert the returned textual content “Version 2” to a JSON response. Click the Save button.

Deploy the API to e.g. the prod stage and invoke the URL. This time, a JSON formatted response is returned. This might be a option to change the response if you end up not capable of change the response of the lambda itself or as a short lived fast repair.

$ curl https://irysdyxhm2.execute-api.eu-west-3.amazonaws.com/prod/myjavalambda
 
    "newVersion": "Version 2"

3. Secure API

In this part, authentication by way of Cognito can be added to the setup.

  1. A shopper first logs in by way of Cognito (a shopper login can be configured);
  2. After profitable login, Cognito returns an id_token to the shopper;
  3. The shopper sends a request to the API Gateway with the acquired id_token;
  4. The API Gateway verifies in Cognito whether or not the id_token is legitimate;
  5. Cognito will return to API Gateway successful response when the id_token is legitimate;
  6. The API Gateway sends the request to the lambda operate;
  7. The lambda operate executes and sends its response to the API Gateway;
  8. The API Gateway sends the response to the shopper.

3.1 Create Cognito User Pool

Navigate to the Cognito service and click on Manage User Pools. In the subsequent display screen, click on the Create a consumer pool button.

Enter the identify MyFirstUserPool as Pool identify and you’ll depart the default settings for now. Therefore, click on the Review defaults hyperlink and within the subsequent display screen, click on the Create pool button.

3.2 Create App Client

In the left menu, click on App shoppers and click on the Add an app shopper hyperlink.

Execute the next steps and on the finish click on the Create app shopper button:

  • Disable Generate shopper secret
  • In the Auth Flows Configuration part solely allow Enable uername password primarily based authentication

Navigate to the App shopper settings part within the left menu. Execute the next steps and click on the Save adjustments button. Note that this won’t be manufacturing prepared settings, for extra data see the official AWS documentation.

  • Enable Cognito User Pool
  • Enter a Callback URL, this can be essential to retrieve the ID token
  • Enable within the Allowed OAuth Flows the merchandise Implicit grant
  • Enable within the Allowed OAuth Scopes the openid merchandise

Navigate to the Domain identify part within the left menu. Choose a singular area identify (click on the Check availability button with a purpose to confirm whether or not it’s nonetheless obtainable) and click on the Save adjustments button.

3.3 Create User

You now have a UI obtainable the place you may create a consumer. Navigate within the left menu to App shopper settings, navigate to the underside of the web page and click on the Launch Hosted UI hyperlink. A login display screen is proven, click on the Sign up hyperlink.

Fill in your consumer identify, mail, password and click on the Sign up button. Next, a mail is distributed to you with a verification code which must be entered within the subsequent popup with a purpose to verify the account.

When you navigate to the Users and teams part within the left menu of the User Pool, you’ll discover that one consumer is created on this User Pool with standing CONFIRMED.

3.4 Create Authorizer in API

Navigate to the API Gateway service to your API. In the left menu select Authorizers and click on the Create New Authorizer button. Give it the identify MyAuthorizer, select Cognito as Type and choose the Cognito User Pool MyFirstUserPool. Finally, select the identify Authorizaton for the header parameter which can include the ID token. Click the Create button.

3.5 Add Authorizer to Request

In the API Gateway, navigate to the Resources part to the GET request and click on the Method Request hyperlink. Choose MyAuthorizer as Authorization setting. If it isn’t obtainable as an choice to select from, refresh the web page first. And don’t forget to click on the v-icon, in any other case the change just isn’t saved.

Finally, deploy the API to the dev stage.

3.6 Test the API

In order to check whether or not the configuration works, you’re going to execute some steps.

First, navigate to the Cognito User Pool, select within the left menu for App shopper settings, scroll right down to the underside of the web page and click on the Launch Hosted UI hyperlink. Sign in with the consumer you created.

You are redirected to the callback URL you configured and this URL now incorporates some additional parameters:

https://mydeveloperplanet.com/#id_token=<the ID token>&access_token=<the entry token>&expires_in=3600&token_type=Bearer

Copy the worth of the ID token.

Navigate to the API Gateway service to your API. Select the GET methodology of the dev stage within the Stages part. Here you will discover the URL of the dev stage. Execute the next command the place you change <the ID token> with the token you copied and change the URL with your individual URL.

$ curl --header "Authorization: <the ID token>" https://irysdyxhm2.execute-api.eu-west-3.amazonaws.com/dev/myjavalambda

The response is a profitable response of the dev surroundings:

 
    "newVersion": "Version 3"

Of course, the above guide actions accomplished, are in actual life executed by a shopper software.

When you will have made a mistake with for instance the ID token, the response can be an entry denied message.

"Message":"Access Denied"

4. Conclusion

In this weblog, you realized tips on how to setup a primary API Gateway with authentication by way of a Cognito User Pool. It requires some effort to create the setup, however as soon as that is accomplished, plenty of performance is out there out-of-the-box.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular