Passwordless API using Cognito and Serverless framework
A base API to develop your own passwordless secured application using AWS Cognito and Serverless framework.
Passwordless applications allow users to log without the need to remember a password. For this kind of apps, users enter their mobile phone number or email address and receive an OTP (one-time code) or link, which they can then use to log in.
Cognito does not support passwordless as authentication method, instead allows you handle the authentication process using triggers (lambda functions) and define your own authentication challenge:
You can find more information about triggers and passwordless:
I have developed an application that could be use as a base or reference for your own passwordless secured application. The authentication method uses user’s mobile phone to verify them and grant permissions to secured endpoints. This stack has been developed using:
- AWS Cognito as authentication handler.
- Serverless Framework as deployment cloud manager for AWS services and lambdas.
- Python as Programming language for lambda functions.
In order to achieve a customizable authentication API some endpoints were developed:
- /sign_up: Creates an user in Cognito and sends a custom challenge (OTP) to user’s mobile phone. User has 1 min to answer the challenge.
- /sign_in: Verifies the OTP that was sent to the user’s mobile phone. Provided token has 1 hour as expiration length.
- /refresh_token: Refreshes an expired token.
- /secured/call: Just returns all parameters you sent.
Let’s deploy this stack
First, you will need an AWS account and a user with a policy described in lambda-executor-policy.json
All required resources (Lambdas, Api Gateway, Cognito Pool, Cognito Pool Client, Roles, Policies) are described in serverless.yml
After “pl-deploy” (readme) or “serverless deploy”, a stack will be deployed with all required resources.
Let’s test our secured endpoint
You can use postman for importing the schema test:
/sign_up: Returns a cognito user with a temporal session (1 min), also it sends a SMS to the phone_number.
/sign_in: returns an AccessToken after of success OTP validation.
/secured_call: returns all parameters you sent. Use AuthenticationResult.AccessToken from /sign_in request.
All resources you can find them in my repo
- Twitter: @PalituxD2Code
- Github: @PalituxD
- Linkedin: @pjatocheseminario
Referenced documents/resources:
https://auth0.com/docs/connections/passwordless/guides/sms-otp
Special reference:
Thankful to Mahfuzul Alam for his post: https://medium.com/@mahfuzcse12/building-restful-apis-part-1-of-3-serverless-aws-cognito-user-pools-207917a38074