DEV Community

loading...

Angular 9 Firebase Auth – Anonymous Authentication with AngularFire2 v4

loizenai profile image loizenai ・2 min read

https://grokonez.com/angular-9-firebase-auth-anonymous-authentication

Anonymous authentication uses only a userID to login without registration. Once signing out, user will not be able to log back in. In this tutorial, we're gonna look at way to implement Anonymous authentication with AngularFire2 v4.

Related Post:
How to integrate Firebase with Angular 9

More Practice:
Angular 9 Firebase Auth – Email/Password Authentication with AngularFire2 v4

I. Technology

  • Angular 9
  • AngularFire2 4.0

    II. Overview

    We will build an Angular 9 App that allows user login anonymously:

angular-4-firebase-auth-anonymous-overview

II. How to do

1. Set up the Firebase Project & Install AngularFire2

Please visit this post to know step by step.

angular-4-firebase-integration-copy-firebase-project-config

2. Enable Firebase Auth for Anonymous

Go to your Project on Firebase Console -> Authentication tab -> SIGN-IN METHOD -> enable Anonymous:

angular-4-firebase-auth-anonymous-enable-console

3. Auth Service


import {AngularFireAuth} from 'angularfire2/auth';

@Injectable()
export class AuthService {

  authState: any = null;

  constructor(private afAuth: AngularFireAuth) {
    this.afAuth.authState.subscribe((auth) => {
      this.authState = auth
    });
  }

  get isUserAnonymousLoggedIn(): boolean {
    return (this.authState !== null) ? this.authState.isAnonymous : false
  }

  get currentUserId(): string {
    return (this.authState !== null) ? this.authState.uid : '';
  }

  anonymousLogin() {
    return this.afAuth.auth.signInAnonymously()
      .then((user) => {
        this.authState = user
      })
      .catch(error => console.log(error));
  }

  signOut(): void {
    this.afAuth.auth.signOut();
  }
}
  • We subscribe to the AngularFire auth observable that returns a FirebaseAuthState object. This object is null when logging out, and contains useful User Information (UID, Display Name, Photo URL...) when logging in.
  • We use:
  • AngularFireAuth.auth.signInAnonymously() to log in.
  • AngularFireAuth.auth.signOut() to log out.

https://grokonez.com/angular-9-firebase-auth-anonymous-authentication

Discussion (0)

pic
Editor guide