Build a Complete Angular 6|7 Firebase Authentication System

Learn step by step how to build a complete Angular 7 Firebase authentication system from scratch using third party providers and email/password login method

firebase authentication with angular 7 TL;DR: Hello folks, in today's article will learn step by step how to build a complete Angular 7 Firebase authentication system from scratch using third party providers and email/password authentication workflows. We will add Google, Facebook and Github Authentication methods along with an email and password authentication using Firebase Authentication services.

User Management with Angular

When creating web applications, any sort of authentication feature is important.

When you see the numerous social platforms and email sign in methods available, authentication becomes an extremely complex task, so creating a complete login system from scratch makes the developer feel somewhat perplexed about the time needed to finish the work.

Firebase offers backend services that will simplify the complexity nature of taking care of user authentication with Angular 7 for both mobile and web applications. Authentication and all backend related tasks can be easily implemented in your Angular project using Firebase.

Firebase User Authentication

Luckily, there are services that give us great advantages, for example, sparing us the substantial work it takes to build up all the user authentication flow. Among these services are Firebase and Auth0.

Firebase comes up with a very simple solution to setup authentication in your apps. It is very easy to integrate with your application and you can configure it to add multiple social authentication providers like Google, Facebook, Twitter, Github, and so on. After you have setup these authentication providers on your app, users can use their social accounts to access your web or mobile app easily. Additionally it enables users to sign up with email and password or phone number accounts.

Firebase Services

I believe that Firebase would be an ideal solution for your web or mobile applications created using Angular 7, for the reason that it offers highly useful backend services such as Firebase login authentication, storage, real-time database, functions, etc. The best news is that it is backed by Google and offers a free multi-platform authentication feature.

It is important to mention that the Firebase Database is a non-SQL database which uses  JSON object for  saving and synchronizing the data among its users in real-time.

So what are you waiting for? Let’s see how we can implement an Angular 7 Firebase Authentication system.

In this tutorial  we will walk through the process of building the famous email/password authentication system as well as the social authentication workflow for Angular 7 app from scratch using AngularFire2 the official library for integrating Firebase within Angular apps.

Also, if you want to learn more on how you can setup a custom authentication system with Angular using the JWT Authentication approach, you can refer to this article:  Angular 2-5 JWT Authentication: Using Http Client, Http Interceptors and Guards

In the next section you will learn step by step how to create an Angular 7 Firebase authentication system using social and custom authentication workflows. We will add Google, Facebook and Github Authentication methods along with an email and password authentication using Firebase Authentication services.

1. Prerequisites

For this tutorial you need to have the following prerequisites:

  • Recent versions of Node.js and NPM. You can install them from their official website,
  • Angular CLI v7 installed (npm install @angular/cli -g)
  • Angular 7 or Angular 6
  • RxJS v6
  • Bootstrap

2. Creating the Angular 7 Project

Use the following command to create an Angular 7 project:

$ ng new angular-firebase-authentication

Then, access to the project's folder:

$ cd angular-firebase-authentication

Finally, serve your web application using the command below to make sure it properly works:

$ ng serve --open

This will automatically open your browser and navigate to the http://localhost:4200 address.

3. Configuring a Firebase Project

After setting up your dev environment, you will need to register for a free Firebase account by visiting the page https://firebase.google.com/ and login to your account or create a new one. Next access to your Firebase console and you will see an option to add a new Firebase project, click on it and follow steps to the end.

create new firebase project

Once your firebase project is created, you will be redirected to the admin dashboard for that particular project as showed below:

firebase console

Click on the Add Firebase to your web app button and a popup window that contains your firebase credentials will be opened. The pop up will have the following information about your new Firebase App.


<script src="https://www.gstatic.com/firebasejs/5.7.1/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    databaseURL: "YOUR_DATABASE_URL",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID"
  };
  firebase.initializeApp(config);
</script>

In our case we will need just the config object to link our Angular 7 project with Firebase because of the use of Firebase SDK and the AngularFire2 library. So, we will copy and paste these credentials in our Angular project configuration file environment.ts located in src/environments/environment.ts as follow:


export const environment = {
 production: false,
 firebase: {
 apiKey: "YOUR_API_KEY",
 authDomain: "YOUR_AUTH_DOMAIN",
 databaseURL: "YOUR_DATABASE_URL",
 projectId: "YOUR_PROJECT_ID",
 storageBucket: "YOUR_STORAGE_BUCKET",
 messagingSenderId: "YOUR_SENDER_ID"
 }
};

Next, navigate to the authentication > Sign-in tab so you can activate the sign-in providers of your choice, for us we will choose the Email/password, Google, Facebook and GitHub methods as shown below.

firebase login providers

Now, to be able to activate the Facebook and GitHub providers, you need to create an app for both of them.

4. Configuring Facebook Firebase Authentication

Go to Facebook and create a Facebook App from your developer account. At the end you will have an App ID and an App Secret, use them to enable your Facebook sign-in method in Firebase.

enable firebase facebook authentication

Remember to copy your OAuth redirect URI generated by Firebase and past it in the Facebook Application panel as the following image.

