Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3813

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T06:11:10+00:00 2024-11-26T06:11:10+00:00

Create configurable Angular guards

  • 61k

When building web application, from time to time we have to protect routes from unauthorized access. In Angular, we can do this by using router guards.

This is not an intro to Angular guards, so if you are not familiar with them, you can read more about them in the official documentation.

In this article, we will see how we can create configurable Angular guards. We will create a guard that will check if the logged in user has a specific role, and if not, it will redirect the user to an unauthorized page.

We will use a fake AuthService that will have a method to check if the logged in user has a specific role.

// auth.service.ts export const ROLES = {   ADMIN: 'ADMIN',   MANAGER: 'MANAGER', };  @Injectable({ providedIn: 'root' }) export class AuthService {   userRole = ROLES.ADMIN;    hasRole(role: string): boolean {     return this.userRole === role;   } } 
Enter fullscreen mode Exit fullscreen mode

Before Angular 14 we had class based guards, and a basic solution for our problem would be to create a class based guard for each role and apply it to the routes that we want to protect.

But, this solution is not very flexible, because we have to create a new guard for each role, and if we want to add a new role, we have to create a new guard and apply it to the routes that we want to protect.

This is not very convenient, and it can lead to code duplication.

It would look something like this:

// admin.guard.ts @Injectable({ providedIn: 'root' }) export class AdminGuard implements CanActivate {   authService = inject(AuthService);   router = inject(Router);    canActivate(): boolean | UrlTree {     const hasAccess = this.authService.hasRole(ROLES.ADMIN);     return hasAccess ? true : this.router.createUrlTree(['/unauthorized']);   } } 
Enter fullscreen mode Exit fullscreen mode

// manager.guard.ts @Injectable({ providedIn: 'root' }) export class ManagerGuard implements CanActivate {   authService = inject(AuthService);   router = inject(Router);    canActivate(): boolean | UrlTree {     const hasAccess = this.authService.hasRole(ROLES.MANAGER);     return hasAccess ? true : this.router.createUrlTree(['/unauthorized']);   } } 
Enter fullscreen mode Exit fullscreen mode

And then we would apply the guards to the routes that we want to protect:

// routes.ts export const routes: Routes = [   { path: 'home', component: HomeComponent },   { path: 'admin', component: AdminComponent, canActivate: [AdminGuard] },   { path: 'manager', component: ManagerComponent, canActivate: [ManagerGuard] },   { path: 'unauthorized', component: NotAuthorizedComponent }, ]; 
Enter fullscreen mode Exit fullscreen mode

As we can see, we have a lot of duplicated code! Let's improve this by creating a configurable guard.

Configurable class-based guard

Angular Router provides a data field in the route that we can use to pass data to the guard. We can use this data field to pass the role that we want to check. This way, we can create a single guard that will check the role that we pass in the data field.

// role.guard.ts @Injectable({ providedIn: 'root' }) export class RoleGuard implements CanActivate {   authService = inject(AuthService);   router = inject(Router);    canActivate(route: ActivatedRouteSnapshot): boolean | UrlTree {     // Get the role from the route data     const role = route.data.role;     const hasAccess = this.authService.hasRole(role);     return hasAccess ? true : this.router.createUrlTree(['/unauthorized']);   } } 
Enter fullscreen mode Exit fullscreen mode

And then we would apply the guard to the routes that we want to protect:

// routes.ts export const routes: Routes = [   { path: 'home', component: HomeComponent },   {      path: 'admin',      component: AdminComponent,      canActivate: [RoleGuard],      data: { role: ROLES.ADMIN },   },   {      path: 'manager',      component: ManagerComponent,     canActivate: [RoleGuard],     data: { role: ROLES.MANAGER },   },   { path: 'unauthorized', component: NotAuthorizedComponent }, ]; 
Enter fullscreen mode Exit fullscreen mode

The code is much cleaner now, and we don't have any duplicated code. But, the only issue with this approach is that is not typechecked. We can pass any string in the data field, and the guard will not complain. We can improve this creating an interface for the data field, and then we can use this interface to type the data field.

interface RoleGuardData {   role: 'ADMIN' | 'MANAGER'; // We can add more roles here or infer them from the AuthService }  // And then we can use this interface to type the data field:  export const routes: Routes = [   {      // ...     data: { role: ROLES.MANAGER } as RoleGuardData,   }, ]; 
Enter fullscreen mode Exit fullscreen mode

Now, if we try to pass a string that is not a valid role, we will get a type error.

Configurable function-based guard

In Angular 14, we got function-based guards. This means that we can create a function that will return a guard. This is very useful because we can create a function that will return a guard for a specific role, and then we can apply this function to the routes that we want to protect.

// role.guard.ts export const roleGuard = (role: 'MANAGER' | 'ADMIN'): CanActivateFn => {   const guard: CanActivateFn = () => {     const authService = inject(AuthService);     const router = inject(Router);      const hasAccess = authService.hasRole(role);     return hasAccess ? true : router.createUrlTree(['/unauthorized']);   };    return guard; }; 
Enter fullscreen mode Exit fullscreen mode

And then we would apply the function to the routes that we want to protect:

// routes.ts export const routes: Routes = [   {      path: 'admin',      component: AdminComponent,      canActivate: [roleGuard(ROLES.ADMIN)],   },   {      path: 'manager',      component: ManagerComponent,     canActivate: [roleGuard(ROLES.MANAGER)],   }, ]; 
Enter fullscreen mode Exit fullscreen mode

When using function-based guards, we don't have to worry about typechecking, because we can infer the role from the function parameter and pass it to the AuthService.

How to test the guards

We can test the guards by creating a mock AuthService, but in our case we can use the real AuthService because it's already a fake service.

// role.guard.spec.ts import { TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { ROLES, AuthService } from './auth.service'; import { RoleGuard } from './role.guard';  describe('RoleGuard', () => {   let router: Router;   let guard: RoleGuard;   let authService: AuthService;    beforeEach(() => {     TestBed.configureTestingModule({       imports: [RouterTestingModule],       providers: [RoleGuard, AuthService],     });      router = TestBed.inject(Router);     guard = TestBed.inject(RoleGuard);     authService = TestBed.inject(AuthService);   });    it('should be created', () => {     expect(guard).toBeTruthy();   });    it('should return true if the user has the role', () => {     authService.userRole = ROLES.ADMIN; // Set the user role     const route = { data: { role: ROLES.ADMIN } } as unknown as ActivatedRouteSnapshot;     expect(guard.canActivate(route)).toBeTrue();   });    it('should return /unauthorized if the user does not have the role', () => {     authService.userRole = ROLES.ADMIN; // Set the user role     const route = { data: { role: ROLES.MANAGER } } as unknown as ActivatedRouteSnapshot;     const unauthorizedUrlTree = router.createUrlTree(['/unauthorized']);     expect(guard.canActivate(route)).toEqual(unauthorizedUrlTree);   }); }); 
Enter fullscreen mode Exit fullscreen mode

And here's the test for the function-based guard:

// role.guard.spec.ts describe('RoleGuard', () => {   it('allows user to navigate to route if he has access', async () => {     TestBed.configureTestingModule({       providers: [         AuthService,         provideRouter([           {path: 'admin', component: AdminComponent, canActivate: [roleGuard(ROLES.ADMIN)]},         ]),       ],     });     const authService = TestBed.inject(AuthService);     const harness = await RouterTestingHarness.create();      authService.userRole = ROLES.ADMIN;     let instance = await harness.navigateByUrl('/admin');     expect(instance).toBeInstanceOf(AdminComponent);   });    it('redirects to unauthorized if the user doesnt have access', async () => {     TestBed.configureTestingModule({       providers: [         AuthService,         provideRouter([           {path: 'manager', component: ManagerComponent, canActivate: [roleGuard(ROLES.MANAGER)]},           {path: 'unauthorized', component: NotAuthorizedComponent},         ]),       ],     });      const authService = TestBed.inject(AuthService);     const harness = await RouterTestingHarness.create();      authService.userRole = ROLES.ADMIN;     let instance = await harness.navigateByUrl('/manager');     expect(instance).toBeInstanceOf(NotAuthorizedComponent);   }); }); 
Enter fullscreen mode Exit fullscreen mode

I changed the testing way for the functional based guard to use the RouterTestingHarness because it's easier to think about the test this way (at least for me).

That's it!

Thanks for reading!


I tweet a lot about Angular (latest news, videos, podcasts, updates, RFCs, pull requests and so much more). If you’re interested about it, give me a follow at @Enea_Jahollari. Give me a follow on dev.to if you liked this article and want to see more like this!

angularjavascriptrouterwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.