free web tracker

Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

Authentication with Authguard in Ionic 4

Ionic 4 is using Angular Routing, so it becomes very simple to add authentication in an Ionic application using Auth Guards.

The Ionic Auth Guards are the Ionic version of the Angular Navigation Guards. Here in this blog we will explain what is Ionic guard and How to use Authguard in Ionic 4.

How to use ionic guard


What is Ionic Guard

  • Route guards create the process of protecting few routes and redirecting the user quite simple.
  • Ionic guards like ionViewCanEnter to determine whether or not a user could navigate to a page.
  • The basic idea behind a route guard is that you attach a service which acts as the “route guard” to a particular route.

  • 1. canActivate

  • Service has a canActivate method which will result either true or false depending on whether the user should be permitted to go to that route or not.
  • If the canActivate method result false, then the user will unable to access the route.

  • 2. canLoad

  • we could also use canLoad instead of canActivate to entirely prevent the loading of the children for that route (rather than just preventing access).
  • canLoad guard is used to decide if a module can be loaded or not.
  • How to implement Auth guard

    $ ionic generate guard auth
    

    import { Injectable } from '@angular/core';
    import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    import { Observable } from 'rxjs';
    import { Storage } from '@ionic/storage';
    
    @Injectable({
    providedIn: 'root'
    })
    export class AuthGuard implements CanActivate {
    
    constructor(private router: Router, private storage: Storage) { }
    
    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable | Promise {
    return new Promise((resolve) => {
    this.storage.ready().then(() => {
    const token = localStorage.getItem('token');
    
    if (token) {
    resolve(true);
    } else {
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    resolve(false);
    }
    });
    });
    }
    

    import { NgModule } from '@angular/core';
    import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
    import { AuthGuard } from './core/auth/auth-guard.service';
    
    const routes: Routes = [{
    path: 'login',
    loadChildren: './pages/login/login.module#LoginPageModule'
    }, {
    path: '',
    loadChildren: './tabs/tabs.module#TabsPageModule',
    canActivate: [AuthGuard]
    }];
    
    @NgModule({
    imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
    exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    Steps to create Ionic application with Authguard

    1. Open visual studio code and then open terminal in it.
    2. Write command like “ionic start Demo —tabs”
    3. Open the recently made application in visual studio code.
    4. Type command like “ionic serve”. So it will run our application into our system default browser.
    5. If you want to run out application in simulators, then there will be command like “ionic cordova run ios”.
    6. To create login page there will be command like “ionic g page login”.
    7. So the routing of login will be create at “app-routing.module.ts” file.
    8. Now we want to restrict our user to access our main tab bar pages without authorization token. For that we will create new module related to core module with the command like “ionic g m core”.
    9. We have to create Authguard via this command like “ionic g guard core/auth”. It will generate the guard in core folder.
    10. Then create an activate method that will be used to make route for tabs or login as per the authorization token which we obtained at the time of login.
    11. Now install storage plugin for ionic 4. That will be used to store token.
    12. Import our ionic storage module in “app.module.ts” file.
    13. Inject storage from Ionic storage module in auth guard file which is used for validation of authorization token.
    14. We will do same business logic which can activate method that if we got the token then we have to navigate to our tabs screens otherwise move user to login screens.
    15. Now use same activate method in “app-routing.module.ts” file to prevent user to navigate to tabs screen with the guard file with the code like “canActivate: [AuthGuard]”.
    16. Create some login page to add email and password things for user with the reactive forms
    17. So for that we have to import reactive forms module in “login.module.ts”
    18. Do some validation for email and password as in-built validation provided in angular reactive forms?
    19. Do some business logic like if our form is valid then store our authorization token into local storage and navigate to tabs screen.
    20. If we want to make some custom service that will handle our toast messages, then create toast service in our core folder with the command like “ionic g s core/toast”
    21. Now import toast controller into toast service file and add method to present our dynamic toast messages
    22. Now we want to use toast service in login screen so we have to import our toast service in “login.module.ts” file in “providers” array.
    23. If you want to change any theme color of login page then we can easily change from “variables.scss” file.
    24. Now all things are set and we have to run our application with command as described in step 4 or 5.
    25. Now if we want to add Android platform then just write command like “ionic cordova platform add android”
    26. After successfully adding platform, just run the command like “ionic cordova run android --device”. So it will run our app into android device
    27. Now first it will display login screen and we have to login with our credentials and if our form is valid then app will redirect to tabs screen.
    28. Now first it will display login screen and we have to login with our credentials and if our form is valid then app will redirect to tabs screen.
    29. At last router will redirect to login page.

    These are the steps to create Ionic application using Authguard, it is very common and acquired by most of the real world and many Ionic Mobile Application Development Companies.