Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Angular Firebase Authentication Tutorial - Anonymous Auth

Episode 2 written by Jeff Delaney
full courses and content on fireship.io

Health Check: This lesson was last reviewed on and tested with these packages:

  • Angular v4
  • AngularFire2 v4

Update Notes: Breaking changes have been introduced since this video's original release. Checkout the following updated lessons covering User Auth.

Find an issue? Let's fix it

Anonymous authorization allows a user to start using your app with going through the typical OAuth or Email/Password registration. This is also approach is also called lazy auth, lazy registration, and gradual engagement. One of the most common ways to lose new users is to have a complex signup process.

Anonymous auth works by creating a session using only a user ID (UID). If the user signs out without upgrading their account, they will not be able to log back in.

View Demo

In most cases, you should have a working auth feature before setting anonymous auth. I am building this feature on top our Angular OAuth tutorial.

Step 1: Enable Anonymous Auth in Firebase

Make sure the anonymous option is enabled in your Firebase console.

Make sure to activate the anonymous provider in the Firebase console.

Make sure to activate the anonymous provider in the Firebase console.

Step 2: Updating the Auth Service

We’re using the AuthService code from the OAuth lesson. Here are the parts needed specifically for anonymous auth. It works just like any other auth approach in Angular Firebase - the most important part is subscribing to the auth state in the constructor.

core/auth.service.ts

@Injectable()
export class AuthService {

authState: FirebaseAuthState = null;

constructor(private af: AngularFire,
private db: AngularFireDatabase,
private router:Router) {

af.auth.subscribe((auth) => {
this.authState = auth;
});
}

anonymousLogin() {
return this.af.auth.login({
provider: AuthProviders.Anonymous,
method: AuthMethods.Anonymous,
})
.then(() => console.log("successful login") )
.catch(error => console.log(error));
}
}

Step 3: Sign in Users Anonymously

Now we just need to wire up a component to sign in users anonymously.

users/user-login.ts

export class UserLoginComponent {

constructor(public auth: AuthService, router: Router) { }

signInAnonymously() {
this.auth.anonymousLogin()
.then(() => this.afterSignIn());
}

private afterSignIn(): void {
// Do after login stuff here, such router redirects, toast messages, etc.
this.router.navigate(['/']);
}
}

users/user-login.html

<button (click)="signInAnonymously()" >
Connect Anonymously
</button>

Step 4: Limiting Access for Anonymous Users

Many apps try to limit access to certain features for anonymous users. The FirebaseAuthState object will include anonymous: true, so we can create a TypeScript getter to make conditional logic easier to handle in templates.

get currentUserAnonymous(): boolean {
return this.authenticated ? this.authState.anonymous : false
}

Then you can use it in the template like so:

users/user-login.html

<div *ngIf="auth.currentUserAnonymous" >
Content for anonymous users
</div>

Step 5: Upgrading an Anonymous Auth Account

Let’s say your user has created some data and wants to upgrade from anonymous to a full fledged user. Firebase supports account upgrading, but you would need to rebuild the auth process from scratch and bypass AngularFire2. Fortunately, there there is a reasonable alternative to avoid this extra layer of complexity.

A different approach is to map the anonymous user data snapshot to a new account after they upgrade. This process will depend on how your NoSQL database is structured, but let’s say you have data that is nested under the user ID.

"userID" : {
"some": "data"
}

The mapping function would look something like this.


  1. Save the anonymous UID

  2. Log the user in via Google OAuth

  3. Get the data snapshot from the anonymous user

  4. Update the database with the snapshot

 anonymousUpgrade(): firebase.Promise {

let anonId = this.currentUserId // the anonymous UID

// Login with google
return this.googleLogin().then( () => {
// get the anonymous data snapshot
this.db.object(anonId).subscribe(snapshot => {
// map the anonymous user data to the new account.
this.db.object(this.currentUserId).update(snapshot)
})
});
}

Update: Upgrading with Anonymous Firebase users in Angular 4

Here’s how to handle an anonymous upgrade with AngularFire2 version 4. Now we have a function in the Firebase SDK that can link accounts with a Popup window. Much easier!


import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';

// omitted...

anonymousUpgrade() {
const provider = new firebase.auth.GoogleAuthProvider()
firebase.auth().currentUser.linkWithPopup(provider)
}