Custom OTP implementation via AWS Lambda, SES & DynamoDB
OTP or one time password, as the name suggests, can only be used once for logging on to a network or a service. Once used, it can’t be used again and hence provide a better security when combined with a traditional authentication mechanisms.
This article will focus on a time based implementation of an OTP mechanism, which means the OTP code will be valid for a short period of time. It must be used within the specified time window, otherwise it won’t be valid once the time period has elapsed.
The scope of code provided in this article is strictly educational and shouldn’t be used in production, at least not as it is. This is just a demonstration of an OTP workflow.
A “forgot password” workflow will be shown in this article, but it can be further extended into dozens of different scenarios.
This project will use serverless
framework for managing its AWS application lifecycle. If you don’t have serverless
, run the following command to install it globally:
$ npm install -g serverless
Setting up the project
# Create your new serverless project$ serverless# and follow the instruction
# after that move into new project directory$ cd project-name
serverless.yml
should look something like this:
- This project has three policies: dynamodb access to store and retrieve user’s data , lambda execution to execute functions and ses access to send emails.
- Two functions:
generate
andreset
which are accessible via api gateway endpointsgenerate-otp
andreset-password
respectively. - It also sets up a DynamoDB resource
userTable
, which will hold users information.
It is assumed that you have already populated table with couple of users and also added those addresses as verified emails in AWS SES.
Function to generate OTP
Reset password Function
helper functions:
To deploy the project, run the following command in the root directory of your project:
$ serverless deploy
Once deployed successfully, lambda functions will be created and exposed via api endpoints.
Workflow
To start the “forgot password” workflow, simply call the generate-otp
endpoint and provide it with an email address:
$ curl -X GET 'https://your-aws-api-uri/generate-otp/<email>' -H 'accept: application/json'
If the function executed successfully, an OTP should be sent to the email provided. Once you have the code, make a POST
request to the reset
endpoint to reset the password.
$ curl -X POST 'https://your-aws-api-uri/reset' -H 'Content-Type: application/json' -d '{"email":"<email-address>", "otp":"<otp-code>", "password": "<new-password>"}'
This POST
request will set up a new password for the user.
Conclusion
This article explains how an OTP mechanism can be leveraged in any application workflow and make it more secure.