You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Contents
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Firebase Phone Authentication With Angular 4 Tutorial
Episode 29 written by Jeff DelaneySigning up users with a phone number adds certain degree of trust or confidence to an app. In this lesson, we are going to use the new phone authentication paradigm from Firebase in our Angular 4 app. At this time, phone auth is not supported in AngularFire2, so we will use the firebase JavaScript SDK directly. Phone auth can also be used to link accounts, providing an effective solution for two-factor authentication.
Configuring the reCAPTCHA Widget in Angular
Firebase requires users to use reCAPTCHA to prevent abusive use of the API. You can also implement an invisible reCAPTCHA, but we will be using the visible version in this example.
Injecting the Window Object
You will need to make a reference to the Window object, which represents the DOM. It is considered a bad practice to modify window
directly inside a component - the same goes for all global browser objects. Angular apps can also run on mobile and desktop platforms (which don’t have a window), so a better alternative is to inject the window as a service.
Generate the service with ng g service window
import { Injectable } from '@angular/core'; |
Phone Login Component
ng g component phone-login |
Now we need to collect the user’s phone number. The number must be submitted in E.164 format, which looks like +19495555555
for U.S. numbers.
In order keep values free of validation errors, I am breaking the from into four separate parts and creating a PhoneNumber
class. Then I use a getter to combine the form values into a single string in E164 format.
PhoneNumber class
export class PhoneNumber { |
After the the confirmation text is sent, we display another form field for the user to enter the confirmation. Here’s a breakdown of the process step-by-step
- User verifies reCAPTCHA
- User submits their phone number.
- Firebase sends SMS text and returns a confirmation object.
- User verifies SMS code and the auth state is updated.
Result of successful Firebase phone auth
phone-login.component.ts
import { Component, OnInit } from '@angular/core'; |
phone-login.component.html
In the HTML template, we trigger the various stages of the auth login with button clicks. The phone number object and the verification code are tracked with ngModel
.
<div [hidden]="user"> |