February 12, 2020

Passwordless authentication with Ionic and Firebase


  • Create an ionic project
> ionic start myproject 
  • Give a package id in file >myproject/config.xml

<widget id="com.mycompany.tasks" version="0.0.8" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

  • Add firebase credentials into >myproject/src/environments/envirornment.ts

export const environment = {
  production: false,
  firebase: {
    apiKey: "....",
    authDomain: "....",
    databaseURL: "....",
    projectId: "....",
    storageBucket: "....",
    messagingSenderId: "....",
    appId: "....",
    measurementId: "...."
  }
};

  • Add an App by going to Firebase console > Your project > Project settings


Download the GoogleService-Info.plist file produced in this 
  • Enable Passwordless authentication
  • Build your project
> ionic build
(This will load contents in www folder)

  • Setup Firebase hosting

> npm install -g firebase-tools
> firebase login
> firebase init hosting
(This this step provide www as the public folder. You need to be in your project base folder for this)'
> firebase deploy


Next goto Firebase>Develop>Hosting and note down the hosting domain
It will be something like yourproject.firebaseapp.com

  • Setup Firebase Dynamiclink domain. It's in the Grow section

It will be something like yourproject.page.link

  • Add Firebase Dynamiclink plugin
As a prep step, add yourproject.firebaseapp.com and yourproject.page.link to Authorized Domain in Firebase. Project setttings> Authentication > Sign-in method > Authorize Domain (scroll down)

> cordova plugin add cordova-plugin-firebase-dynamiclinks --variable APP_DOMAIN="yourproject.firebaseapp.com" --variable PAGE_LINK_DOMAIN="yourproject.page.link"

  • Install ionic native libraries
> npm install @ionic-native/firebase-dynamic-links

  • Build for iOS
> ionic cordova build ios

  • Preparing
 Copy the downloaded GoogleService-Info.plist to platforms/ios/resources/ios/GoogleService-Info.plist

Add following to config.xml, <platform name="ios"> section

<resource-file src="resources/ios/GoogleService-Info.plist" />
        <preference name="GoogleIOSClientId" value="client id in GoogleService-Info.plist" />
 </platform>

  • Create Login page

> ionic g page login

In login.page.html

...
<ion-content>
  <ion-item>
    <ion-label>Email</ion-label>
    <ion-input [(ngModel)]="email"></ion-input>
  </ion-item>
<ion-button (click)="sendEmail(email)">Send</ion-button>
</ion-content>

In login.page.ts

import { Component } from "@angular/core";
import { AngularFireAuth } from "@angular/fire/auth";
import { FirebaseDynamicLinks } from "@ionic-native/firebase-dynamic-links/ngx";
import { Platform } from "@ionic/angular";
import { Router } from '@angular/router';

@Component({
  selector: "app-login",
  templateUrl: "login.page.html",
})
export class LoginPage {

constructor(
    private firebaseDynamicLinks: FirebaseDynamicLinks,
    private firebaseAuth: AngularFireAuth,
    private platform: Platform,
    private router: Router
  ) {
    this.platform.ready().then(() => {
      this.firebaseDynamicLinks.onDynamicLink().subscribe(
        (resp: any) => {
          firebaseAuth.auth
            .signInWithEmailLink(this.email, resp["deepLink"])
            .then(() => {
              this.router.navigate(["/home"]);
            })
            .catch(err => {console.error(err););
            });
        },
        (err: any) => { console.error(err);}
      );
    });
  }
async sendEmailLink() {
    var actionCodeSettings = {
      // Redirect url
      url: "https://yourproject.firebaseapp.com/login",
      handleCodeInApp: true,
      iOS: {
        bundleId: "com.mycompany.tasks"
      }     
    };
try {
      await this.firebaseAuth.auth.sendSignInLinkToEmail(
        this.email,
        actionCodeSettings
      );
    } catch (err) {
      console.error(err);
    }
  }
}

  • Next
. Deploy the iOS app using Xcode
. In the Login page that you see in the app, enter your email and click Send
. You will then get an email from Firebase with this sort of content.

Hello,

We received a request to sign in to project-xxxxxxx using this email address. If you want to sign in with your youremail@someemail.com account, click this link:

Sign in to project-xxxxxx

If you did not request this link, you can safely ignore this email.

Thanks,

Your project-xxxxxxx team

Click on the Sign in link from your mobile, this should open the app again and home page will be loaded.