Securing Serverless Applications With SMS Two-Factor Authentication
In this article we will build a JWT authorization application on Amazon Web Services with SMS Two Factor authentication enabled using the Java Spring framework.
Architecture
New users can be registered to the application by sending a POST request to the /register path.
Example Request:
curl --location --request POST '{base_url}/register' \
--header 'Content-Type: application/json' \
--data-raw '{
"firstName": "Cem",
"lastName": "Onan",
"email": "test@example.com",
"password": "Test1234",
"phoneNumber": "+905555555555"
}'
Example Response:
Whenever a registered user attempts to log in, the first user’s credentials are checked to see if they are valid. Then a new OTP token is issued and sent to the client via SMS.
OTP token length is by default set to be 4 digits long. But it can be changed by overriding SAM template parameters.
Example Request:
curl --location --request POST '{base_url}/login' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "test@example.com",
"password": "Test1234"
}'
Example Response:
The client can send a POST request to /otp/{otpId}/verify the path to verify its OTP token to get the JWT token.
OTP tokens should be verified 120 seconds after they are sent. This expiration time can also be changed in SAM template parameters.
Also whenever an OTP token is verified it’s marked as used and gets expired regardless of whether its expiration date is over or not.
Example Request:
curl --location --request POST '{base_url}/otp/99f07ea1-bdfa-4839-82e7-15ff12c143ef/verify' \
--header 'Content-Type: application/json' \
--data-raw '{
"otp": 3409
}'
Example Response:
Deployment
This application consists of resources such as Lambda functions, Secrets Manager secrets, IAM roles and permission policies, DynamoDB tables, etc.
For deploying all these resources on the cloud automatically, we’ve used SAM templates as our Infrastructure as Code tool.
After you’ve made your changes to template parameters you can deploy the application on your AWS account by running the following commands in the next order:
$ sam build$ sam deploy --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND
Links
You can find the code repository at the following link:
https://github.com/onanmco/otp-application
References
[1] https://www.twilio.com/docs/libraries/reference/twilio-java/ (2022–09–18)
[2] https://docs.aws.amazon.com/code-samples/latest/catalog/code-catalog-javav2-example_code-dynamodb.html (2022–09–18)
[3] https://docs.aws.amazon.com/cloudformation/index.html (2022–09–18)
[4] https://cloud.spring.io/spring-cloud-function/reference/html/spring-cloud-function.html (2022–09–18)
[5] https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/ (2022–09–18)