Hi Techies, this angular 4 firebase authentication tutorial will explain about the session management in your Angular 4 App.
Angular 4 firebase authentication has contained the Firebase as backend while Angular 4 as front-end.
Authentication is one of the important aspects of any web application. The attached image, explains how the session works in SPA (Single Page Application)
Generally, we store session on back-end and back-end will remember and recognize the client.
In SPA, we have to play with a session at front-end only. In fact, Angular 4 works with a token, not a session.
Moreover, Token is returned by the server to authorize the user, who is using the front-end is an authorized user.So, basically, server will provide a token to front-end, and, then front-end will manage the token to secure the user authentication.
Getting started with Angular 4 Firebase Authentication
Let’s dive into this tutorial, it’s having simple sign-in and sign-up functionality.
The data of users are saved into firebase databse.
And if the user get’s logged-in after sign-up, he will be able to access the home page.
This is a simple example to work with Angular 4 firebase authentication.
First of all, set up an Angular Project.
Are you a newbie in Angular 4?, no worries, you can learn Angular 4 in quick time over here, Take me to Angular 4 Basics
Create your project, using ng new.
ng new angular4-fireabse-auth
Is it your first Angular 4 project? and do you want a detailed guide to create your first Angular 4 App? Take me to Angular 4 Hello World
Add boostrap style in your project.
npm install --save bootstrap
Apply bootstrap, add/modify the style block with bootstrap css in your .angular-cli.json file.
"styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css", "styles.css" ]
Now, let’s install firebase in your Angular project.
npm install --save firebase
Next, generate components sign-up, sign-in and home.
ng generate component auth/sign-up --spec false
ng generate component auth/sign-in --spec false
Furthermore, we can use short forms also, as shown below.
ng g c Home
Now, set up your firebase app
First of all, go to Firebase console.
If you’re not a user of firebase, then create your user and gets logged in.
Now, create a project in firebase by Add Project icon.
Make the Sign-in method enabled, for now, we’re going to enabled Email/Password method only.
Now, get the credentials to initialized firebase app from Angular.
Now all set, to use a firebase app with Angular 4.
Furthermore, just go through once, “Angular 4 Firebase Authentication: A Project Folder Structure”
Next, let’s dig into the Angular 4 App now.
This app basically has four components, sign-in, sign-up, home, and app default component.
Now, let’s see an App Module, path is src/app/app.module.ts
//Import browser module import { BrowserModule } from '@angular/platform-browser'; //Import Ng module import { NgModule } from '@angular/core'; //Import forms module import { FormsModule, ReactiveFormsModule } from '@angular/forms'; //Imports router modules import { Routes, RouterModule } from '@angular/router'; //Import our App Component import { AppComponent } from './app.component'; //Import sign up component import { SignUpComponent } from './auth/sign-up/sign-up.component'; //Import sign in component import { SignInComponent } from './auth/sign-in/sign-in.component'; //Import auth service import { AuthService } from './auth/auth.service'; //Import auth guard import { AuthGaurd } from './auth/authgaurd.service'; //Import home component import { HomeComponent } from './home/home.component'; //Define the routes const appRoutes: Routes = [ //If no path then it would redirected to sign-in {path: '', redirectTo: '/sign-in', pathMatch: 'full' }, //Sign-in {path: 'sign-in', component: SignInComponent}, //Sign-up {path: 'sign-up', component: SignUpComponent}, //Home {path: 'home', component: HomeComponent, canActivate:[AuthGaurd]} ] @NgModule({ declarations: [ AppComponent, SignUpComponent, SignInComponent, HomeComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes) ], providers: [AuthService, AuthGaurd], bootstrap: [AppComponent] }) export class AppModule { }
Next, let’s define the app component, path is src/app/app.component.ts
//Import core modules import { Component, OnInit } from '@angular/core'; //Import firebase and it's all required dependencies import * as firebase from 'firebase'; //Import auth service import { AuthService } from './auth/auth.service'; //Import router import { Router } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Angular 4 Firebase Authentication: A Tutorial On Session Management'; token: string; constructor(private authService: AuthService, private router: Router){ } ngOnInit() { //Initialize firebase app that we can use in Angular 4 Firebase Authentication App firebase.initializeApp({ apiKey: "//API KEY FROM FIREBASE HERE//", authDomain: "//AUTH DOMAIN FROM FIREBASE WILL BE HERE//" }); } //Logout method onLogout(){ this.authService.logout(); } //Check use is logged in checkUserLoggedIn(){ return localStorage.getItem('isLoggedIn') ? true : false; } }
Next, let’s see the app component HTML, path is src/app/app.component.html
<div style="text-align:center"> <h1> Welcome to {{title}}! </h1> <img width="300" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg=="> </div> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="row pull-right" *ngIf="!checkUserLoggedIn()"> <span routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" > <a href="#" routerLink="/sign-in">Sign-in</a> | </span> <span routerLinkActive="active"> <a href="#" routerLink="/sign-up">Sign-up</a> </span> </div> <div class="row pull-right" *ngIf="checkUserLoggedIn()"> <a href="#" routerLink="/home">Home</a> | <a href="#" (click)="onLogout()">Logout</a> </div> </div> </div> </div> <router-outlet></router-outlet>
Now, we should define the sign-up and sign-in
First of all, we’ll do the sign-up, path is src/app/auth/sign-up/sign-up.component.ts
//Import core modules import { Component, OnInit } from '@angular/core'; //Import forms modules import { FormControl, FormGroup, Validators } from '@angular/forms'; //Import auth service import { AuthService } from '../auth.service'; //Import router import { Router } from '@angular/router'; @Component({ selector: 'app-sign-up', templateUrl: './sign-up.component.html', styleUrls: ['./sign-up.component.css'] }) export class SignUpComponent implements OnInit { signupForm: FormGroup; constructor(private authService: AuthService, private router: Router) { } ngOnInit() { this.signupForm = new FormGroup({ 'email': new FormControl(null, Validators.required), 'pass': new FormControl(null, Validators.required), }); } signup(){ this.authService.signUp(this.signupForm.value.email, this.signupForm.value.pass); this.router.navigate(['/sign-in']); } }
Next, sign up HTML path is src/app/auth/sign-up/sign-up.component.html
<div class="container"> <h1>Sign Up Form</h1> <div class="row"> <div class="col-md-6"> <form [formGroup]="signupForm" (ngSubmit)="signup()"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="email" formControlName="email" class="form-control" placeholder="Email"> </div> <p class="help-block" *ngIf="!signupForm.get('email').valid && signupForm.get('email').touched">Please enter email.</p> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="password" formControlName="pass" class="form-control" placeholder="Password"> </div> <p class="help-block" *ngIf="!signupForm.get('pass').valid && signupForm.get('pass').touched">Please enter passworld.</p> </div> </div> <div class="row pull-right"> <div class="col-md-12"> <button type="submit" class="btn btn-primary" [disabled]="!signupForm.valid">Sign up</button> </div> </div> </form> </div> </div> </div>
Similarly, let’s dig into sign in, path is src/app/auth/sign-in/sign-in.component.ts
//Import core modules import { Component, OnInit } from '@angular/core'; //Import form modules for Angular 4 Firebase Authentication import { FormControl, FormGroup, Validators } from '@angular/forms'; //Import auth service for Angular 4 Firebase Authentication import { AuthService } from '../auth.service'; @Component({ selector: 'app-sign-in', templateUrl: './sign-in.component.html', styleUrls: ['./sign-in.component.css'] }) export class SignInComponent implements OnInit { signinForm: FormGroup; constructor(private authService: AuthService) { } ngOnInit() { this.signinForm = new FormGroup({ 'email': new FormControl(null, Validators.required), 'pass': new FormControl(null, Validators.required), }); } signin(){ this.authService.signIn(this.signinForm.value.email, this.signinForm.value.pass); } }
Sign-in HTML, path is src/app/auth/sign-in/sign-in.component.html
<div class="container"> <h1>Sign In Form</h1> <div class="row"> <div class="col-md-6"> <form [formGroup]="signinForm" (ngSubmit)="signin()"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="email" formControlName="email" class="form-control" placeholder="Email"> </div> <p class="help-block" *ngIf="!signinForm.get('email').valid && signinForm.get('email').touched">Please enter email.</p> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="password" formControlName="pass" class="form-control" placeholder="Password"> </div> <p class="help-block" *ngIf="!signinForm.get('pass').valid && signinForm.get('pass').touched">Please enter passworld.</p> </div> </div> <div class="row pull-right"> <div class="col-md-12"> <button type="submit" class="btn btn-primary" [disabled]="!signinForm.valid">Signin</button> </div> </div> </form> </div> </div> </div>
Finally, see the Home page, just have a simple HTML over there, path is src/app/home/home.component.html
<div class="container"> <h4>Welcom to Home of Angular 4 Firebase Authentication App! </h4> </div>
Moreover, once you do the sign-up, you can see the users are saved into firebase database.
Let’s define an Auth Service which will do the database communication
path is src/app/auth/auth.service.ts
//Import firebase import * as firebase from 'firebase'; //Import router import { Router } from '@angular/router'; //Import Injectable import { Injectable } from '@angular/core'; @Injectable() export class AuthService{ constructor(private router: Router){} signUp(email: string, password: string){ firebase.auth().createUserWithEmailAndPassword(email, password) .then( response => { console.log("Successfull Sign up"); }, error => console.log(error) ) } signIn(email: string, password: string){ firebase.auth().signInWithEmailAndPassword(email, password) .then( response => { this.router.navigate(['home']); this.getCurrentUserToken(); }, error => console.log(error) ); } logout(){ firebase.auth().signOut(); localStorage.removeItem('isLoggedIn'); } getCurrentUserToken(){ firebase.auth().currentUser.getToken() .then( (token: string) => { localStorage.setItem('isLoggedIn', token); } ) localStorage.getItem('isLoggedIn'); } isAuthenticated(){ return (localStorage.getItem('isLoggedIn')) ? true : false; } }
All things considered, to run your Angular 4 Firebase Authentication App, let’s define the final step.
AuthGuard which will do the Authentication of Angular Firebase App
File location is src/app/auth/authgaurd.service.ts
//Import core import { Injectable } from '@angular/core'; //Import router modules import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; //Import service import { AuthService } from './auth.service'; @Injectable() export class AuthGaurd implements CanActivate { constructor(private authService: AuthService){}; canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){ return this.authService.isAuthenticated(); } }
One last thing, here, apply global CSS for validation messages, path is src/style.css
/* You can add global styles to this file that will be applied to whole Angular 4 Firebase Authentication Project, and also import other style files */ input.ng-invalid.ng-touched{ border: 1px solid red; } p.help-block{ color: red; }
Finally, put all together and you’re ready to run this Angular 4 Firebase Authentication App
Run your app, and see the application in your browser @ http://localhost:4200
angular4-fireabse-auth > ng serve
Here, suggested visit, Deep dive into Angular 4 Reactive Forms
To conclude, I hope, you love this tutorial and you’re ready to apply Angular 4 Firebase Authentication for your web application. If you’ve any questions/suggestions, hit the comments below.
Happy Coding!
I cannot seem to import auth.service.ts. It fails to import to my sign-up and sign in componenets as well as my app.module.ts. Basically anywhere I need to import auth.service.ts it errors saying it cannot find module. I have triple checked that I have the file structure wrong so any help would be appreciated! Thanks for the tutorial!
I meant file structure right*
It was a typo on my end. Carry on…
Sorry, for the late response.
And glad to see that it’s working for you!
Your welcome 🙂