Angular Firebase Auth – Anonymous Authentication with AngularFire2 v4

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 4

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

I. Technology

– Angular 4
– AngularFire2 4.0

II. Overview

We will build an Angular 4 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.

4. App Module


import {AngularFireModule} from 'angularfire2';
import {AngularFireAuthModule} from 'angularfire2/auth';

import {AuthService} from './auth/auth.service';

@NgModule({
  // ...
  imports: [
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule
  ],
  providers: [AuthService],
  // ...
})

III. Practice

1. Project structure

angular-4-firebase-auth-anonymous-structure

2. App Module


import {environment} from '../environments/environment';
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';

import {AngularFireModule} from 'angularfire2';
import {AngularFireAuthModule} from 'angularfire2/auth';

import {AuthService} from './auth/auth.service';

import {AppComponent} from './app.component';
import {UserLoginComponent} from './auth/user-login/user-login.component';
import {UserInfoComponent} from './auth/user-info/user-info.component';

@NgModule({
  declarations: [
    AppComponent,
    UserLoginComponent,
    UserInfoComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule
  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule {}

3. Auth Service


import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {AngularFireAuth} from 'angularfire2/auth';

@Injectable()
export class AuthService {

  authState: any = null;

  constructor(private afAuth: AngularFireAuth, private router: Router) {
    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();
    this.router.navigate(['/'])
  }
}

4. Components

4.1 User Login Component

user-login.component.ts


import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {AuthService} from '../auth.service';

@Component({
  selector: 'user-login',
  templateUrl: './user-login.component.html',
  styleUrls: ['./user-login.component.css']
})
export class UserLoginComponent implements OnInit {

  constructor(public authService: AuthService, private router: Router) {}

  ngOnInit() {
  }

  signInAnonymously() {
    this.authService.anonymousLogin()
      .then(() => this.router.navigate(['/']));
  }
}

user-login.component.html

<div *ngIf="!authService.isUserAnonymousLoggedIn">
	<button (click)="signInAnonymously()">Login</button>
</div>

4.2 User Info Component

user-info.component.ts


import {Component, OnInit} from '@angular/core';
import {AuthService} from '../auth.service';

@Component({
  selector: 'user-info',
  templateUrl: './user-info.component.html',
  styleUrls: ['./user-info.component.css']
})
export class UserInfoComponent implements OnInit {

  constructor(public authService: AuthService) {}

  ngOnInit() {
  }

  logout() {
    this.authService.signOut();
  }

}

user-info.component.html

<div *ngIf="authService.isUserAnonymousLoggedIn">
	<h5 class="text-primary">User Information</h5>
	<h4>
		<strong>UID:</strong> {{ authService.currentUserId }}
	</h4>
	<button class="button" (click)="logout()">Logout</button>
</div>

5. App Routing Module

app-routing.module.ts


import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';

import { UserLoginComponent } from './auth/user-login/user-login.component';

const routes: Routes = [
  {path: '', redirectTo: 'login', pathMatch: 'full'},
  {path: 'login', component: UserLoginComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule {}

6. App Component

app.component.ts


import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'JavaSampleApproach';
  description = 'Angular4-Firebase Demo';
}

app.component.html

<div class="container">
	<div style="color: blue; margin-bottom:20px">
		<h1>{{title}}</h1>
		<h3>{{description}}</h3>
	</div>

	<user-info></user-info>

	<router-outlet></router-outlet>
</div>

7. Check Result

Run the App, login and log out several times:
angular-4-firebase-auth-anonymous-overview

Firebase Console:
angular-4-firebase-auth-anonymous-console-resule

IV. Source Code

Angular4FirebaseAuth-anonymous

27 thoughts on “Angular Firebase Auth – Anonymous Authentication with AngularFire2 v4”

  1. Awesome website you have here but I was wondering if you knew of
    any message boards that cover the same topics
    talked about here? I’d really like to be a part of online
    community where I can get advice from other knowledgeable
    individuals that share the same interest.
    If you have any recommendations, please let me know. Many thanks!

  2. I like the helpful information you provide in your articles.

    I’ll bookmark your weblog and check again here frequently.

    I am quite certain I’ll learn many new stuff right here!

    Good luck for the next!

  3. Howdy fantastic website! Does running a blog like this require a
    massive amount work? I’ve very little expertise in programming but I was
    hoping to start my own blog soon. Anyhow, if you have any suggestions or tips for new blog
    owners please share. I understand this is off subject but I simply wanted to ask.
    Many thanks!

  4. Heya are using WordPress for your blog platform?
    I’m new to the blog world but I’m trying to get started and create my own. Do you
    need any coding expertise to make your own blog?
    Any help would be greatly appreciated!

  5. Hello! I understand this is kind of off-topic however I needed to ask.
    Does running a well-established website like yours take a lot of
    work? I am completely new to blogging but I do write in my journal everyday.

    I’d like to start a blog so I can easily share my own experience and views online.
    Please let me know if you have any kind of ideas or tips for brand
    new aspiring blog owners. Thankyou!

  6. Howdy this is kind of of off topic but I was wondering if blogs use
    WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding skills so I wanted to get guidance
    from someone with experience. Any help would be greatly appreciated!

  7. This design is steller! You most certainly know how
    to keep a reader entertained. Between your wit and your videos, I was almost moved
    to start my own blog (well, almost…HaHa!) Excellent job.

    I really enjoyed what you had to say, and more than that, how
    you presented it. Too cool!

  8. I am really enjoying the theme/design of your site. Do you ever run into any internet browser
    compatibility problems? A small number of my blog visitors have complained
    about my site not working correctly in Explorer but looks
    great in Opera. Do you have any advice to help fix this problem?

  9. Right here is the perfect blog for anyone who wishes to find out about this topic.

    You understand a whole lot its almost tough to argue with you (not that I really would want to…HaHa).
    You certainly put a fresh spin on a topic which has been discussed for many years.
    Great stuff, just wonderful!

  10. Terrific article! This is the type of info that should be shared around the internet.
    Shame on the seek engines for no longer positioning this post higher!
    Come on over and visit my website . Thank you =)

  11. Hello There. I discovered your weblog using msn. This
    is an extremely neatly written article. I’ll make sure to
    bookmark it and come back to read extra of your useful information. Thanks for the post.

    I’ll certainly comeback.

  12. You could certainly see your expertise in the article you write.
    The sector hopes for even more passionate writers such as you who aren’t afraid to mention how they believe.
    At all times follow your heart.

  13. Ιt’s pеrfect time to maқe a few plans for the long run and it’s time to bе happy.

    I’ve read this submіt and if I could I desirе to suggest you few attentiⲟn-grabbing issues
    or advice. Perhaps you can write next articles
    relating to tһis articlе. I want to ⅼearn even more things apρroximately it!

Leave a Reply

Your email address will not be published. Required fields are marked *