Implement Authentication in Angular using AWS Amplify

Authentication using AWS Amplify

Table of Contents

This article is about how to implement Authentication in an Angular using AWS amplify within a very short period of time. As a specialized development company, we offer the services of custom software and dedicated team to help our customers in this kind of implementations.

So, as we saw in previous article,

AWS Amplify is a set of tools and services that enables mobile and front-end web developers to build secure, scalable full stack applications, powered by AWS.

So, Here we will explore another use case of AWS amplify, which is to add the Authentication to the angular web app using amplify in 2 ways,

1. Use pre-built UI components

2. Call Authentication APIs manually

Prerequisites:

  • Node.js version 10 or later
  • AWS Account

Create a new Angular application

Use the Angular CLI to bootstrap a new Angular app:

npx -p @angular/cli ng new amplify-app

? Would you like to add Angular routing? Y
? Which stylesheet format would you like to use? (your preferred stylesheet provider)

cd amplify-app

Angular 6+ Support

Currently, the newest versions of Angular (6+) do not include shims for ‘global’ or ‘process’ as provided in previous versions. Add the following to your src/polyfills.ts file to recreate them:

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

Initiate the Amplify project

Now that we have a running Angular app, it’s time to set up Amplify for this app

amplify init

Enter a name for the project (amplify-auth-angular)

# All AWS services you provision for your app are grouped into an "environment"
# A common naming convention is dev, staging, and production
Enter a name for the environment (dev)

# Sometimes the CLI will prompt you to edit a file, it will use this editor to open those files.
Choose your default editor

# Amplify supports JavaScript (Web & React Native), iOS, and Android apps
Choose the type of app that you're building (javascript)

What JavaScript framework are you using (angular)

Source directory path (src)

Distribution directory path (dist)
Change from dist to dist/amplify-auth-angular

Build command (npm run-script build)

Start command (ng serve or npm start)

# This is the profile you created with the `amplify configure` command in the introduction step.
Do you want to use an AWS profile

The above given process creates a file called aws-exports.js in the src directory

Install Amplify and Angular dependencies

Inside the amplify-auth-angular directory, install the Amplify Angular library and run your app:

npm install --save aws-amplify @aws-amplify/ui-angular

npm start

The @aws-amplify/ui-angular package is a set of Angular components and an Angular provider which helps integrate your application with the AWS-Amplify library.

Create authentication service in Angular

To start from scratch, run the following command in your project’s root folder:

If you want to re-use an existing authentication resource from AWS (e.g. Amazon Cognito UserPool or Identity Pool) refer to this section.

amplify add auth
? Do you want to use the default authentication and security configuration? Default configuration
? How do you want users to be able to sign in? Username
? Do you want to configure advanced settings?  No, I am done.

To deploy the service, run the push command:

amplify push

Now, the authentication service has been deployed and you can start using it. To view the deployed services in your project at any time, go to Amplify Console by running the following command:

Set AWS Amplify Config to the App

In your app’s entry point (i.e. main.ts), import and load the configuration file:

import { Amplify } from '@aws-amplify/core';
import { Auth } from '@aws-amplify/auth';
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);
Auth.configure(awsconfig);

Import AWS Amplify UI module

File: app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

/* import AmplifyUIAngularModule  */
import { AmplifyUIAngularModule } from '@aws-amplify/ui-angular';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    /* configure app with AmplifyUIAngularModule */
    AmplifyUIAngularModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Replace the content inside of app.component.ts with the following:

import { Component, ChangeDetectorRef } from '@angular/core';
import { onAuthUIStateChange, CognitoUserInterface, AuthState } from '@aws-amplify/ui-components';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'amplify-angular-auth';
  user: CognitoUserInterface | undefined;
  authState: AuthState;

  constructor(private ref: ChangeDetectorRef) {}

  ngOnInit() {
    onAuthUIStateChange((authState, authData) => {
      this.authState = authState;
      this.user = authData as CognitoUserInterface;
      this.ref.detectChanges();
    })
  }

  ngOnDestroy() {
    return onAuthUIStateChange;
  }
}

Replace the content inside of app.component.html with the html code given,

<amplify-authenticator *ngIf="authState !== 'signedin'"></amplify-authenticator>

<div *ngIf="authState === 'signedin' && user" class="App">
    <amplify-sign-out></amplify-sign-out>
    <div>Hello, {{user.username}}</div>
    <!-- This is where you application template code goes -->  
</div>

 class=

Customization of the UI with Angular

If you’d like to customize the form fields in the Authenticator Sign In or Sign Up component, you can do so by using the formFields property.

In app.component.ts add formFields variable as following:

formFields = [
      {
        type: "email",
        label: "Custom email Label",
        placeholder: "custom email placeholder",
        required: true,
      },
      {
        type: "password",
        label: "Custom Password Label",
        placeholder: "custom password placeholder",
        required: true,
      },
      {
        type: "phone_number",
        label: "Custom Phone Label",
        placeholder: "custom Phone placeholder",
        required: false,
      },
    ];
  }

File: app.componen.html

<amplify-authenticator usernameAlias="email">
  <amplify-sign-up
    slot="sign-up"
    usernameAlias="email"
    [formFields]="formFields"
  ></amplify-sign-up>
  <amplify-sign-in slot="sign-in" usernameAlias="email"></amplify-sign-in>
</amplify-authenticator>

 class=

To see more options: https://docs.amplify.aws/ui/auth/authenticator/q/framework/angular#customization

Sample Angular Code in Github

If you face any issues at any point of time, you can go through the full implementation here,

https://github.com/unimedia-technology/amplify-auth-angular

Unimedia Technology

Here at Unimedia Technology we have a team of Angular Developers that can develop your most challenging Web Single Page applications using the latest AWS technologies.

Remember that at Unimedia, we are experts in emerging technologies, so feel free to contact us if you need advice or services. We’ll be happy to assist you.

Unimedia Technology

Your software development partner

We are a cutting-edge technology consultancy specialising in custom software architecture and development.

Our Services

Sign up for our updates

Stay updated, stay informed, and let’s shape the future of tech together!

Related Reads

Dive Deeper with These Articles

Explore more of Unimedia’s expert insights and in-depth analyses in the realm of software development and technology.

Let’s make your vision a reality!

Simply fill out this form to begin your journey towards innovation and efficiency.