Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork21
Application example built with Angular 20 with authentication using the Amazon Cognito service.
License
rodrigokamada/angular-amazon-cognito
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Application example built withAngular 20 with authentication using theAmazon Cognito service.
This tutorial was posted on myblog in portuguese and on theDEV Community in english.
Before you start, you need to install and configure the tools:
1. Let's create the account. Access the sitehttps://aws.amazon.com/cognito/ and click on the buttonSign up now.
2. Click on the buttonCreate a new AWS account.
3. Fill in the fieldsEmail Address,Password,Confirm password,AWS account name,Security check and click on the buttonContinue (step 1 of 5).
4. Click on the optionPersonal - for your own projects, fill in the fieldsFull Name,Phone Number,Country or Region,Address,City,State, Province or Region,Postal Code, click on the checkboxI have read and agree to the terms of the AWS Customer Agreement. and click on the buttonContinue (step 2 of 5).
5. Fill in the fieldsCredit card number,Expiration date,Cardholder's name, click on the optiondUse my contact address,CPF, fill in the fieldsTax Registration Number,Date of birth,Postal Code,Neighbothood,Tax address and click on the buttonVerify and Continue (step 3 of 5).
Note:
- Some fields may be different for your country.
6. Click on the optionText message (SMS), select an option in the fieldCountry or region code, fill in the fieldsMobile phone number,Type the characters as shown above and click on the buttonSend SMS (step 4 of 5).
7. Fill in the fieldVerify code and click on the buttonContinue (step 4 of 5).
8. Click on the optionBasic support - Free and click on the buttonComplete sign up.
9. Click on the buttonGo to the AWS Management Console.
10. Click on the optionRoot user, fill in the fieldRoot user email address and click on the buttonNext.
11. Fill in the fieldSecurity check and click on the buttonSubmit.
12. Fill in the fieldPassword and click on the buttonSign in.
13. Click on the buttonSwitch to the new Console Home.
14. Click on the menuSecurity, Identity & Compliance and on the submenuCognito.
15. Click on the linkTry out the new interface..
16. Click on the buttonCreate user pool.
17. Click on the optionEmail and click on the buttonNext.
18. Click on the optionsCognito defaults,No MFA,Enable self-service account recovery - Recommended,Email only and click on the buttonNext.
19. Click on the optionsEnable self-registration,Allow Cognito to automatically send messages to verify and confirm - Recommended,Send email message, verify email address and click on the buttonNext.
20. Click on the optionSend email with Cognito and click on the buttonNext.
21. Fill in the fieldUser pool name, click on the optionPublic client, fill in the fieldApp client name, click on the optionDon't generate a client secret and click on the buttonSign in.
22. Click on the buttonCreate user pool.
23. Click on the linkangular-cognito with the user pool name.
24. Copy the user pool ID displayed, in my case, the IDus-east-2_pptCj2gqV was displayed because this ID will be configured in the Angular application and click on the linkApp integration.
25. Copy the client ID displayed, in my case, the ID1452opnjll0ldmocs201b1oimu was displayed because this ID will be configured in the Angular application.
26. Ready! Account created, user pool ID and client ID generated.
1. Let's create the application with the Angular base structure using the@angular/cli with the route file and the SCSS style format.
ng new angular-cognito--routing true--style scssCREATE angular-cognito/README.md (1060 bytes)CREATE angular-cognito/.editorconfig (274 bytes)CREATE angular-cognito/.gitignore (548 bytes)CREATE angular-cognito/angular.json (3261 bytes)CREATE angular-cognito/package.json (1079 bytes)CREATE angular-cognito/tsconfig.json (863 bytes)CREATE angular-cognito/.browserslistrc (600 bytes)CREATE angular-cognito/karma.conf.js (1432 bytes)CREATE angular-cognito/tsconfig.app.json (287 bytes)CREATE angular-cognito/tsconfig.spec.json (333 bytes)CREATE angular-cognito/.vscode/extensions.json (130 bytes)CREATE angular-cognito/.vscode/launch.json (474 bytes)CREATE angular-cognito/.vscode/tasks.json (938 bytes)CREATE angular-cognito/src/favicon.ico (948 bytes)CREATE angular-cognito/src/index.html (300 bytes)CREATE angular-cognito/src/main.ts (372 bytes)CREATE angular-cognito/src/polyfills.ts (2338 bytes)CREATE angular-cognito/src/styles.scss (80 bytes)CREATE angular-cognito/src/test.ts (745 bytes)CREATE angular-cognito/src/assets/.gitkeep (0 bytes)CREATE angular-cognito/src/environments/environment.prod.ts (51 bytes)CREATE angular-cognito/src/environments/environment.ts (658 bytes)CREATE angular-cognito/src/app/app-routing.module.ts (245 bytes)CREATE angular-cognito/src/app/app.module.ts (393 bytes)CREATE angular-cognito/src/app/app.component.scss (0 bytes)CREATE angular-cognito/src/app/app.component.html (23364 bytes)CREATE angular-cognito/src/app/app.component.spec.ts (1100 bytes)CREATE angular-cognito/src/app/app.component.ts (220 bytes)✔ Packages installed successfully. Successfully initialized git.
2. Install and configure the Bootstrap CSS framework. Do steps 2 and 3 of the postAdding the Bootstrap CSS framework to an Angular application.
3. Configure the variablecognito.userPoolId with the Amazon Cognito User Pool ID and the variablecognito.userPoolWebClientId with the Amazon Cognito WEB Client ID in thesrc/environments/environment.ts andsrc/environments/environment.prod.ts files as below.
cognito:{userPoolId:'us-east-2_pptCj2gqV',userPoolWebClientId:'1452opnjll0ldmocs201b1oimu',},
4. Install theaws-amplify library.
npm install aws-amplify5. Change thesrc/polyfills.ts file. Add the global declaration as below. This configuration is required starting with Angular version 6.
(windowasany).global=window;
6. Create theCognitoService service.
ng generate service cognito--skip-tests=trueCREATE src/app/cognito.service.ts (136 bytes)
7. Change thesrc/app/cognito.service.ts file and add the lines as below.
import{Injectable}from'@angular/core';import{BehaviorSubject}from'rxjs';importAmplify,{Auth}from'aws-amplify';import{environment}from'../environments/environment';exportinterfaceIUser{email:string;password:string;showPassword:boolean;code:string;name:string;}@Injectable({providedIn:'root',})exportclassCognitoService{privateauthenticationSubject:BehaviorSubject<any>;constructor(){Amplify.configure({Auth:environment.cognito,});this.authenticationSubject=newBehaviorSubject<boolean>(false);}publicsignUp(user:IUser):Promise<any>{returnAuth.signUp({username:user.email,password:user.password,});}publicconfirmSignUp(user:IUser):Promise<any>{returnAuth.confirmSignUp(user.email,user.code);}publicsignIn(user:IUser):Promise<any>{returnAuth.signIn(user.email,user.password).then(()=>{this.authenticationSubject.next(true);});}publicsignOut():Promise<any>{returnAuth.signOut().then(()=>{this.authenticationSubject.next(false);});}publicisAuthenticated():Promise<boolean>{if(this.authenticationSubject.value){returnPromise.resolve(true);}else{returnthis.getUser().then((user:any)=>{if(user){returntrue;}else{returnfalse;}}).catch(()=>{returnfalse;});}}publicgetUser():Promise<any>{returnAuth.currentUserInfo();}publicupdateUser(user:IUser):Promise<any>{returnAuth.currentUserPoolUser().then((cognitoUser:any)=>{returnAuth.updateUserAttributes(cognitoUser,user);});}}
8. Create theSignUpComponent component.
ng generate component sign-up--skip-tests=trueCREATE src/app/sign-up/sign-up.component.scss (0 bytes)CREATE src/app/sign-up/sign-up.component.html (22 bytes)CREATE src/app/sign-up/sign-up.component.ts (279 bytes)UPDATE src/app/app.module.ts (638 bytes)
9. Change thesrc/app/sign-up/sign-up.component.ts file. Import theRouter andCognitoService services and create thesignUp andconfirmSignUp methods as below.
import{Component}from'@angular/core';import{Router}from'@angular/router';import{IUser,CognitoService}from'../cognito.service';@Component({selector:'app-sign-up',templateUrl:'./sign-up.component.html',styleUrls:['./sign-up.component.scss'],})exportclassSignUpComponent{loading:boolean;isConfirm:boolean;user:IUser;constructor(privaterouter:Router,privatecognitoService:CognitoService){this.loading=false;this.isConfirm=false;this.user={}asIUser;}publicsignUp():void{this.loading=true;this.cognitoService.signUp(this.user).then(()=>{this.loading=false;this.isConfirm=true;}).catch(()=>{this.loading=false;});}publicconfirmSignUp():void{this.loading=true;this.cognitoService.confirmSignUp(this.user).then(()=>{this.router.navigate(['/signIn']);}).catch(()=>{this.loading=false;});}}
10. Change thesrc/app/sign-up/sign-up.component.html file. Add the lines as below.
<divclass="row justify-content-center my-5"><divclass="col-4"><divclass="card"><divclass="card-body"*ngIf="!isConfirm"><divclass="row"><divclass="col mb-2"><labelfor="email"class="form-label">Email:</label><inputtype="email"id="email"name="email"#email="ngModel"[(ngModel)]="user.email"class="form-control form-control-sm"></div></div><divclass="row"><divclass="col mb-2"><labelfor="password"class="form-label">Password:</label><divclass="input-group input-group-sm"><input[type]="user.showPassword ? 'text' : 'password'"id="password"name="password"#password="ngModel"[(ngModel)]="user.password"class="form-control form-control-sm"><buttontype="button"class="btn btn-outline-secondary"(click)="user.showPassword = !user.showPassword"><iclass="bi"[ngClass]="{'bi-eye-fill': !user.showPassword, 'bi-eye-slash-fill': user.showPassword}"></i></button></div></div></div><divclass="row"><divclass="col d-grid"><buttontype="button"(click)="signUp()"class="btn btn-sm btn-success"[disabled]="loading"><spanclass="spinner-border spinner-border-sm"role="status"aria-hidden="true"*ngIf="loading"></span> Sign up</button></div></div></div><divclass="card-body"*ngIf="isConfirm"><divclass="row"><divclass="col mb-2"><labelfor="code"class="form-label">Code:</label><inputtype="text"id="code"name="code"#code="ngModel"[(ngModel)]="user.code"class="form-control form-control-sm"></div></div><divclass="row"><divclass="col d-grid"><buttontype="button"(click)="confirmSignUp()"class="btn btn-sm btn-success"[disabled]="loading"><spanclass="spinner-border spinner-border-sm"role="status"aria-hidden="true"*ngIf="loading"></span> Confirm</button></div></div></div></div></div></div>
11. Create theSignInComponent component.
ng generate component sign-in--skip-tests=trueCREATE src/app/sign-in/sign-in.component.scss (0 bytes)CREATE src/app/sign-in/sign-in.component.html (22 bytes)CREATE src/app/sign-in/sign-in.component.ts (279 bytes)UPDATE src/app/app.module.ts (490 bytes)
12. Change thesrc/app/sign-in/sign-in.component.ts file. Import theRouter andCognitoService service and create thesignIn method as below.
import{Component}from'@angular/core';import{Router}from'@angular/router';import{IUser,CognitoService}from'../cognito.service';@Component({selector:'app-sign-in',templateUrl:'./sign-in.component.html',styleUrls:['./sign-in.component.scss'],})exportclassSignInComponent{loading:boolean;user:IUser;constructor(privaterouter:Router,privatecognitoService:CognitoService){this.loading=false;this.user={}asIUser;}publicsignIn():void{this.loading=true;this.cognitoService.signIn(this.user).then(()=>{this.router.navigate(['/profile']);}).catch(()=>{this.loading=false;});}}
13. Change thesrc/app/sign-in/sign-in.component.html file. Add the lines as below.
<divclass="row justify-content-center my-5"><divclass="col-4"><divclass="card"><divclass="card-body"><divclass="row"><divclass="col mb-2"><labelfor="email"class="form-label">Email:</label><inputtype="email"id="email"name="email"#email="ngModel"[(ngModel)]="user.email"class="form-control form-control-sm"></div></div><divclass="row"><divclass="col mb-2"><labelfor="password"class="form-label">Password:</label><divclass="input-group input-group-sm"><input[type]="user.showPassword ? 'text' : 'password'"id="password"name="password"#password="ngModel"[(ngModel)]="user.password"class="form-control form-control-sm"><buttontype="button"class="btn btn-outline-secondary"(click)="user.showPassword = !user.showPassword"><iclass="bi"[ngClass]="{'bi-eye-fill': !user.showPassword, 'bi-eye-slash-fill': user.showPassword}"></i></button></div></div></div><divclass="row"><divclass="col d-grid"><buttontype="button"(click)="signIn()"class="btn btn-sm btn-success"[disabled]="loading"><spanclass="spinner-border spinner-border-sm"role="status"aria-hidden="true"*ngIf="loading"></span> Sign in</button></div></div></div></div></div></div>
14. Create theProfileComponent component.
ng generate component profile--skip-tests=trueCREATE src/app/profile/profile.component.scss (0 bytes)CREATE src/app/profile/profile.component.html (22 bytes)CREATE src/app/profile/profile.component.ts (280 bytes)UPDATE src/app/app.module.ts (726 bytes)
15. Change thesrc/app/profile/profile.component.ts file. Import theCognitoService service and create theupdate method as below.
import{Component,OnInit}from'@angular/core';import{IUser,CognitoService}from'../cognito.service';@Component({selector:'app-profile',templateUrl:'./profile.component.html',styleUrls:['./profile.component.scss'],})exportclassProfileComponentimplementsOnInit{loading:boolean;user:IUser;constructor(privatecognitoService:CognitoService){this.loading=false;this.user={}asIUser;}publicngOnInit():void{this.cognitoService.getUser().then((user:any)=>{this.user=user.attributes;});}publicupdate():void{this.loading=true;this.cognitoService.updateUser(this.user).then(()=>{this.loading=false;}).catch(()=>{this.loading=false;});}}
16. Change thesrc/app/profile/profile.component.html file. Add the lines as below.
<divclass="row justify-content-center my-5"><divclass="col-4"><divclass="row"><divclass="col mb-2"><labelfor="email"class="form-label">Email:</label><inputtype="email"id="email"name="email"#email="ngModel"[ngModel]="user.email"disabledclass="form-control form-control-sm"></div></div><divclass="row"><divclass="col mb-2"><labelfor="name"class="form-label">Name:</label><inputtype="text"id="name"name="name"#name="ngModel"[(ngModel)]="user.name"class="form-control form-control-sm"></div></div><divclass="row"><divclass="col d-grid"><buttontype="button"(click)="update()"class="btn btn-sm btn-dark"[disabled]="loading"><spanclass="spinner-border spinner-border-sm"role="status"aria-hidden="true"*ngIf="loading"></span> Update</button></div></div></div></div>
17. Change thesrc/app/app.component.ts file. Import theRouter andCognitoService services and create theisAuthenticated andsignOut methods as below.
import{Component,OnInit}from'@angular/core';import{Router}from'@angular/router';import{CognitoService}from'./cognito.service';@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.scss'],})exportclassAppComponentimplementsOnInit{isAuthenticated:boolean;constructor(privaterouter:Router,privatecognitoService:CognitoService){this.isAuthenticated=false;}publicngOnInit():void{this.cognitoService.isAuthenticated().then((success:boolean)=>{this.isAuthenticated=success;});}publicsignOut():void{this.cognitoService.signOut().then(()=>{this.router.navigate(['/signIn']);});}}
18. Change thesrc/app/app.component.html file and add the menu as below.
<navclass="navbar navbar-expand-sm navbar-light bg-light"><divclass="container-fluid"><aclass="navbar-brand"href="#">Angular Amazon Cognito</a><buttonclass="navbar-toggler"type="button"data-bs-toggle="collapse"data-bs-target="#navbarContent"aria-controls="navbarSupportedContent"aria-expanded="false"aria-label="Toggle navigation"><spanclass="navbar-toggler-icon"></span></button><divid="navbarContent"class="collapse navbar-collapse"><ulclass="navbar-nav me-auto mb-2 mb-lg-0"><liclass="nav-item"><aclass="nav-link"routerLink="/signUp"routerLinkActive="active"*ngIf="!isAuthenticated">Sign up</a></li><liclass="nav-item"><aclass="nav-link"routerLink="/signIn"routerLinkActive="active"*ngIf="!isAuthenticated">Sign in</a></li><liclass="nav-item"><aclass="nav-link"routerLink="/profile"routerLinkActive="active"*ngIf="isAuthenticated">Profile</a></li><liclass="nav-item"><aclass="nav-link"routerLink=""(click)="signOut()"*ngIf="isAuthenticated">Sign out</a></li></ul></div></div></nav><router-outlet></router-outlet>
19. Change thesrc/app/app-routing.module.ts file and add the routes as below.
import{NgModule}from'@angular/core';import{RouterModule,Routes}from'@angular/router';import{ProfileComponent}from'./profile/profile.component';import{SignInComponent}from'./sign-in/sign-in.component';import{SignUpComponent}from'./sign-up/sign-up.component';constroutes:Routes=[{path:'',redirectTo:'signIn',pathMatch:'full',},{path:'profile',component:ProfileComponent,},{path:'signIn',component:SignInComponent,},{path:'signUp',component:SignUpComponent,},{path:'**',redirectTo:'signIn',},];@NgModule({imports:[RouterModule.forRoot(routes),],exports:[RouterModule,],})exportclassAppRoutingModule{}
20. Change thesrc/app/app.module.ts file. Import theFormsModule module, theProfileComponent,SignInComponent,SignUpComponent components as below.
import{NgModule}from'@angular/core';import{BrowserModule}from'@angular/platform-browser';import{FormsModule}from'@angular/forms';import{AppRoutingModule}from'./app-routing.module';import{AppComponent}from'./app.component';import{ProfileComponent}from'./profile/profile.component';import{SignInComponent}from'./sign-in/sign-in.component';import{SignUpComponent}from'./sign-up/sign-up.component';@NgModule({declarations:[AppComponent,ProfileComponent,SignInComponent,SignUpComponent,],imports:[BrowserModule,FormsModule,AppRoutingModule,],providers:[],bootstrap:[AppComponent,],})exportclassAppModule{}
21. Run the application with the command below.
npm start> angular-cognito@1.0.0 start> ng serve✔ Browser application bundle generation complete.Initial Chunk Files| Names| Raw Sizevendor.js| vendor|9.98 MB| styles.css, styles.js| styles|486.91 kB| polyfills.js| polyfills|339.28 kB| scripts.js| scripts|76.33 kB| main.js| main|47.13 kB| runtime.js| runtime|6.87 kB|| Initial Total|10.91 MBBuild at:2022-01-18T16:33:13.971Z- Hash: ce7a03498c95d4f5- Time: 25230ms** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/**✔ Compiled successfully.
Note:
- It may display some warnings when running the application.
22. Ready! Access the URLhttp://localhost:4200/ and check if the application is working. See the application working onGitHub Pages andStackblitz.
1. Let's test the application. Access the URLhttp://localhost:4200/, fill in the fieldEmail,Password and click on the buttonSign up.
2. Check that the user was created in Amazon Cognito.
3. Open the email with the subjectYour verification code and copy the code generated, in my case, the code308386 was generated.
4. Fill in the fieldCode with the code copied and click on the buttonConfirm.
5. Check that the user was confirmed in Amazon Cognito.
6. Fill in the fieldEmail,Password and click on the buttonSign in.
7. Fill in the fieldName and click on the buttonUpdate.
8. Click on the user link created in Amazon Cognito.
9. Check that the user name was updated in Amazon Cognito.
10. Ready! We test the user sign in, sign up and update.
1. Clone the repository.
git clone git@github.com:rodrigokamada/angular-amazon-cognito.git
2. Install the dependencies.
npm ci
3. Run the application.
npm start
About
Application example built with Angular 20 with authentication using the Amazon Cognito service.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.


































