Angular 4 Authentication Tutorial With Firebase

Angular 4 Authentication Tutorial with Firebase

In this tutorial i will go through the Authentication basics in Angular 4, i will show you how it's working and how to create a simple one.

How does Authentication work ?

Since Angular is a frontend scripting language it won't be opening a session with the backend, it will be sending the auth. information to the server using an api or else to verify, since you don't want to keep authenticating everytime the client wants to check information Angular will send a token to be used to keep/remember logged in users.

 

Steps to Create Authentication in Angular 4

I will start by creating two components which one will be responsible for new users to signup while the other to sign in.

From CMD "Inside project folder"

ng g c signup --spec false
ng g c signin --spec false

 

Expected output:

C:\angular4QuickStart\authExample>ng g c signup --spec false
installing component
 create src\app\signup\signup.component.css
 create src\app\signup\signup.component.html
 create src\app\signup\signup.component.ts
 update src\app\app.module.ts

C:\angular4QuickStart\authExample>ng g c signin --spec false
installing component
 create src\app\signin\signin.component.css
 create src\app\signin\signin.component.html
 create src\app\signin\signin.component.ts
 update src\app\app.module.ts

 

signup.component.html

ngSubmit -- This part will send all submit information to onSup function which we will create later in the ts file.

I will also add an email text box and password.

<form (ngSubmit)="onSup(sForm)" #sForm="ngForm">
<div class="form-group">
<label for="email">Email</label>
<input type="email"id="email"name="email"ngModel required>
<label for="password">Password</label>
<input type="password"id="password"name="password"ngModel required>
</div>
<button type="submit">Sign Up</button>
</form>

signup.component.ts

First we need to import NgForm since we will be using it

import {NgForm} from '@angular/forms';

Add Signup Page using Routing

To be able to add a link that will load different component html pages i will create routing, for Angular 4 routing tutorial please check this link.
app.module.ts

import { RouterModule, Routes } from '@angular/router';

Add in the imports::

RouterModule.forRoot([
{path: 'signup', component: SignupComponent},
])

 

app.component.html

<a routerLink="/signup">Signup</a>
<router-outlet></router-outlet>

 

Google Firebase

Firebase Signup

If you have a google account then you don't need to do anything, just go to firebase.com and select 'GO TO CONSOLE'.

Create your first Firebase project

  • Select 'Add project'.
  • Add project name and select 'Create Project'
  • After that you will be brought to your project page showing list of all the features.

Create Database Permissions

  • Select database.
  • Go to rules
  • Keep auth != null to have it only when authenticated

Enable Authentication Service

  • Select 'Authentication'.
  • Select 'Set Up Sign-In Method'.
  • You will have several Sign-in options so you can use in your application like:
    • Email
    • Phone
    • Google
    • Facebook
    • Twitter
    • Github
    • Anonymous
  • Select the ones you would like to enable and click on then click on enable, for this tutorial choose Email.
  • Save.

 

Authentication Backend

For the backend i will be using Google Firebase for Authentication handling, i will be also using it's SDK, first i will statr by installing the SDK to my project by running the following command from the project folder.

npm install --save firebase
npm install promise-polyfill --save-exact

 

Credential Authentication Service

Now i will create a service to use it for authentication

ng g s authServ

Now the TypeScript file was created with all needed code and we need to provide it first to be used.

Import Firebase SDK

app.component.ts

import { Component, OnInit } from '@angular/core';
import * as firebase from 'firebase';
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
firebase.initializeApp({
apiKey:"AIzaSyCaGb5t7AXKUdxg5l45YkoMMet0xrcW1oQ",
authDomain:"dotsway-b0cb3.firebaseapp.com"
});
}
title='app works!';
}

auth-serv.services.ts

Add below colored part:

import { Injectable } from '@angular/core';
import * as firebase from 'firebase';
@Injectable()
export class AuthServService {
sUpFunc(email: string, password: string){

 

firebase.auth().createUserWithEmailAndPassword(email,password){}
}
constructor() { }
}
app.module.ts
import {AuthServService} from './auth-serv.service'
providers: [AuthServService],

signup.component.ts

import { Component, OnInit } from '@angular/core';
import {NgForm} from '@angular/forms';
import {AuthServService} from '../auth-serv.service'
@Component({
selector:'app-signup',
templateUrl:'./signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
constructor(private authServService:AuthServService) { }
ngOnInit() {
}
onSup(form: NgForm) {
const email = form.value.email;
const password = form.value.password;
this.authServService.sUpFunc(email,password);
}
}

Add Sign In Page to Angular 4 Authentication Project

 signin.component.html

Copy the content  of  signup.component.html to the singin component html while changing the colored part only.

<form (ngSubmit)="onSin(sForm)" #sForm="ngForm">
<div class="form-group">
<label for="email">Email</label>
<input type="email"id="email"name="email"ngModel required>
<label for="password">Password</label>
<input type="password"id="password"name="password"ngModel required>
</div>
<button type="submit">Login</button>
</form>
signin.component.ts
Copy the content  of  signup.component.ts to the singin component ts while changing the colored part only.
import {NgForm} from '@angular/forms';
Under ngOnInit part:
onSin(form: NgForm) {
const email = form.value.email;
const password = form.value.password;
this.authServService.sInFunc(email,password);
}
auth-serv.service.ts
Copy the sUpFunc and paste it under it and just replace the colored part
sInFunc(email: string, password: string){
firebase.auth().signInWithEmailAndPassword(email,password)
.catch(
error => console.log(error)
)
}
signin.component.ts
import { AuthServService } from '../auth-serv.service';
and add below inside the constructor:
constructor(private authServService:AuthServService) { }

Add Sign-In Route

app.module.ts
Inside the RouterModule.forRoot

{path: 'signin', component:SiginComponent},

Add hyperlink
app.component.html
<a routerLink="/signin">Login</a>

Log the response

auth-serv.service.ts

sInFunc(email: string, password: string){
firebase.auth().signInWithEmailAndPassword(email,password)
.then(response => console.log(response))
.catch(
error => console.log(error)
)
}

Requiring a Token

Next step is to require a token to keep the user logged in instead of authenticating with each request.

Subscribe to
for video tutorials updates