AWS Cognito Auth with Phone Number OTP just like firebase, without Amplify

5.4k Views Asked by At

I am trying to enable login & Sign Up with Phone Number + OTP for a website (not Mobile) just like Firebase Auth offers.

I have looked up endless tutorials, almost all of which require AWS Amplify, which then requires knowing React/Angular/Vue (I'm not a front end developer). I followed tutorials like this one (https://techinscribed.com/passwordless-phone-number-authentication-using-aws-amplify-cognito/) and have created all the Lambda Functions, Cognito UserPools as stated in the tutorial. My roadblock is that it requires Amplify, and I just want to use vanilla JavaScript.

So I downloaded the AWS SDK builder with:

  • AWS.CognitoIdentity
  • AWS.CognitoIdentityServiceProvider
  • AWS.CognitoSync

I am using Zappa with Flask (serverless) to render HTML + JS to the user. I have everything else configured with API Gateway for the backend. All I need to do is authenticate users and generate sessions tokens for authenticated users, allowing access to their personal data, (like saved info, favorites, etc).

I am praying for someone to help me figure out how I can authenticate my users and generate the session/JWT tokens for my users. Any guidance would be appreciated.

2

There are 2 best solutions below

2
On BEST ANSWER

AWS Amplify is just a wrapper around the core AWS services. The goal is to provide a boilerplate that takes care of the common access patterns. You don't have to use framework if you don't want to and can use the core services directly.

Before I point you to these low level APIs, it's worth noting that Amplify does have vanilla JS APIs as well. Refer the official docs here. You can handle authentication with only JS and not worry about any frameworks.

The docs for the Authentication module can be found here.

For reference, here are the scripts for Sign-up and login:

import { Auth } from 'aws-amplify';

async function signUp() {
    try {
        const user = await Auth.signUp({
            username,
            password,
            attributes: {
                email,          // optional
                phone_number,   // optional - E.164 number convention
                // other custom attributes 
            }
        });
        console.log({ user });
    } catch (error) {
        console.log('error signing up:', error);
    }
}


async function SignIn() {
    try {
        const user = await Auth.signIn(username, password);
    } catch (error) {
        console.log('error signing in', error);
    }
}
1
On

Cotter co-founder here.

We have a simple library that allows you to send OTP verification to users via SMS/WhatsApp with Vanilla Javascript.

Guide: Sending OTP with HTML + Vanilla JS.

Working Example: in CodeSandbox (you need to add your API_KEY_ID, which you can get from the dashboard).

1. Import the library

<!-- 1️⃣ Get Cotter SDK -->
<script
  src="https://js.cotter.app/lib/cotter.js"
  type="text/javascript"
></script>

2. Make a div with id="cotter-form-container" to contain the form

<div
  id="cotter-form-container"
  style="width: 300px; height: 300px;"
></div>

3. Show the form

<!-- 3️⃣ Initialize Cotter with some config -->
<script>
  var cotter = new Cotter("<YOUR_API_KEY_ID>"); //  Specify your API KEY ID here

  cotter
    .signInWithOTP()
    .showPhoneForm()  // to send OTP to using email use .showEmailForm()
    .then(payload => console.log(payload))
    .catch(err => console.log(err));
</script>

4. Get JWT Tokens

Check your console logs, you should get a response like this:

{
    "token": {...},
    "phone": "+12345678910",
    "oauth_token": {
        "access_token": "eyJhbGciOiJFUzI1NiIsImtpZCI6I...", // use this
        "id_token": "eyJhbGciOiJFUzI1NiIsImtpZCI6IlN...",
        "refresh_token": "27322:UYO4pcA17i4sCIYD...",
        "expires_in": 3600,
        "token_type": "Bearer",
        "auth_method": "OTP"
    },
    "user": {
        "ID": "abcdefgh-abcd-abcd-abcd-f17786ed499e", // Cotter User ID
        ... // more user info
    }
}

Use the oauth_token.access_token for your sessions, here's how you can validate the JWT token.

5. Customize form

To show buttons to send the OTP via both SMS and WhatsApp, go to Dashboard > Branding.