Authentication Using Firebase in Angular for Web-Based Applications
Firebase provides easy and flexible APIs for Authentication. Inside your app, the user can sign up using a variety of methods. The popular ones being Google, Facebook, Twitter, E-Mail.
Pre-requisite: You need a firebase account to begin. Once you have your account created, create a sample project.
Go to the firebase console and create one. I’m naming my project as ‘firebase-auth’. I’m registering this as a web-app and enabling hosting.
After the project is created, click on Authentication -> Get Started. On this screen, you can see all the methods, that the firebase provides. I’m enabling Google here.
You can add firebase-tools, through CLI for managing your firebase projects.
In my previous post, I had created a simple login form, I’ll be working on top of that.
Let’s begin.
Step 1: Add Firebase to your project.
ng add @angular/fire
If you have installed firebase-tools and logged in, at this point you can choose the project to work with.
Step-2: Initialize firebase.
Copy your project settings from project settings-> General.
Add the firebaseConfig in your environment.ts file.
export const environment = {
production: false,
firebaseConfig: {
apiKey: "AIzaSyCMTX7ODZQPP7W3LtmYJM4_epxM9_hFFCo",
authDomain: "fir-auth-6bea8.firebaseapp.com",
projectId: "fir-auth-6bea8",
storageBucket: "fir-auth-6bea8.appspot.com",
messagingSenderId: "1019846518052",
appId:"1:1019846518052:web:f7a211820bc606ac77ffb1"
}
};
Next, import the firebase modules and environment file in app module. Inititalize the firebase here.
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { environment } from 'src/environments/environment';
..imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MaterialModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFireAuthModule
]
Step-3:
I have created a service where I can add all firebase related methods. This service can be injected into any component and its method can be used.
ng g service services/firebasefirebase.service.tsimport { Injectable } from ‘@angular/core’;
import { AngularFireAuth } from ‘@angular/fire/auth’;
import firebase from ‘firebase/app’;@Injectable({
providedIn: ‘root’
})
export class FirebaseService {constructor(private fireAuth: AngularFireAuth) { }signInWithGoogle(): any{
return this.fireAuth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
}signOut(){
return this.fireAuth.signOut();
}
}
Step-4:
I’m adding firebase Auth in the Login component. Import this service and Inject it into the constructor.
import { FirebaseService } from ‘../../services/firebase.service’;constructor(private firebaseService: FirebaseService){}
Next, in the HTML add a button for Login with Google.
<button mat-raised-button type=”button” (click)=”loginWithGoogle()”>Login with Google </button>
In the component class, add loginWithGoogle().
loginWithGoogle(){
this.firebaseService.signInWithGoogle().then(response => {
this.router.navigate(['/dashboard']);
}
);
}
Here, signInWithGoogle() of service is invoked. As it returns a promise, we use a .then method to get the response. I’m navigating it to a new route, dashboard.
Let’s store the response in a service method so that we can access it in the dashboard component.
I have created a new service called DataService.
import { Injectable } from '@angular/core';@Injectable({
providedIn: 'root'
})
export class DataService {
userData: Object; //firebase response objectconstructor() { }//assign the value using a setter method
setUserData(data){
this.userData = data;
}//To get the value
getUserData(){
return this.userData;
}
}
In login.component.ts,
import { DataService } from ‘../../services/data.service’;
constructor(private firebaseService: FirebaseService, private router: Router, private dataService: DataService) {loginWithGoogle(){
this.firebaseService.signInWithGoogle().then(response => {
this.dataService.setUserData(response);
this.router.navigate(['/dashboard']);
}
);
}
Step-5:
In the dashboard component file, import firebase service, data service.
import { FirebaseService } from ‘../../services/firebase.service’;
import { DataService } from ‘../../services/data.service’;user: Object;constructor(private dataService: DataService, private firebaseService: FirebaseService) {}ngOnInit(): void {
this.user = this.dataService.getUserData();
}
In the dashboard HTML, I’m binding the displayName property.
<mat-toolbar>
<mat-toolbar-row>
<span>Welcome, {{user?.user?.displayName}}</span>
<span class=”spacer”></span>
</<mat-toolbar>
Step-6:
To Sign-out user, I’m adding an anchor link in the header.
<mat-toolbar>
<mat-toolbar-row>
<span>Welcome, {{user?.user?.displayName}}</span>
<span class=”spacer”></span>
<a href=”” (click)=”signOut()”> Sign Out</a>
</mat-toolbar-row>
</mat-toolbar>
In the Dashboard Component, call the signOut method from the firebase service.
signOut(){
this.firebaseService.signOut();
}
That’s all!
Check out the code at https://github.com/rucha412/login-form