Angular Authentication with AWS Cognito and Amplify

Angular Authentication with  AWS Cognito and Amplify

Angular Authentication with AWS Cognito and Amplify. You have been able to successfully create a fully-functioning user authentication using AWS Amplify and AWS Cognito with Angular

In this article, we will be looking at implementing a serverlesssolution with the AWS Amplify library with Angular8 applications.

We will be creating a fully-functioning user authentication that includes user signup, verifying the email, sign in, and sign out. To make all these things happen we will be using AWS Cognito, a handy service provided by AWS.

To get started with that, an AWS account is required and if you don’t have an account, you can create a free account at AWS. If you already have an account, you are good to go.

TL;DR

What Is Amplify?

Amplify is an open-source library that helps you to easily build a flexible, reliable, and scalable serverless back end and integrate it with your front end. This was first launched in November at AWS re:Invent 2017.

“An opinionated, category-based client framework for building scalable mobile and web apps” — AWS

The Amplify framework consists of three key features:

  • Libraries: Come with a set of comprehensive libraries for JavaScript, Android, and iOS associated with cloud services, such as analytics, authentication, storage, notifications, REST, and GraphQL APIs, AR/VR.
  • Amplify CLI: Command-line tool for configuring and managing serverless infrastructures on AWS.
  • UI components: Set of framework-specific cool UI components for React, React Native, Angular, Ionic, and Vue for authentication, photo picker, etc. to make your developments easy.

These UI components come with super handy themes but in this tutorial, we will develop our own UI components.

Let’s Start

To get started, first, we need to install and configure the AWS Amplify CLI on our local machine. We will use npm to install the CLI and this will require Node.js and npm installed on your machine

Make sure your Node version is at least 8.x.x or higher and your npm version is 5.x.x or higher. If not, you need to upgrade your Node and npm to meet at least the minimum requirements.

To install the Amplify CLI in your terminal, simply run the following command, this will globally install the CLI on your local machine:

npm install -g @aws-amplify/cli

Once you’ve installed the CLI, you need to configure it by creating an IAM user to create and manage your AWS resources. To do that, simply run:

amplify configure

This process will take you through several steps.

  • This will open up the AWS console in your browser and you need to log in to your account and once you are done, you need to press enter in the terminal to continue the process.
  • Next, it will ask you to specify the AWS region: us-east-1 (I’m selecting us-east-1, North Virginia as my region, this may vary according to your region).
  • Next, it will ask you to specify the username of the new IAM user: angular-amplify-demo (you may use any name according to your preference)
  • As soon as you hit the enter, it will redirect you to the IAM management console. You can click next to complete creating the user and we will leave the default settings and permissions. You can head over to the terminal and hit enter to continue.

Next, it will ask:

  • accessKeyId: YOUR_ACCESS_KEY_ID
  • secretAccessKey: YOUR_SECRET_ACCESS_KEY

(You can grab these keys from your IAM user.)

Next, it will ask for a profile name: (default) and I’m leaving this as default, but you can give a profile name for this.

This will create/update the AWS profile on your local machine that is associated with the above accessKeyId and secretAccessKey. With this step, you have successfully set up the new user.

Alternatively, you can watch a video tutorial about the configuration process.

Next step…

Congratulations!

With this, you have now successfully installed and configured AWS Amplify on your local machine.

Creating the Angular Project

Next, we need to create our Angular project. I will be using the Angular CLI to generate a new Angular app and for that, you need to have the Angular CLI installed on your machine.

If you don’t, simply run the below command to install the Angular CLI globally:

npm install -g @angular/cli

To create and run a new app, simply run:

ng new aws-amplify-cognito-authentication
cd aws-amplify-cognito-authentication
ng serve

This will start your application and you can navigate to localhost:4200 from yous browser to open the application.

Install the Amplify Libraries

To get started with Amplify, we need to install the aws-amplify and aws-amplify-angular libraries as dependencies of our Angular application.

The aws-amplify-angular package is a set of Angular components and an Angular provider that helps integrate your application with the AWS Amplify library. It supports Angular 5.0 or above.

Configure the Back End

Now, we need to configure our back end for the project and enable authentication with Amazon Cognito user pools. To initialize the back-end project, simply run:

amplify init

And this will take you through a series of questions that are required to set up our back end.

  • Choose your default editor: Visual Studio Code. (You can choose the code editor that you are using.)
  • Choose the type of app that you’re using: JavaScript.
  • Which JavaScript framework are you using: Angular.
  • Source directory path: src.(You need to specify the source directory path of your project, I will accept the default by hitting the enter as src is our source directory.)
  • Destination directory path: dist/aws-amplify-cognito-authentication. (By default, Angular will create a subfolder with the same name, therefore, make sure to specify the subfolder as the destination directory path.)
  • Build command: npm run-script build
  • Start command: ng serve
  • Do you want to use an AWS profile? Yes.
  • Please choose the profile you want to use: default.(If you gave a name to your profile during the Amplify configuration process, make sure to select that name as your profile.)

And with that, it will take some time to initialize the project in the cloud and once done, you will see a successful message in your terminal with a bunch of other information.

Now we have successfully configured our back end.

Then, we need to configure AWS Cognito by creating an Amazon Cognito user pool, which is a full-featured user-directory service that helps us to handle our user registration and authentication.

To start with that, simply run the command:

amplify auth add

And again, this will take you through a series of questions that are required to set up our user pools.

  • Do you want to use the default authentication and security configuration: Yes, use the default configuration.

But I will choose the default configuration so that it immediately configures Cognito locally. Now we need to publish our configurations to the cloud so we can start using the service.

