How to add Firebase Authentication to an Angular application

Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

This is effectively a drop-in solution for identity management without requiring any custom backend code.

First, [create a new Firebase application].

  • Add firebase and firebaseui npm dependencies
  • Add the Firebase UI CSS from https://www.gstatic.com/firebasejs/ui/4.6.1/firebase-ui-auth.css
  • Initialize Firebase, show auth UI, and detect auth changes using the code below
import * as firebase from 'firebase';
import * as firebaseui from 'firebaseui';

// copy config from Firebase console https://console.firebase.google.com/
const firebaseConfig = {
  apiKey,
  authDomain,
  databaseURL,
  projectId,
  storageBucket,
  messagingSenderId,
  appId,
};
firebase.initializeApp(firebaseConfig);

// urls can be a string or function
// signInOptions determines which auth methods are enabled
const uiConfig = {
  signInSuccessUrl: '<url-to-redirect-to-on-success>',
  signInOptions: [firebase.auth.GoogleAuthProvider.PROVIDER_ID],
  tosUrl: '<your-tos-url>',
  privacyPolicyUrl: function () {
    window.location.assign('<your-privacy-policy-url>');
  },
};

// Initialize the FirebaseUI Widget using Firebase
const ui = new firebaseui.auth.AuthUI(firebase.auth());
if (ui.isPendingRedirect()) {
  // provide a CSS selector where the auth UI should be created
  ui.start('#authui', uiConfig);
} else {
  // listen for changes to auth status
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      this.stateService.currentUser = user;
    }
  });
}

Links