facebook developers app setup

5. Configuring GitHub Firebase Authentication

Do the same for GitHub, where you have to go here and register a new app as shown below:

register new app github

Then, you will get an OAuth 2.0 Client ID and Client Secret use them to activate the GitHub Sign-in method and don't forget to copy the generated OAuth redirect URI and set it as your Authorization callback URL for your created GitHub app.

6. Configuring Google and Email/Password Firebase Authentication

Google and Email/Password Authentication methods are the simplest to enable, just click on both respectively and choose the option enable with the slide button as following:

enable firebase google authentication

enable firebase email password authentication

Finally click on the Save button.

7. Installing AngularFire2 Library

To allow communication between our Angular 7 web application and Firebase database we will use the AngularFire2 library which is the official Firebase library for Angular.

Go back to your terminal, make sure you are inside the project’s root folder and then execute the following command to install Firebase SDK and AngularFire2 from npm.

$ npm install firebase @angular/fire --save

Now open your application main module app.module.ts and import the required modules as shown below.


//[...]
import { AngularFireModule } from 'angularfire2';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { environment } from '../environments/environment';

Then, add them to the imports array like this:


imports: [
  AngularFireModule.initializeApp(environment.firebase),
  AngularFirestoreModule, // imports firebase/firestore, only needed for database features
  AngularFireAuthModule, // imports firebase/auth, only needed for auth features
  ...
]

8. Creating Components, Templates and Routes

In our example we will have 3 components with their corresponding templates

  • The Register Component - Register users with Email and Password.
  • The Login Component - Login users using social providers option and also with Email and password.
  • The Profile Component - Protected area accessible only for authenticated users.

 

The routing of our Angular 7 app is very simple. Yet, you should notice that we are using an AuthGuard that checks if the user is logged in, and in such a case he will be redirected to the user Profile page. On the other hand if the user tries to access the Profile page without being authenticated, he will be redirected to the login page.


// src/app/routing.module.ts

export const rootRoutes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent, canActivate: [AuthGuard] },
  { path: 'register', component: RegisterComponent, canActivate: [AuthGuard] },
  { path: 'profile', component: ProfileComponent,  resolve: { data: ProfileResolver}}
];

We need to generate route guard files. Run the below command to create route guards.

ng generate guard core/auth

Then, go to src/app/core/auth.guard.ts and add the constructor and canActivate functions as follow.


export class AuthGuard implements CanActivate {

  constructor(
    public userService: UserService,
    private router: Router
  ) {}

  canActivate(): Promise{
    return new Promise((resolve, reject) => {
      this.userService.getCurrentUser()
      .then(user => {
        this.router.navigate(['/profile']);
        return resolve(false);
      }, err => {
        return resolve(true);
      })
    })
  }
}

We also use a ProfileResolver for the profile component which allows retrieving data about the authenticated user before rendering the page, or redirecting to the login page if the user is not logged in. This is the contents of the src/app/profile/profile.resolver.ts file.


// [Imports...]

@Injectable({
    providedIn:  'root'
})
export class ProfileResolver implements Resolve {

  constructor(public userService: UserService, private router: Router) { }

  resolve(route: ActivatedRouteSnapshot) : Promise {

    let user = new FirebaseUserModel();

    return new Promise((resolve, reject) => {
      this.userService.getCurrentUser()
      .then(res => {
        if(res.providerData[0].providerId == 'password'){
          user.image = 'user-profile-url.png';
          user.name = res.displayName;
          user.provider = res.providerData[0].providerId;
          return resolve(user);
        }
        else{
          user.image = res.photoURL;
          user.name = res.displayName;
          user.provider = res.providerData[0].providerId;
          return resolve(user);
        }
      }, err => {
        this.router.navigate(['/login']);
        return reject(err);
      })
    })
  }
}

9. Creating An Authentication Service

To abstract all the interactions with Firebase auth, we will create an Angular service using this command.

$ ng g s core/auth

With this command we created an AuthService which is the one that will do most of the serious work by allowing us to login, register and logout users with Firebase providers. All the authentication logic will be defined in this service, which will allow us to keep our components simple and clean.

Firstly, start by importing the Firebase related classes as follow.


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

Then add the following to our AuthService constructor and you will have something similar to that.


@Injectable({
    providedIn:  'root'
})
export  class  AuthService {
    constructor(public afAuth: AngularFireAuth){}

}

10. Implementing Firebase Third Party Authentication

Our AuthService will define the functions that will handle the social login using Firebase. As an example, for Google authentication we will use this method (you can find it in src/app/core/auth.service.ts).


doGoogleAuth(){
  return new Promise((resolve, reject) => {
      let provider = new firebase.auth.GoogleAuthProvider();
      provider.addScope('profile');
      provider.addScope('email');
      this.afAuth.auth
      .signInWithPopup(provider)
      .then(res => {
        resolve(res);
      }, err => {
        console.log(err);
        reject(err);
      })
    })
}

As you can see, we specify OAuth 2.0 scopes using the addScope method to request additional information about the user from Google Authentication provider.

