How to guard route by user role

0 votes

How to guard route by user role ?

I'm trying to guard a route based on the user's role in my Express.js app, but I'm unsure how to implement this properly. I know I need to check the user's role before allowing access to certain routes, but I'm not clear on how to set up role-based access control (RBAC) or which middleware functions to use for this purpose. Could someone explain the best way to guard routes by user role in Express.js?

Dec 4, 2024 in Web Development by Nidhi
• 10,860 points
79 views

1 answer to this question.

0 votes

1. Create an AuthService to manage user roles:

This service will store the current user's role and provide methods to check access rights.

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

@Injectable({

  providedIn: 'root'

})

export class AuthService {

  private userRole: string = 'admin';  // Mock role (In real-world, get it from an API or token)

  getUserRole(): string {

    return this.userRole;

  }

  hasRole(role: string): boolean {

    return this.userRole === role;

  }

}

2. Create a Route Guard:

Generate a route guard that checks if the user has the required role to access the route.

ng generate guard role

Then, implement the guard logic:

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

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { AuthService } from './auth.service';


@Injectable({

  providedIn: 'root'

})

export class RoleGuard implements CanActivate {

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

  canActivate(

    route: ActivatedRouteSnapshot,

    state: RouterStateSnapshot

  ): boolean {

    const requiredRole = route.data['role'];  // Get the required role from route data

    if (this.authService.hasRole(requiredRole)) {

      return true;

    } else {

      this.router.navigate(['/unauthorized']);  // Redirect if user doesn't have the required role

      return false;

    }

  }

}

3. Define Routes with the Guard:

In the app-routing.module.ts, protect routes using the RoleGuard by specifying required roles in the data field.

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

import { RouterModule, Routes } from '@angular/router';

import { AdminComponent } from './admin/admin.component';

import { UserComponent } from './user/user.component';

import { UnauthorizedComponent } from './unauthorized/unauthorized.component';

import { RoleGuard } from './role.guard';


const routes: Routes = [

  {

    path: 'admin',

    component: AdminComponent,

    canActivate: [RoleGuard],

    data: { role: 'admin' }  // Only accessible by users with 'admin' role

  },

  {

    path: 'user',

    component: UserComponent,

    canActivate: [RoleGuard],

    data: { role: 'user' }  // Only accessible by users with 'user' role

  },

  {

    path: 'unauthorized',

    component: UnauthorizedComponent

  },

  {

    path: '',

    redirectTo: '/user',

    pathMatch: 'full'

  }

];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

answered Dec 12, 2024 by Navya

Related Questions In Web Development

0 votes
1 answer

How to deny direct access to a folder and file by htaccess?

Hello @kartik, Just move the includes folder out of the ...READ MORE

answered Aug 24, 2020 in Web Development by Niroj
• 82,840 points
9,585 views
0 votes
1 answer

How to download a file by jQuery.Ajax?

Hello @kartik, You don't need to do this ...READ MORE

answered Sep 18, 2020 in Web Development by Niroj
• 82,840 points
7,598 views
0 votes
2 answers

How to user Jquery's Plugin "Mondial relay" in react js properly?

Hi, have you found a solution? I'm facing ...READ MORE

answered Nov 30, 2022 in Web Development by Kévin
1,229 views
+1 vote
2 answers

How to embed Google map on my website?

1. Search whatever you want to embed. 2. ...READ MORE

answered Jan 17, 2020 in Web Development by anonymous
1,501 views
0 votes
1 answer

Unable to start express server on AWS instance

It's not your code — you can't connect ...READ MORE

answered Oct 1, 2018 in AWS by Priyaj
• 58,020 points
3,274 views
0 votes
1 answer

Start script missing error when running npm start

It seems that there is an undefined ...READ MORE

answered Feb 10, 2022 in Java by Soham
• 9,710 points
4,564 views
0 votes
0 answers

Pre-rendering VS Server-side rendering for Angular SEO

i want to integrate an seo optimization ...READ MORE

Feb 14, 2022 in Others by Kichu
• 19,040 points
734 views
0 votes
1 answer

Pre-rendering VS Server-side rendering for Angular SEO

https://developers.google.com/web/updates/2019/02/rendering-on-the-web use this article it explains all about ...READ MORE

answered Feb 22, 2022 in Others by narikkadan
• 63,600 points
579 views
0 votes
1 answer

How To Implement Caching in Node.js Using Redis?

To retrieve cached data from Redis in ...READ MORE

answered Oct 25, 2024 in Web Development by kavya
193 views
0 votes
1 answer

How do you create a custom hook to manage form validation?

Instead of coding up lots of code ...READ MORE

answered Oct 21, 2024 in Web Development by Navya
• 460 points
303 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP