← Back to list

Navigating Authentication in Angular 17: Deconstructing the Deprecated ‘CanActivate’

What are Auth Guards and Why they are used?

Parvatichad · 2024-01-11 06:18 · 0 claps · 5.4 min read
#canactivate #authguard #angular-authentication #authentication
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Navigating Authentication in Angular 17: Deconstructing the Deprecated ‘CanActivate’

What are Auth Guards and Why they are used?

Auth Guards provided by Angular that are used to control behaviour during navigation to and from various routes in the application.

Routes are used to define public and private paths in the application that help a user to navigate from one component/ module to another.

Sometimes you might need to restrict certain pages/routes to the user, in your angular application. For instance, there might be a page that can only be supposed to accessed by logged-in users. So it would be great if we could prevent users from going to this page without login into the system. This kind of functionality can be achieved by route guards.

Auth Guards as the name sounds act as a gatekeeper, determining whether a user can access a specific route based on conditions such as authentication status or user permissions.

here are several router guards provided by angular and each one takes care of different purposes. Here we are focusing on the most common use case of router guards, preventing access of particular routes of the application to some users using canActivate route guard.

How Auth Guard Implementation has Changed in Anguar 17?

Angular version 17 introduced a new syntax for creating route guards that do not require the use of interfaces.

According to official Angular docs, we can create a custom functional class that will inject the and Auth Service and Router service to control the navigational behaviour behind our Guards.

Let’s jump into the practical implementation of our canActivate class in a sample Students application. In this Students app, a user can only be allowed to view Students details, if it is logged in. Else the navigation will redirect to the Login page.

Let’s begin the journey.

Step 1: Project Setup

Start by creating a new Angular project using the Angular CLI:

ng new angular-auth-guards-example
cd angular-auth-guards-example

Step 2: Creating Components

Generate the necessary components to illustrate the functionality:

ng generate component employee
ng generate component employee-details
ng generate component login

These components will help us visualize the different parts of our application and how route protection works.

Step 3: Implementing Auth Guard and Service

AuthGuard

Create an **AuthGuard** to protect routes based on authentication status:

ng generate guard auth/auth

Edit the generated **auth.guard.ts** file:

import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard = () => 
  const authService = inject(AuthService);
  const router = inject(Router);
  if (authService.isLoggedIn) {
    return true
  }
  // Redirect to the login page
  return router.parseUrl('/login');
};

AuthService

Generate an authentication service to simulate login/logout functionality:

ng generate service auth/auth

Edit the generated **auth.service.ts** file:

// auth.service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { tap, delay } from 'rxjs/operators';
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  isLoggedIn = false;
  redirectUrl: string | null = null;
  login(): Observable<boolean> {
    return of(true).pipe(
      delay(1000),
      tap(() => (this.isLoggedIn = true))
    );
  }
  logout(): void {
    this.isLoggedIn = false;
  }
}

Step 4: Configuring Route Protection

Utilize the **canActivate** guard in your routing module to secure specific routes:

Edit the **app.routing.ts** file:

// app-routing.module.ts
import { RouterModule, Routes } from '@angular/router';
import { EmployeeComponent } from './student-list/student-list.component';
import { EmployeeDetailsComponent } from './student-details/student-details.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth/auth.guard';
export const routes: Routes = [
  // ... other routes ...
  {
    path: 'employee/:id',
    component: EmployeeDetailsComponent,
    canActivate: [AuthGuard],
  },
  // ... other routes ...
];

Step 5: Enhancing User Experience

Improve the user experience by implementing the login functionality:

Edit the **login.component.ts** file:

typescriptCopy code
// login.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth/auth.service';
@Component({
  // ... component details ...
})
export class LoginComponent {
  constructor(private authService: AuthService, private router: Router) {}
  login(): void {
    this.authService.login().subscribe(() => {
      if (this.authService.isLoggedIn) {
        const redirectUrl = this.authService.redirectUrl
          ? this.authService.redirectUrl
          : '/employee';
        this.router.navigate([redirectUrl]);
      }
    });
  }
}

Conclusion

As we bid adieu to the deprecated ‘CanActivate’ interface in Angular 15, the realm of authentication remains rich with possibilities. Beyond the traditional guard approach, several alternative methods and concepts stand ready to bolster your authentication strategies:

1. CanLoad Guard:

The **CanLoad** guard allows you to prevent the loading of feature modules until certain conditions are met, making it an excellent choice for optimizing performance and reducing unnecessary network requests.

2. CanActivateChild Guard:

Navigating within a protected route often involves child routes. The **CanActivateChild** guard empowers you to secure these child routes independently, offering finer-grained control over access.

3. Resolver:

Resolvers enable you to fetch necessary data before activating a route, a process that can be tightly integrated with authentication. By combining a resolver with authentication checks, you can ensure that users have the required data and permissions before accessing a protected route.

4. Role-Based Access Control (RBAC):

RBAC introduces a hierarchical access control system based on user roles. By associating roles with routes and components, you can enforce granular access control and tailor the user experience to specific roles within your application.

5. Third-Party Authentication Providers:

Leveraging third-party authentication providers like OAuth 2.0 or OpenID Connect can streamline the authentication process, enhancing security and offering seamless single sign-on experiences for your users.

6. JWT (JSON Web Tokens):

Implementing JWT-based authentication can simplify the management of user sessions. JWTs are self-contained tokens that carry user information and can be verified to ensure authenticity, reducing the need for server-side session storage.

7. Multi-Factor Authentication (MFA):

Enhance security by implementing MFA, requiring users to provide multiple forms of verification before accessing protected routes. MFA adds an extra layer of protection against unauthorized access.

8. Firebase Authentication:

Firebase provides a robust authentication service that can seamlessly integrate with your Angular application. It supports various authentication providers and offers features like passwordless sign-in and email verification.

As Angular continues to evolve, so do the tools at your disposal for crafting secure, efficient, and user-friendly authentication systems. By exploring these alternative methods and adapting them to your application’s needs, you can navigate the ever-changing landscape of authentication with confidence and innovation.

Conclusion: Embracing Diverse Authentication Strategies

As we bid adieu to the deprecated ‘CanActivate’ interface in Angular 15, the realm of authentication remains rich with possibilities. Beyond the traditional guard approach, several alternative methods and concepts stand ready to bolster your authentication strategies:

1. CanLoad Guard:

The **CanLoad** guard allows you to prevent the loading of feature modules until certain conditions are met, making it an excellent choice for optimizing performance and reducing unnecessary network requests.

2. CanActivateChild Guard:

Navigating within a protected route often involves child routes. The **CanActivateChild** guard empowers you to secure these child routes independently, offering finer-grained control over access.

3. Resolver:

Resolvers enable you to fetch necessary data before activating a route, a process that can be tightly integrated with authentication. By combining a resolver with authentication checks, you can ensure that users have the required data and permissions before accessing a protected route.

4. Role-Based Access Control (RBAC):

RBAC introduces a hierarchical access control system based on user roles. By associating roles with routes and components, you can enforce granular access control and tailor the user experience to specific roles within your application.

5. Third-Party Authentication Providers:

Leveraging third-party authentication providers like OAuth 2.0 or OpenID Connect can streamline the authentication process, enhancing security and offering seamless single sign-on experiences for your users.

6. JWT (JSON Web Tokens):

Implementing JWT-based authentication can simplify the management of user sessions. JWTs are self-contained tokens that carry user information and can be verified to ensure authenticity, reducing the need for server-side session storage.

7. Multi-Factor Authentication (MFA):

Enhance security by implementing MFA, requiring users to provide multiple forms of verification before accessing protected routes. MFA adds an extra layer of protection against unauthorized access.

8. Firebase Authentication:

Firebase provides a robust authentication service that can seamlessly integrate with your Angular application. It supports various authentication providers and offers features like passwordless sign-in and email verification.

As Angular continues to evolve, so do the tools at your disposal for crafting secure, efficient, and user-friendly authentication systems. By exploring these alternative methods and adapting them to your application’s needs, you can navigate the ever-changing landscape of authentication with confidence and innovation.


메타데이터
post_id
ee25dd93d690
slug
navigating-authentication-in-angular-17-deconstructing-the-deprecated-canactivate-ee25dd93d690
url
https://medium.com/@parvatichad012/navigating-authentication-in-angular-17-deconstructing-the-deprecated-canactivate-ee25dd93d690
canonical_url
https://medium.com/@parvatichad012/navigating-authentication-in-angular-17-deconstructing-the-deprecated-canactivate-ee25dd93d690
author_url
https://medium.com/@parvatichad012
status
ok
fetched_at
2026-07-11 16:18:17