Follow us

AWS API Gateway Endpoint Security

When you work on serverless architecture and you expose API URL's then we always have security concern, how we could secure our serverless API's.

With AWS, in general, we create lambda function as our API code base and then we use AWS API gateway to expose lambda function as public API.

AWS API Gateway provide multiple security mechanisms to secure API gateway exposed URL's.

 

Lambda 
Authorizer 
Authorizer 
Cognito 
Authorizer 
JWT Token 
Authorizer

 

Lambda authorizer

This we should use when we want to have our own logic to generate and validate token, so you will have lambda function which will be actually validating your token, so you could say that you have stored your api token/key in DynamoDB and then you are validating them using lambda function when  api gateway request received for api call.

 

IAM authorizer

This we should use when we actually have backend/internal API calls, so like we have api gateway endpoints which are being use form your own application and there we want to validate your api gateway endpoint with IAM credential, similar like how we access any other AWS service using IAM credential.

 

Cognito authorizer

This we should use when we want to provide credential management per use being login to your platform. So you have UI and you want each user should use there own credential to access the API gateway endpoint. So basically with the help of Cognito, user get registered to Cognito user pool and then based on successful login, it access the user token from current Cognito session for that user and then that token get pass to API gateway endpoint.

 

Oauth or JWT Token on api gateway level

This we should use when we want just to use API gateway provided token (fixed token, just generate and then share with client to use). You could generate multiple token and share with client and manage throttling key wise.

 

Lambda Authorizer Demo/Example (follow below steps):

 

  • Create simple lambda function:
    • Name: HelloWorld
    • Runtime: Select Node.js

 

Sample code:

 

exports.handler = (event, context, callback) => {

  callback(null, {

    statusCode: 200,

    body: "Hello from Lambda",

  });

};

 

  • Deploy lambda function.
  • Scroll up to the Function overview panel, click Add Trigger, and select API Gateway.