To do that, simply run:

amplify publish

This will show you a summary of your configuration in a tabular view and you can confirm by saying: “Yes”.

This process will take some time to create our Cognito user pool and Congito identity pool and once done, it will show a success message in your terminal.

You can visit your AWS console to check if the user pool has successfully been created (make sure you have selected the correct region).

This is image title

What’s Next?

Now that we are all set with our back end, we need to configure our front-end application for the authentication process.

Now, if you have noticed, a new file called aws-exports.jshas been created inside your Angular application, which holds all the configuration related to AWS Cognito.

This is image title

As the next step, we need to import these configurations to our app. In your main.ts file, you need to add the following imports:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import Amplify from 'aws-amplify';
import awsconfig from './aws-exports'; 

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

Amplify.configure(awsconfig);

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

main.ts

With Angular 6+, the Angular team decided to remove the support for “global” and “process” variables in the browser, therefore, all the Angular 6+ applications don’t include shims for that.

To add the support, you need to add the following code in your polyfills.ts file:

(window as any).global = window;
(window as any).process = {
  env: { DEBUG: undefined },
};

polyfills.ts

Next, we need to include the “node” package that should be included in the types compiler option in your src/tsconfig.app.json file to work with aws-js-sdk.

"compilerOptions": {
    "types" : ["node"]
}

All set to go, let’s register our first user in the AWS Cognito pool.

Sign Up

To send our user object to Cognito, your need to import the aws-amplify library to your component.

import { Auth } from 'aws-amplify';

To create a new user in your user pool:

 Auth.signUp(user)
      .then(data => {
        console.log(data);
        this.toVerifyEmail = true;
        this.signstatus = '';
      })
      .catch(err => console.log(err));

user-authentication.component.ts

The Auth.signUp() method takes the user object as an argument with required fields for user registration, which looks like this, in our case:

const user = {
   username,
   password,
   attributes: {
        email,
        phone_number
        // other custom attributes
      }
}

Now, when you pass the username, you have to ensure that you have set the username as the sign-in method in your Cognito user pool.

If you have selected email as your sign-in method, you need to send the user email as the username property in the user object.

You can check which attribute you have set as the sign-in method in the Cognito user pool by visiting the Attributes tab under the General settings in your Cognito user pool.

This is image title

In this example, I have set the Email address or phone number as my sign-in option.

This Auth.signUp() promise returns a data object which is a type of CognitoUser and if you successfully sign up, you will get a six-digit verification code sent to your email to verify your email address.

Verify the Email

To verify your email address:

 Auth.confirmSignUp(userName, verifycode, 
  {forceAliasCreation: true}).then(data => {
        console.log(data)
        this.toVerifyEmail = false;
        this.signstatus = 'signin'
     })
       .catch(err => console.log(err));

user-authentication.component.ts

The Auth.confirmSignUp(userName, verifyCode) promise takes two arguments:

  • userName: User name or email address that we have chosen to sign in the user. (In our case, it’s email address.)
  • verifyCode: Six-digit verification code that was sent to your email address.

Sign In

To sign in your newly created user:

Auth.signIn(user).then(user => {
      console.log(user);
    })
      .catch(err => console.log(err));

user-authentication.component.ts

The Auth.signIn(user) promise takes one argument that includes the username and password:

const_ user = {
      username,
      password
   }

And that returns the user object which will contain the challengeName and challengeParam properties that you can use to check if the user has enabled two-factor authentication, etc.

Sign Out

To sign out the user from the current session:

Auth.signOut()
    .then(data => console.log(data))
    .catch(err => console.log(err));

dashboard.component.ts

This will clear the current user session by revoking the auth token.

If you want to sign out the user from all the devices you need to pass an additional configuration to your sign-out method, like this:

Auth.signOut({ global: true })
    .then(data => console.log(data))
    .catch(err => console.log(err));

This will ensure that your user is signed out from all the devices if the user has been logged in from multiple devices.

Conclusion

Congratulations, you have been able to successfully create a fully-functioning user authentication using AWS Amplify and AWS Cognito with Angular, by:

  • Installing the AWS Amplify CLI on our local machine and configuring it with our AWS account.
  • Configuring the serverless back end with the help of the Amplify CLI and AWS Cognito cloud service for user authentication.
  • Creating an Angular 8 project using the Angular CLI.
  • Using aws-amplify libraries to sign up, confirm password, sign in, and sign out the user.

Although this article is a bit lengthy, we have still only covered the very basic features that are provided by aws-amplify library.

You can explore more features such as change password, forget password, verifying the phone number, etc. that are related to user registration by referring to the official Amplify documentation.

Additionally, here’s the complete GitHub project.

Thanks for reading!

angular javascript programming

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Install Angular - Angular Environment Setup Process

Install Angular in easy step by step process. Firstly Install Node.js & npm, then Install Angular CLI, Create workspace and Deploy your App.

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular. Angular is a Typesc

Learning JavaScript: Development Environments for JavaScript Programming

One of the nice things about learning JavaScript these days is that there is a plethora of choices for writing and running JavaScript code. In this article, I’m going to describe a few of these environments and show you the environment I’ll be using in this series of articles.

How to Build an Angular Application with Angular CLI

How to set up the Angular CLI and generate a Trivial App

Learning JavaScript: Data Types and Variables

To paraphrase the title of an old computer science textbook, “Algorithms + Data = Programs.” The first step in learning a programming language such as JavaScript is to learn what types of data the language can work with. The second step is to learn how to store that data in variables. In this article I’ll discuss the different types of data you can work with in a JavaScript program and how to create and use variables to store and manipulate that data.