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
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.
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.
- 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:
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:
- Allow all methods if the token value is "test-token-123"
- 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:
- In the left sidebar menu, click on Authorizers:
- Click Create New Authorizer as Lambda and choose your lambda function created for authorization.
- Click Test and in the dialog box you can enter any Authorization (header) to test the authorizer:
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:
- 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:
- Change the Authorization setting and select your created authorizer and click the checkmark icon to save the change:
- 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.
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.
- 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.
- Once API gateway successfully created, then from left navigate to Authorization and select the IAM (build-in) for your API and 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.
Categories/Tags: api gateway