Trigger configuration 
API Gateway 
application-services aws server(ess 
Add an API to your Lambda function to create an HTTP endpoint that invokes your function. API Gateway supports two 
types of RESTfu1 APIs: HTTP APIs and REST APIs. Learn more 
Create a new API or attach an existing one. 
Create an API 
API type 
O 
H •rrp API 
create an HTTP APL 
Security 
Configure the security mechanism for your API endpoint. 
Open 
O REST API 
create a REST APL 
Don't add authorization Or authentication reauirements. Anv Can invoke function with an HTTP

Note: This way the Open Security setting configures the API endpoint to not require any authentication and you will be able to easily test it from a browser.

 

  • Now copy gateway Url and hit into browser and it will give you result, so your api is working without any authentication.

HelloWorld 
Descr 
Last n 
I hou 
Add destination 
API Gateway 
+ Add trigger 
Code 
Test 
Monitor 
e Layers 
Aliases 
Configuration 
Triggers 
Versions 
C 
Funct 
oar 
Enable 
X I match 
General configuration 
Trig 
Permissions 
Destinations 
Environment variables 
Tags 
Q API Gateway 
Trigger 
API Gateway: HelloWorId-API 
API endpoint: https://pqjakhnuig.execute-api.us-west-2.amazonaws.com/defauIt/HeUoWortd 
Details

 

https://pqiakhnuig.execute-api.us-west-2.amazonaws.com/default/HelIoWorId 
Hello from Lambda

 

  • Now to create API authentication through lambda function, create another new lambda function and here I will use blue print instead of creating from scratch, so that we can get inbuilt available code for us to use.

Click on the radio button of the Use a blueprint card, search for authorizer in the search bar, and select the api-gateway-authorizer-python blueprint:

alt

Notes: The Blueprint is particularly useful because it defines a utility class named AuthPolicy. This class greatly simplifies the generation of dynamic policies for your APIs because it already implements all the required logic to allow or deny a specific API endpoint or HTTP method. For example, creating an "allow all" policy can be accomplished by the following snippet:

  • In the Code source code editor, double-click lambda_function.py, and replace the lambda_handler function with the following code:

 

def lambda_handler(event, context):

    token = event['authorizationToken'] # retrieve the Auth token

 

    principal_id = 'Test123' # fake

 

    policy = create_policy(event['methodArn'], principal_id)

 

    if event['authorizationToken'] == "test-token-123":

        policy.allowAllMethods()

    else:

        policy.denyAllMethods()

 

    return policy.build()

 

def create_policy(method_arn, principal_id):

    tmp = method_arn.split(':')

    region = tmp[3]

    account_id = tmp[4]

    api_id, stage = tmp[5].split('/')[:2]

 

    policy = AuthPolicy(principal_id, account_id)

    policy.restApiId = api_id

    policy.region = region

    policy.stage = stage

 

    return policy

This code generates a policy that will:

  1. Allow all methods if the token value is "test-token-123"
  2. Deny access to all methods otherwise
  • To save your changes to the function, at the top of the Code source function, click Deploy.

 

  • Now to add above created lambda function as authorizer of your API gateway you created first lambda function, go to API gateway console and select your HelloWorld-API created part of step 1 lambda function:

alt

  • In the left sidebar menu, click on Authorizers:
  • Click Create New Authorizer as Lambda and choose your lambda function created for authorization.

alt

  • Click Test and in the dialog box you can enter any Authorization (header) to test the authorizer:

alt

Any text other than test-token-123 will return an Denay with Effect. If you enter test-token-123 the authorization token will be accepted and the Lambda Function will generate an allow policy:

alt

  • Now to apply this authorizer with your api gateway endpoint, click on Resources on the left sidebar menu followed by ANY and lastly Method Request:

alt

 

  • Change the Authorization setting and select your created authorizer and click the checkmark icon to save the change:

alt

  • Click Actions > Deploy API to re-deploy the API
  • Now you can test your api by passing token into header, I used postman to test this api.

GET 
Authorization 
https:,//pgjakhnuig.execute-api.us-west-2.amazonaws.com/defauIt/HeIIoWorld 
Params 
Headers (I) 
Pre-request Script 
Value 
Tests 
Authorization 
test-token- 123 
Send 
Bulk Edi' 
status: 
80 dy 
Pretty 
Cookies 
Raw 
Headers (6) 
Preview 
Lambdal 
Test Results 
Hello from

 

 

API Key Authorizer Demo/Example (follow below steps):

Now, if you want to try API key instead of your lambda function, then, it quite easy:

  • While you add trigger as API gateway for your lambda function, which you want to expose as API, then select "API Key" from the security drop down instead of Open and result of that when you go and check your API gateway for that lambda then and navigate to "API Keys" from left section and you will find there API key got auto generated with default usages plan and from there copy the API key which you need to use to call your api.

Note: Instead of selecting API Key as security while you add API gateway as trigger for your lambda, you can leave it open as security drop down and letter you can enable this as well from the API gateway => Resource => Any => and then Method request and enable API Key.

Кауд 
С имшп 
ЛЮ k.ys 
AWS 
Ены“ О 
AsscoXe•6 Usage 91ans

  • Using postman to call API by passing api key.

 

 

IAM Authorizer Demo/Example (follow below steps):

 

  • In this case, I just created lambda function with default run time as node js with default source code.
  • Now navigate to API gateway console and create/build HTTP API gateway and choose lambda function you created with integration section.

API Gateway 
APIS 
Custom domain names 
vpc links 
x 
Create an API 
Step 2 
Configure routes 
Step 
Define stages 
Step 4 
Review and create 
Create an A 
Create and configure integrations 
Specify the backend services that your API will communicate with. These are called integrations. For a Lambd 
integration, API Gateway invokes the Lambda function and responds with the response from the function. Fo 
HTTP integration, API Gateway sends the request to the URL that you specify and returns the response from 
the URL. 
Integrations Info 
Lambda 
AWS Region 
us-east- 1 
Add integration 
Lambda function 
Q hellow-worldl 
X 
Remove 
Version Learn more. 
2.0

 

  • Once API gateway successfully created, then from left navigate to Authorization and select the IAM (build-in) for your API and attach authorizer.

API Gateway 
APIS 
x 
Custom domain names 
vpc links 
API: hellow-world... 
(6jsurlogyl) 
Develop 
Routes 
Authorization 
Integrations 
CORS 
Reimport 
Authorization 
Attach authorizers to routes 
Routes for hellow-world 
Q 
Search 
/hellow-world 
GET 
Manage authorizers 
No authorizer attached to GET /hellow-world 
No authorizer is attached to this route. You can either attach an existing authorizer or create and attach 
new one. 
Create and attach an authorizer 
Select existing authorizer 
IAM (built-in) 
Attach authorizer

 

  • Now to test your API gateway endpoint url, you must have AIM access key and secret key, so you could create IAM user and have required policy to invoke API gateway and lambda function execution and then you could use same your access key and secret key with postman to test your endpoint. While testing with postman, from authorization tab, you need choose AWS signature and provide access key and secret key.

GET v 
Authorization 
Type 
Access Key 
SecretKey 
AWS Region 
Service Name 
https://6jsurlogyl.execute-api.us-east-l .amazonaws.com,/hellow-world 
Params 
Clear 
Send 
Headers (5) 
Headers (4) 
Preview 
Pre-request Script 
AWS Signature 
Tests 
a ody 
Cookies 
Save helper data to request 
Test Results 
Updat 
status: 200 0K 
Pretty 
Raw 
1 
el 10 from

 

Categories/Tags: api gateway

Recent Articles

1

AWS Saving Plan - Cost optimization tips

2
3

AWS RDS Key Concepts & Why you should use it?

4
5

Open-Search/Kibana - Multi Tenancy Setup

See All Articles