A Comprehensive Guide to Passwordless Login with AWS Cognito and Amplify - Frontend Guide

  • Sat Jun 22 2024
  • Jazim Abbas

If you’d like to explore the code, I’ve created a repository on GitHub where you can view it in detail.

This article is the second part of a series. In the previous article, we explored setting up the backend and AWS resources using AWS Amplify, Cognito, and Lambda functions to trigger a custom Auth Flow for passwordless authentication.

In this part, we’ll delve into setting up authentication on the frontend. I'm using React, but the approach will be applicable to any frontend library or framework, such as Vue, Angular, Svelte, etc.

Introduction

I'm using React with Vite. You can easily set up your react-vite app using the following command:

npm create vite@latest

After that, you need to install two packages for Amplify:

{
  "dependencies": {
    "@aws-amplify/ui-react": "^6.1.8",
    "aws-amplify": "^6.0.28"
  }
}

There's no need to install @aws-amplify/ui-react. This package includes some helpers like Context Provider that handle authentication out of the box. You just need to wrap the Provider around the root App component, and everything will be handled by this package. If you're concerned about the JavaScript bundle size, you can simply omit this package. You can use the aws-amplify package to implement authentication and everything else. I'll use the @aws-amplify/ui-react package as it simplifies our authentication process. I don't want to delve into implementation details further, which is why I've chosen this package.

However, if you want me to cover authentication using only the aws-amplify package, please let me know in the comment section, and I'll consider writing an article on that as well. But for now, it's outside the scope of this article.

Amplify Setup and Configurations

import { Amplify } from "aws-amplify";
import awsConfig from "./aws-exports";
import { Authenticator, useAuthenticator } from "@aws-amplify/ui-react";
import { Auth } from "./components/Auth";
import { Home } from "./components/Home";

Amplify.configure(awsConfig);

export default function App() {
  return (
    <Authenticator.Provider>
      <AppLoad />
    </Authenticator.Provider>
  );
}

function AppLoad() {
  const { authStatus } = useAuthenticator((context) => [context.authStatus]);

  if (authStatus === "configuring") return <p>Loading ...</p>;
  else if (authStatus === "unauthenticated") return <Auth />;
  return <Home />;
}

The line Amplify.configure(awsConfig) is crucial; make sure you've included it. This sets up Amplify with our frontend, preventing errors.

Now, where does awsConfig come from? If you check the .gitignore file, you'll notice I've added the awsConfig file there. This file contains private information about the Cognito user pool. The question arises: what content should be in that file?

/* eslint-disable */
// WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

const awsConfig = {
  aws_project_region: "us-east-1",
  aws_cognito_identity_pool_id: "us-east-1:144481c0-abcd-.....",
  aws_cognito_region: "us-east-1",
  aws_user_pools_id: "us-east-1-abcdasdas",
  aws_user_pools_web_client_id: "4qweqeqwasdasdf2e4err0v",
  oauth: {},
  aws_cognito_username_attributes: [],
  aws_cognito_social_providers: [],
  aws_cognito_signup_attributes: ["PHONE_NUMBER"],
  aws_cognito_mfa_configuration: "OFF",
  aws_cognito_mfa_types: ["SMS"],
  aws_cognito_password_protection_settings: {
    passwordPolicyMinLength: 8,
    passwordPolicyCharacters: [],
  },
  aws_cognito_verification_mechanisms: ["PHONE_NUMBER"],
};

export default awsConfig;

You don’t need to create this file manually. Fortunately, AWS Amplify will generate this file for you the first time you create AWS resources. Additionally, when any resources are updated using the Amplify CLI, running the command amplify update will automatically recreate this file and update the configurations for you. I covered how to set up AWS Amplify and create resources in the Backend Guide article. If you haven't read it yet, I recommend doing so before proceeding with this article.

UI and App Logic

I won't delve into the details here, as the implementation is straightforward. I'm simply calling the Amplify helper functions for signup and OTP verification.

