Avav Smith

Avav Smith

1574910922

Angular Authentication with AWS Cognito and Amplify

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

What is GEEK

Buddha Community

Angular Authentication with  AWS Cognito and Amplify

Óscar Rondón

1578337223

Hi Avat,
is fantastic your work, but in mine case no run.

Hello, excellent tutorial.
I would like to be able to clarify some doubts, I see that with this method aws does not respond to the access token, nor refresh token. How can I consume a method exposed in the api gateway and that is protected with oauth?

I have been able to consume this gateway api but logging in with the own cogni ui.

Using amplify is it possible to have your own custom login form and log in against cognito and then use these tokens to be able to use the apis protected by oauth2?

How To Set Up Two-Factor Authentication in cPanel

What is 2FA
Two-Factor Authentication (or 2FA as it often referred to) is an extra layer of security that is used to provide users an additional level of protection when securing access to an account.
Employing a 2FA mechanism is a vast improvement in security over the Singe-Factor Authentication method of simply employing a username and password. Using this method, accounts that have 2FA enabled, require the user to enter a one-time passcode that is generated by an external application. The 2FA passcode (usually a six-digit number) is required to be input into the passcode field before access is granted. The 2FA input is usually required directly after the username and password are entered by the client.

#tutorials #2fa #access #account security #authentication #authentication method #authentication token #cli #command line #cpanel #feature manager #google authenticator #one time password #otp #otp authentication #passcode #password #passwords #qr code #security #security code #security policy #security practices #single factor authentication #time-based one-time password #totp #two factor authentication #whm

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Were  Joyce

Were Joyce

1622798007

Angular 12 + Spring Boot: JWT Authentication example | Spring Security

In this tutorial, I will show you how to build a full stack Angular 12 + Spring Boot JWT Authentication example. The back-end server uses Spring Boot with Spring Security for JWT Authentication & Role based Authorization, Spring Data JPA for interacting with database. The front-end will be built using Angular 12 with HttpInterceptor & Form validation.

Related Posts:

– Angular 12 + Spring Boot: CRUD example

– Angular 12 + Spring Boot: File upload example

– Spring Boot, MongoDB: JWT Authentication with Spring Security

Contents [hide]

#angular #full stack #spring #angular #angular 12 #authentication #authorization #jwt #login #registration #security #spring boot #spring security #token based authentication

Karine  Crooks

Karine Crooks

1595659020

Authentication with AWS Amplify & React

What is Amplify?

The open-source Amplify Framework provides the following products to build fullstack iOS, Android, Web, and React Native apps:

  • Amplify CLI - Configure all the services needed to power your backend through a simple command line interface.
  • Amplify Libraries - Use case-centric client libraries to integrate your app code with a backend using declarative interfaces.
  • Amplify UI Components - UI libraries for React, React Native, Angular, Ionic and Vue.

The Amplify Console is an AWS service that provides a git-based workflow for continuous deployment & hosting of fullstack web apps. Cloud resources created by the Amplify CLI are also visible in the Amplify Console.

Basic Setup

First, if you don’t have Node yet, download and install it.

Open https://nodejs.org/en/download

You will also need an AWS account to run Amplify. Create your AWS account if you don’t have one yet.

Amplify

Now, with the basic setup completed, let’s begin.

Install the Amplify CLI

The Amplify Command Line Interface (CLI) is a unified toolchain to create, integrate, and manage the AWS cloud services for your app.

$ sudo npm install -g @aws-amplify/cli

Configure Amplify

Sign In to your AWS account and run:

$ sudo npm install -g @aws-amplify/cli

Press Enter, Specify the Aws region, username, and Enter again.

amplify configure

Follow these steps to set up access to your AWS account: Sign in to your AWS administrator account: https://console.aws.amazon.com/

Press Enter to continue
Specify the AWS Region
? region: eu-west-2
Specify the username of the new IAM user:
? user name: amplify-user

Complete the user creation using the AWS console

https://console.aws.amazon.com/iam/home?region=undefined#/users$new?step=final&accessKey&userNames=amplify-7T7mt&permissionType=policies&policies=arn:aws:iam::aws:policy%2FAdministratorAccess

Press Enter to continue

_C_omplete the AWS Amplify user creation, download the credentials, and add the remaining information in the terminal:

Scanning for plugins…

Plugin scan successful

#amplify #react #aws #amplify-blog #cognito #programming

AWS AmplifyとAngular8を使ってCognitoでQuickSightにログインするページを作ってみる

先日、aws-samplesで公開されていたCognitoのユーザーでQuickSightにログインするサンプルを紹介するブログを書きました。 また、AmplifyとAngular8を使ってCognitoでAWSマネジメ […]

#AWS #Amazon Cognito #QuickSight #Federation #AWS Amplify #Cognito User Pools #Amplify