Friday 8 April 2022

How to Set Up AWS Authentication UI from Amplify for an Angular Project

This post shows how to set up an Angular project that uses Amazon Web Service Cognito as the identity provider with provided Authentication UI from Amplify. At the time of writing, the Angular version is 13.2 and Amplify version is 4.3.16.

1. First make sure Angular CLI has been installed
   npm install -g @angular/cli

2. Create a new Angular project, in our example here is called angular-amplify-frontend
   ng new angular-amplify-frontend

3. Add AWS Amplify to the project and the UI module for Angular
   npm install aws-amplify
   npm install --save aws-amplify @aws-amplify/ui-angular

4. Then install Amplify CLI
   npm install -g @aws-amplify/cli

5. Initialise a new Amplify project.
   amplify init
Make sure that the AWS user account set has AdministratorAccess-Amplify permission. Otherwise, you will get this error "AccessDeniedException: User:... is not authorized to perform: amplify:CreateApp on resource".

6. Now we can add the authentication module
   amplify add auth

7. Then run
   amplify push

8. Add the following to src/polyfills.ts file to avoid error when rendering in browser:
   (window as any).global = window;
   (window as any).process = {
      env: { DEBUG: undefined },
   };

9. Import Amplify and AmplifyAuthenticatorModule modules and configuration from 'aws-exports' on app.module.ts file.
. . .
import Amplify from 'aws-amplify';
import { AmplifyAuthenticatorModule } from '@aws-amplify/ui-angular';
import awsconfig from 'src/aws-exports'

Amplify.configure(awsconfig);

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      . . .
      AmplifyAuthenticatorModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
To avoid this TypeScript error "Could not find a declaration file for module './aws-exports'. 'aws-exports.js' implicitly has an 'any' type.", create a aws-exports.d.ts file on the same level as aws-exports.js file with the following content:
   declare const awsmobile: Record<string, any>
   export default awsmobile;

10. Import authenticator stylesheet on the styles file
@import '~@aws-amplify/ui-angular/theme.css';

11. Finally put the following on app.component.html file
<amplify-authenticator>
   <ng-template amplifySlot="authenticated"
    let-user="user"
    let-signOut="signOut">
      <h1>Welcome {{ user.username }}!</h1>
      <button (click)="signOut()">Sign Out</button>
  </ng-template>
</amplify-authenticator>

Then run the project
   ng serve --o


If you got an error “bundle initial exceeded maximum budget”.
Open angular.json file on the project's root then find ‘budgets’ keyword. Then change the values for ‘maximumWarning’ and ‘maximumError’.
   "budgets": [
      {
         . . .
         "maximumWarning": "2mb",
         "maximumError": "5mb"
      }
   ]