import { useState } from "react";
import { registration, verifyOTP } from "../utils";

export function Auth() {
  const [tab, setTab] = useState("phone"); // phone | verification

  return (
    <div className="form-wrapper">
      <h1>Signup or Signin</h1>
      <hr />

      {tab === "phone" ? (
        <RegistrationForm onSuccess={() => setTab("verification")} />
      ) : (
        <CodeVerificationForm />
      )}
    </div>
  );
}

function RegistrationForm({ onSuccess }) {
  const [phoneNo, setPhoneNo] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async () => {
    setIsLoading(true);

    try {
      await registration(phoneNo);
      setIsLoading(false);
      onSuccess();
    } catch (err) {
      setIsLoading(false);
      console.log("Error", err);
    }
  };

  return (
    <div className="center">
      <input
        placeholder="Phone Number"
        value={phoneNo}
        onChange={(e) => setPhoneNo(e.target.value)}
      />
      <button onClick={handleSubmit} disabled={isLoading}>
        Submit
      </button>
    </div>
  );
}

function CodeVerificationForm() {
  const [code, setCode] = useState("");

  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async () => {
    setIsLoading(true);

    try {
      const { isSignedIn } = await verifyOTP(code);

      if (isSignedIn) setIsLoading(false);
      else alert("Invalid code");
    } catch (err) {
      setIsLoading(false);
      console.log("Code Verification Error", err);
    }
  };

  return (
    <div className="center">
      <input placeholder="Code" value={code} onChange={(e) => setCode(e.target.value)} />
      <button disabled={isLoading} onClick={handleSubmit}>
        Submit
      </button>
    </div>
  );
}

Cognito won't create a user unless they've registered first. Therefore, you have to create the user yourself by calling signup. So, what do we do when we call the Amplify signin helper function and encounter an error, specifically a "UserNotFoundException"? In that case, we need to call the Amplify signup helper function to create the user. Then, we need to call the signin function again so that the user can log in. You can see the implementation in the following code snippet:

import { signUp as signupApi, signIn as signinApi, confirmSignIn } from "aws-amplify/auth";

export const registration = async (phoneNumber) => {
  try {
    const result = await signinApi({
      username: phoneNumber,
      options: { authFlowType: "CUSTOM_WITHOUT_SRP" },
    });
    return result;
  } catch (err) {
    if (err.name === "UserNotFoundException") {
      await signup(phoneNumber);
      return;
    }

    throw err;
  }
};

export const verifyOTP = async (otpCode) => {
  const result = await confirmSignIn({ challengeResponse: otpCode });
  return result;
};

const signup = async (phoneNumber) => {
  // focus(1:1)
  const password = Math.random().toString(10) + "Abc#";
  await signupApi({
    username: phoneNumber,
    password,
    options: { userAttributes: { phone_number: phoneNumber } },
  });
  await registration(phoneNumber);
};

One thing to note is when we call the Amplify signup helper function, I'm generating a random password. However, this article is about password-less authentication. We're just satisfying Amplify because password is a required field; otherwise, Amplify will throw an error.

In the end, if the user successfully logs in, we simply render the Home Component, where there's a button to logout, as you can see in the following code snippet:

import { useAuthenticator } from "@aws-amplify/ui-react";

export function Home() {
  const { signOut, isPending } = useAuthenticator((context) => [
    context.signOut,
    context.isPending,
  ]);

  return (
    <div>
      <h1>HomePage</h1>
      <hr />
      <div className="home">
        <button disabled={isPending} onClick={signOut}>
          Logout
        </button>
      </div>
    </div>
  );
}

Conclusion

To summarize, AWS Cognito is a complete solution we can add any authentication flow to fulfill our application requirements. In our case password-less authentication. We are using react for this article, but you can use any framework the implementation would be same. To make the article easy to understand I am using the additional package @aws-amplify/ui-react but its totally upto you if you wanna use this package or not. You can just simple aws-amplify package or you are good to go if you are concerned about javascript bundling.