circuit

Use Angular Route-Guards to Secure Angular Pages

By allow, deny or redirect to other page-view. It's very simple to secure Angular pages using route-guards.




Ionic4 hide header on scroll.

A route guard is an important feature of the Angular Router that allows or denies the user access to the route pages based on some logic, based on weather user is logged in or not.

  • ROUTE-GUARDS are very much important in web app having login/logout scenarios.

  • It's commonly used to check if a user is logged in and has the authorization to access a page.

  • We can easily manage which page is allowed for logged in user and which for non-logged in users.

IMPLEMENTATION OF ROUTE GUARDS

We can add a route guard by implementing the CanActivate interface available from the @angular/router package and extends the canActivate() method which holds the logic to allow or deny access to the route.

For example, the following guard will check value of userLoggedIn and allow access to a route accordingly**: ** (Don't worry about the code - we'll understand everything in detail.)

class AuthGuardService implements CanActivate {
  userLoggedIn = false;

canActivate() {
    if (this.userLoggedIn) {
     return true;
    } else {
     return false;
    }
  }
}

We can now protect a route with the guard using the canActivate attribute:

const routes: Routes = [
  {
    path: 'user/:id',
    component: UserDetailComponent,
    canActivate:[AuthGuardService]
  }
];

The above code is about β€œRouting of an Angular Component”. Click here πŸ‘† to learn more about Angular-Routing.

We can apply ' Route Guards' to an authenticated area of our web app, or an admin section that requires special permissions to be accessed. In the following code sample we will see a very simple implementation of a route guard.

Create the Guard

We will create a service first, but to create a Guard we must implement the canActivate. Let's create a AuthGuardService run this command in your terminal/command-prompt:

ng g s service/AuthGuard

This command will generate two TypeScript file β€” look belowπŸ‘‡

#1 Create AuthGuardService

Next, open the src/app/service/auth-guard.service.ts file and update it as follows**:** (I did import and use AuthService in this codeπŸ‘‡πŸ‘‡ to learn more about AuthService Click hereπŸ‘†)

#2 Register AuthGuardService

We can now register this AuthGuardService in the Angular route definition. Open the src/app/app-routing.module.ts file and update it as follows**:**πŸ‘‡πŸ‘‡ (feel free to change value of 'path' and 'component' accordingly)

Note: the security doesn't make sense on the client side. Rather we use route guards (or any other mechanisms) are all UX features, as we prevent the user from entering an area where he is not allowed to enter. But, the final security checks should always done at the server side.

Blocking is not enough

Just returning true or false is actually not enough. We need to tell the user what happened, why they not allowed to enter into the page. Either by displaying some notification or most often by redirecting to some other page view.

We can do that by injecting the router into the AuthGuard and redirect to other page view. See this: πŸ‘‡πŸ‘‡

#3 Modifying AuthGuardService

(Learn more about 'Type Observable' and 'Manage Subscriptions in Angular' β€” Click hereπŸ‘†)

  • Once we attach this guard to a route, the canActivate() method will fire before the route is activated, means before it opens the actual path or before it loads actual component.
  const routes: Routes = [
  {
    path: 'user/:id',
    component: UserDetailComponent,
    canActivate:[AuthGuardService]
  }
  ];
  • The logic will first check if the user is valid, and if not it will navigate to the login route.

  • Note it also grabs the current URL and sets is as a query parameter, so it would be something like /login?return=%2Fusers%2Fabc123 (the URL is encoded). This is the case when we are trying to access user like this: /users/abc123 and the canActivate detects it unauthorized user.

Conclusion

  1. Create AuthGuardService
  2. Register AuthGuardService
  3. Modifying AuthGuardService

Done! 🀩 It's that simple to secure pages using route-guards. See you later πŸ‘‹πŸ‘‹

Learn More




Continue Learning