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.
[js]
ng new angular4-fireabse-auth
[/js]
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.
[js]
npm install –save bootstrap
[/js]
Apply bootstrap, add/modify the style block with bootstrap css in your .angular-cli.json file.
[js]
“styles”: [
“../node_modules/bootstrap/dist/css/bootstrap.min.css”,
“styles.css”
]
[/js]
Now, let’s install firebase in your Angular project.
[js]
npm install –save firebase
[/js]
Next, generate components sign-up, sign-in and home.
[js]
ng generate component auth/sign-up –spec false
[/js]
[js]
ng generate component auth/sign-in –spec false
[/js]
Furthermore, we can use short forms also, as shown below.
[js]
ng g c Home
[/js]
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
[js]
//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 { }
[/js]
Next, let’s define the app component, path is src/app/app.component.ts
[js]
//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;
}
}
[/js]
Next, let’s see the app component HTML, path is src/app/app.component.html
[html]
Welcome to {{title}}!
[/html]
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
[js]
//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’]);
}
}
[/js]
Next, sign up HTML path is src/app/auth/sign-up/sign-up.component.html
[html]
Sign Up Form
[/html]
Similarly, let’s dig into sign in, path is src/app/auth/sign-in/sign-in.component.ts
[js]
//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);
}
}
[/js]
Sign-in HTML, path is src/app/auth/sign-in/sign-in.component.html
[html]
Sign In Form
[/html]
Finally, see the Home page, just have a simple HTML over there, path is src/app/home/home.component.html
[html]
Welcom to Home of Angular 4 Firebase Authentication App!
[/html]
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
[js]
//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;
}
}
[/js]
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
[js]
//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();
}
}
[/js]
One last thing, here, apply global CSS for validation messages, path is src/style.css
[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;
}
[/css]
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
[js]
angular4-fireabse-auth > ng serve
[/js]
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 🙂