The same approach applies to Facebook, and if we want to get more information about the user for instance his gender, we use provider.addScope('user_gender).


doFacebookAuth(){
   return new Promise((resolve, reject) => {
     let provider = new firebase.auth.FacebookAuthProvider();
     this.afAuth.auth
     .signInWithPopup(provider)
     .then(res => {
       resolve(res);
     }, err => {
       console.log(err);
       reject(err);
     })
   })
}

For Github use this code.


doGitHubAuth(){
 return new Promise((resolve, reject) => {
   let provider = new firebase.auth.GithubAuthProvider();
   provider.addScope('repo');
   this.afAuth.auth
   .signInWithPopup(provider)
   .then(res => {
     resolve(res);
   }, err => {
     console.log(err);
     reject(err);
   })
 })
}

11. Implementing Firebase Email/Password Authentication

This sign-in method needs to be enabled inside the Firebase console so we can use it.

The implementation of this feature requires creating an Angular form using Reactive Forms, so the user can provide his email and password and then submit.

Create the register component then copy the following html code and paste it into your register page template src/app/register/register.component.html.


<h1 class="header">Register with Firebase or Third Party Providers</h1>
<div class="container">
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <form [formGroup]="registerForm">
        <div class="form-group">
          <label>Email address</label>
          <input type="email" formControlName="email" class="form-control">
        </div>
        <div class="form-group">
          <label>Password</label>
          <input type="password" class="form-control" formControlName="password">
          <label class="error">{{errorMessage}}</label>
          <label class="success">{{successMessage}}</label>
        </div>
        <button type="submit" (click)="tryRegister(registerForm.value)" class="btn btn-default">Register</button>
      </form>
    </div>
  </div>
  <div class="row">
    <div class="col-md-4 col-md-offset-4">
      <button type="button" class="btn btn-primary btn-block" (click)="facebookLogin()">Register with Facebook</button>
    </div>
  </div>
  <!-- Other authentication providers: full code in GitHub Repository -->
  <div class="row">
    <div class="col-md-4 col-md-offset-4">
      <p>Already have an account? <a href="/login">Login</a></p>
    </div>
  </div>
</div>

Then, in our register.component.ts define the tryRegister method.


tryRegister(value){
 this.authService.doRegister(value)
 .then(res => {
 console.log(res);
 this.errorMessage = "";
 this.successMessage = "Your account has been created";
 }, err => {
 console.log(err);
 this.errorMessage = err.message;
 this.successMessage = "";
 })
}

doRegister is a function of AuthService which calls the Firebase authentication method createUserWithEmailAndPassword() to allow Firebase to add a new user after performing some validations regarding the email and password provided or reject it by returning an error.


doRegister(value){
 return new Promise((resolve, reject) => {
   firebase.auth().createUserWithEmailAndPassword(value.email, value.password)
   .then(res => {
     resolve(res);
   }, err => reject(err))
 })
}

Because of the similarity between the Register and Login with email and password methods, we decided to omit the Login method in this article so we don't repeat ourselves, keep it clean and simple, but you can find it in the source code provided in our GitHub.

After a successful authentication the user will be redirected to the protected area which is his profile where he will be able to see some basic info.

The logout button allows setting the AuthState to null and redirect the user to the login form.

Takeaway

In this article, you have learned how to configure your Firebase console to be able to use the different Sign-in methods, how to integrate your Angular 7 app with Firebase and finally how to build easily a complete Angular 7 Firebase Authentication system with different Social login providers as well as the Email and Password login.

That's it! We hope that this article helped you solve your issue. If you have any question leave it in the comments section below and we will be glad to answer. You can get the source code files used here from our GitHub Repository .

Name

Angular,7,Angular 8,1,Best Practices,1,Design,1,Firebase,1,Ionic,1,Java,5,Nodejs,2,Python,1,Restful API,1,Software Development,1,Spring,3,Spring Batch,1,Spring Boot 2,1,Web Development,1,
ltr
item
Programming Tutorials, News and Reviews: Build a Complete Angular 6|7 Firebase Authentication System
Build a Complete Angular 6|7 Firebase Authentication System
Learn step by step how to build a complete Angular 7 Firebase authentication system from scratch using third party providers and email/password login method
https://4.bp.blogspot.com/-e7xgOAmTpTQ/XH2c2B8yF2I/AAAAAAAAAO4/EsQDlxVqntsqyQJY-bsZY172_15uhCPQwCLcBGAs/s1600/angular-firebase-authentication-system.png
https://4.bp.blogspot.com/-e7xgOAmTpTQ/XH2c2B8yF2I/AAAAAAAAAO4/EsQDlxVqntsqyQJY-bsZY172_15uhCPQwCLcBGAs/s72-c/angular-firebase-authentication-system.png
Programming Tutorials, News and Reviews
https://www.ninjadevcorner.com/2019/03/complete-angular-firebase-authentication-system.html
https://www.ninjadevcorner.com/
https://www.ninjadevcorner.com/
https://www.ninjadevcorner.com/2019/03/complete-angular-firebase-authentication-system.html
true
493653397416713395
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy