Ionic 6: Adding Auth Guards in Angular to Limit Page Access

In this tutorial, we will be discussing how to add Auth Guards in an Ionic 6 Angular application to limit page access. Auth Guards are used to restrict access to certain pages in the app based on user authentication status. This can be useful for pages that contain sensitive information or require a user to…

By.

•

min read

In this tutorial, we will be discussing how to add Auth Guards in an Ionic 6 Angular application to limit page access. Auth Guards are used to restrict access to certain pages in the app based on user authentication status. This can be useful for pages that contain sensitive information or require a user to be logged in to access.

 

How to use Auth Guards in Ionic Angular App?

Follow these quick steps to implement Auth Guards in the Ionic Angular app.

Step 1: Create a new Ionic 6 Angular application
Step 2: Create an Auth Service
Step 3: Add Auth Guard
Step 4: Implement Auth Service
Step 5: Implement Auth Guard
Step 6: Add Auth Guard to Router
Step 7: Add Login and Logout functionality
Step 8: Test the App

 

Prerequisites

Before we begin, make sure you have the following installed:

  • Node.js
  • Ionic 6 CLI
  • Angular CLI

 

Step 1: Create a new Ionic 6 Angular application

To create a new Ionic 6 Angular application, open the command prompt and run the following command:

ionic start myApp blank --type=angular

This will create a new Ionic 6 Angular application with the name “myApp” in a new directory.

 

Step 2: Create an Auth Service

To create an Auth Service, open the command prompt and navigate to the root of your Ionic 6 Angular application. Run the following command:

ionic g service services/auth

This will create a new Auth Service in the “src/app/services” directory.

 

Step 3: Add Auth Guard

To add an Auth Guard, open the command prompt and navigate to the root of your Ionic 6 Angular application. Run the following command:

ionic g guard guards/auth

This will create a new Auth Guard in the “src/app/guards” directory.

 

Step 4: Implement Auth Service

Open the “src/app/services/auth.service.ts” file and implement the Auth Service. In this example, we will be using a simple isLoggedIn variable to keep track of the user’s authentication status.

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

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

  isLoggedIn: boolean = false;

  login() {
    this.isLoggedIn = true;
  }

  logout() {
    this.isLoggedIn = false;
  }
}

 

Step 5: Implement Auth Guard

Open the “src/app/guards/auth.guard.ts” file and import the Auth Service. Implement the Auth Guard by using the canActivate() method and check the user’s authentication status before allowing access to the page.

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (!this.auth.isLoggedIn) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}

 

Step 6: Add Auth Guard to Router

Open the “src/app/app-routing.module.ts” file and import the Auth Guard. Add the Auth Guard to the routes to which you want to restrict access.

import { AuthGuard } from './guards/auth.guard';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: './home/home.module#HomePageModule' },
  { path: 'restricted', loadChildren: './restricted/restricted.module#RestrictedPageModule', canActivate: [AuthGuard] },
  { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
];

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

In this example, we have added the Auth Guard to the “restricted” route, which means that the user will only be able to access this page if they are logged in.

 

Step 7: Add Login and Logout functionality

To add login and logout functionality, you can add buttons to your login and restricted pages that call the login() and logout() methods of the Auth Service respectively.

<ion-button (click)="auth.login()">Login</ion-button>
<ion-button (click)="auth.logout()">Logout</ion-button>

 

Step 8: Test the App

To test the app, run the following command:

ionic serve

You should now be able to navigate to the “home” and “login” pages without any restrictions, but when you try to access the “restricted” page, you will be redirected to the “login” page if you are not logged in.

 

Other Uses

Auth Guards can also be used in combination with other types of guards such as Role-based access control or CanDeactivate to create more advanced access control mechanisms in your application.

 

Conclusion

In this tutorial, we have discussed how to add Auth Guards in an Ionic 6 Angular application to limit page access. We have shown how to create an Auth Service and Auth Guard, and how to use them to restrict access to certain pages in the app based on user authentication status. This can be a useful tool for protecting sensitive information or requiring a user to be logged in to access certain features of your app.

Leave a Reply

Your email address will not be published. Required fields are marked *