1

Build an Authentication system in Angular using Firebase

 2 years ago
source link: https://blog.knoldus.com/build-an-authentication-system-in-angular-using-firebase/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Reading Time: 4 minutes

In this blog, I am going to take you through the steps of how we can build an authentication system in angular using Firebase and Google API. We can easily use this real-time database to and Google API to let users log in to our web-app with their google account.

Step 1: Setup an Angular project

Your basic project will be set up after that enter into the project folder by using the following command.

 ng new firebase-auth-project

For using the firebase service we will user @angular/fire package. So, in your project install the dependency required by using the following command:

npm install firebase @angular/fire --save

Step 2: Setting up a Firebase Project

If you don’t already have a Firebase setup, you simply need to head to your Firebase console and click on Add project then follow the steps to create a Firebase project.

vLaBDpGayCVsMdZxBdYib_3r3izxFFpWJjGQbaU1ziFlkXr2dqcSHmNng_uL3_6PQfQjueqYYqLPdIDzPZ2Mkf_FMSTmumjGIQePjXwmhcQo5KJRWIm_pji5dMaKKpU9oWenJVA1

1. click Add project, and then enter the name for your project, then Create a project.

hIQPmnCkkKSz-I96SlnlID7xz1dQYimG3TmV2P1s5Yc0mJenU_KVb0knFv7oF9bQ0-Tiv-dW1KxcJwr-HT8gR-W4sRhCixQQ-iOnejzwtZtLgYJ9kcpODYSnYyiZPGAx-69XAfIP

2. Go to Authentication section, and then click Set up sign in method.

ahiGbnt_iYxeY1KdnyLxfmFMNhsvk3FoJ0ihPyJokB3EclqKq-tRrwk-OenNH8DM_wqKQagHwsOKRF1RMnJ28va12Psqqm12NcQnKeQf5fXcmF-x1T4kwWz90WIlGRVcnAaJAPSQ

tw6ubXA1yO0V2qjWF98q9hys1YX674ouYgkDcgwZaBMFlzgsV9pSmuvuMcGEvyasPUY304PRXJiXuXfU1ZWchWPnx1SgIRM6v6XZM_p914w2-tNG66m4QMINPlatgYR9bnKCjSvM

3. This will take you to the following dashboard and you have enabled the google sign In provider

qlf2ZjZ_Xn9ycXlji_Vw97kQh79vcQ6qyWETpLANgiswnmC41f3xWZWpf1PM-UuuEdvbfBf43146NDavryOSnPmqzs2wmfk3LkMOVFLLtJjSfNVVah7KR2av3-3HAeCUjeNzgLLv

4. Go back to the main screen and you click on the “web-app” icon, this will give you configurations that will enable you to enable Firebase services in your web-app.

X-y4gj9rHbjDSQMLhncAmP9XOm4EcMVUECec_zSjzskSsP4X2_L_ljsbdYe6xcUJEo1mN2m0_ZV6WNC6ZTWozAZkBnRz0Ge65nxb3duPHdGNrUpMywGNA0w189RlrfQmdbP5Ko2j

qJfDegbbBHXVbtqs9Y9cuq8l8iVmvjpN9HFj_W6uhvCFrfW6pELBVVMYQZY_PDYoO-pdyPy1kBqm5aVlqsljKnQCQUYyVYeHqtSvAqcgkhh5r2YIbcWq-hHmAkP_BR6C8K2HpsG5

5. Copy these configs, and we will paste them in environment.ts, and we need just the configs because we will be using Firebase SDK in our project.

YTqaFrD0z8IFpHAlZA4HlYmIIkKvkzTP1UGDu01aLBobBKnQqAMLsCGKTwelJjc1akRFcQpNCtnVRH4OluIsyvlbiEb9gR3UsSOqEBMkyk1jFHNGOJSfS5HPaxzHdAuy7mmrgUx5

6. Add the following imports in app.module.ts, and provide the configs to the firebase module.

AngularFireModule.initializeApp(environment.firebaseConfig, 'angular- 
   auth-firebase'),
AngularFirestoreModule,
AngularFireAuthModule

Step 3: Create an authentication service and a login page.

Now we need a service to hold our logic for login and a login component to use that service and implement the feature.

ng generate component login
ng generate service auth

Step 4: Generate a auth service

In auth.service.ts

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import * as firebase from 'firebase';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private firebaseAuth: AngularFireAuth) { }

  signInWithGoogle() {
    return this.firebaseAuth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }
}

We inject the dependency for AngularFireAuth. Inside this dependency, signInWithPopup is a function that opens a pop-up window to let the user sign in through Google account, and on successful authentication, it returns user details wrapped in Promise.

We will use this service in login template.

Step 5: Generate a login HTML template

<h1>
  Login Page
</h1>
<button (click)="onSignIn()">
  Sign in with Google
</button>
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../auth.service';

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

  constructor(private authService: AuthService) {
  }

  ngOnInit(): void {
  }

  onSignIn() {
    this.authService.signInWithGoogle().then((result) => {
      console.log(result);
    });
  }
}

So we call the signInWithGoogle() service method when the button is clicked. It will open a popup window and the user can sign in with google account. If the login is successful we will get the details in the browser console.

Now the possibilities are endless once we get the user details.

Firebase gives us a plethora of user details on successful login like email-id, IDtokens, profile-picture URL, provider details, etc which you can inspect in the console.

This data can be used to send to your own backend for further validation, or register users to your web-app. You can also navigate to other pages after successful login through the router navigation.

And that is it, that how you build an authentication system in angular using firebase.

Thanks a lot for taking the time to read this article, I believe this post really helpful to you. If you want to explore more, visit Firebase Docs.

Footer

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK