You've successfully subscribed to Smartcodehub ™ Blog
Great! Next, complete checkout for full access to Smartcodehub ™ Blog
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Ionic 5 Auth Guard Implementation

Ionic 5 Auth Guard Implementation

Auth guard is the guard which helps developer to not allow unauthenticated user to there website content or mobile application like ionic, basically we can give security to perticular route in angular application.

Abhishek Dana
Abhishek Dana

Hello there, in this blog we are going to learn how we can implement auth guard in ionic 5 angular with the help of localstorage.So before getting started let me discuss about what basically auth guard is and why we are using it in almost every angular application.

What is auth guard ?

So basically auth guard is the guard which helps developer to not allow unauthenticated user to there website content or mobile application like ionic, basically we can give security to perticular route in angular application.

Why to use auth guard ?

Most of the time unauthenticated user's get access to some private content of application which a developer don't want to show to unauthenticated user if the user is authenticated then only users can go through that content so that we get to know which user have gone through this post.

In this blog we are going to use auth guard so auth security that means if user is not loggedIn to application then they should be navigated to login page else they need to navigate to home page.

Let's get started by creating a blank application in ionic 5 using the above command

ionic start auth-implementation

After generating the project open up the project in code editor and open up terminal to generate some services and guard file.

After opening in code editor and opening terminal we need to write below command to generate some page like login , register.

ionic g page login

ionic g page register

After generating page we need to generate our auth guard and auth service to generate it we need to run the following commands

ionic g guard auth

ionic g service auth

After generating head over to app.module.ts and add auth service to provider


import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { RouteReuseStrategy } from "@angular/router";

import { IonicModule, IonicRouteStrategy } from "@ionic/angular";
import { SplashScreen } from "@ionic-native/splash-screen/ngx";
import { StatusBar } from "@ionic-native/status-bar/ngx";

import { AppComponent } from "./app.component";
import { AppRoutingModule } from "./app-routing.module";
import { AuthService } from './auth.service'; // Here is the import line
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    AuthService, // Here is the auth Service 
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }

After adding auth service to app module we need change our route in app-routing.module.ts with the following content...

import { NgModule } from "@angular/core";
import { PreloadAllModules, RouterModule, Routes } from "@angular/router";

const routes: Routes = [
  {
    path: "",
    redirectTo: "login",
    pathMatch: "full",
  },
  {
    path: "login",
    loadChildren: () =>
      import("./login/login.module").then((m) => m.LoginPageModule),
  },
  {
    path: "register",
    loadChildren: () =>
      import("./register/register.module").then((m) => m.RegisterPageModule),
  },
  {
    path: "home",
    loadChildren: () =>
      import("./home/home.module").then((m) => m.HomePageModule),
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }),
  ],
  exports: [RouterModule],
})
export class AppRoutingModule {}

After changing the router module we need to first generate user model basically we are going to define the properties of user like email , password , name , accessToken to do that we need to create a file in src/app with name user.ts After creating file we need to add the following content

export class User {
    name?: string;
    email?: string;
    password?: string;
    accessToken?: string;
}

After that we need to make our login and register form for that you can design by your self here i am just demonstrating the what will happen on login button and register button

login() {
    this.authService.login(this.user).then(resp => {
    	if(resp) {
        	localstorage.setItem('user' , resp.accessToken);
        }
    }).catch(error => {
    	console.log(error);
    })
}

here on getting response i am saving it to localstorage will see this why did we save our accessToken to localstorage And in register page we need to write

register() {
	this.authService.register(this.user).then(resp => {
    	console.log(resp);
    }).catch(error => {
    	console.log(error);
    })
}

And Finally in auth.service.ts file we need to write code for login , register , to get token

import { Injectable } from '@angular/core';

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

  constructor(private http: HttpClient) { }
  
  register(user) {
  	return this.http.post('YOUR-API-URL/User' , user);
  }
  
  login(user) {
  	return this.http.post('YOUR-API-URL/User/login' , user);
  }
  
  getToken() {
  	return !!localstorage.get('user')
  }
}

Here we have user getToken funcation which will get token that we have saved in localstorage which we have already save in localstorage in login funcation. Now we need to do changes in our authGuard file

import { AuthService } from "./auth.service";
import { Injectable } from "@angular/core";
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree,
  Router,
} from "@angular/router";
import { Observable } from "rxjs";

@Injectable({
  providedIn: "root",
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}
  canActivate(): boolean {
    if (!this.authService.gettoken()) {
      this.router.navigateByUrl("/login");
    }
    return this.authService.gettoken();
  }
}

And Now we need to change in app-routing.module.ts adding the guard to home page so that unauthenticated user cannot access to home route without login...

{
    path: "home",
    loadChildren: () =>
      import("./home/home.module").then((m) => m.HomePageModule),
      canActivate: [AuthGuard] // Just add this line to your home page route
  },

Bonus point

Now if you want your user to redirect to homepage directly if user has already loggedIn the this can easily be done with the help of getToken funcation just use it in app.component.ts file

// Inside InitializeApp Funcation just add this 

initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      if (!this.authService.getToken()) {
        this.route.navigate(["login"]);
      } else {
        this.route.navigate(["home"]);
      }
      
      
    });
  }

That's it we have successfully implemented auth guard to our application and even we have setup a small authentication for ionic 5 application.

Hope you guy's like it 😊

Stay tuned for more interesting topics 😊