1574910922
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
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:
These UI components come with super handy themes but in this tutorial, we will develop our own UI components.
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.
angular-amplify-demo
(you may use any name according to your preference)Next, it will ask:
accessKeyId
: YOUR_ACCESS_KEY_IDsecretAccessKey
: 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.
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.
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.
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.
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.)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.)npm run-script build
ng serve
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.
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).
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.js
has been created inside your Angular application, which holds all the configuration related to AWS Cognito.
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.
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.
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.
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.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.
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.
Congratulations, you have been able to successfully create a fully-functioning user authentication using AWS Amplify and AWS Cognito with Angular, by:
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
1578337223
Hi Avat,
is fantastic your work, but in mine case no run.
1596078672
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?
1592807820
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
1598940617
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.
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!!!
For Installing Angular on your Machine, there are 2 prerequisites:
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.
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:
· After executing the command, Angular CLI will get installed within some time. You can check it using the following command
Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:
To create a workspace:
#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli
1622798007
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
1595659020
The open-source Amplify Framework provides the following products to build fullstack iOS, Android, Web, and React Native apps:
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.
First, if you don’t have Node yet, download and install it.
Open https://nodejs.org/en/download
Now, with the basic setup completed, let’s begin.
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
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
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
1591755971
先日、aws-samplesで公開されていたCognitoのユーザーでQuickSightにログインするサンプルを紹介するブログを書きました。 また、AmplifyとAngular8を使ってCognitoでAWSマネジメ […]
#AWS #Amazon Cognito #QuickSight #Federation #AWS Amplify #Cognito User Pools #Amplify