What is the procedure for implementing a RoleGuard in Angular 6?

Is there a way to retrieve the user role from the token?

I've managed to fetch the token using the decoding feature of angular2-jwt, but when I try to apply it for accessing the admin route, it returns a value of false.

Upon checking with console.log(tokenPayLoad), I can see that the token is successfully decoded.

https://i.stack.imgur.com/llBT7.png

Additionally, in the Chrome DevTools' Application view, I can verify that the user is stored in localStorage.

https://i.stack.imgur.com/cCtgK.png

This is how I declared my routes:

  { 
    path: 'dashboard',
    component: DashboardComponent, 
    canActivate: [RoleGuard], 
    data: {expectedRole: 'admin'} 
  },

And here's my implementation of the role-guard.service.ts:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot } from "@angular/router";
import { JwtHelperService } from "@auth0/angular-jwt";
import { AuthService } from '../user/auth.service';

@Injectable({
  providedIn: 'root'
})
export class RoleGuardService implements CanActivate {
  jwtHelper = new JwtHelperService()

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

  canActivate(route: ActivatedRouteSnapshot): boolean {
    const expectedRole = route.data.expectedRole;
    const token = localStorage.getItem('token')
    const tokenPayLoad = this.jwtHelper.decodeToken(token)

    if (!this.auth.isAuthenticated() || tokenPayLoad.role !== expectedRole) {
      console.log(tokenPayLoad)
      this.router.navigate(['/'])
      window.alert('You do not have permission to access this route.')
      return false
    }
    return true
  }
}

Answer №1

With the valuable assistance of user184994, I have realized that I made an oversight by not saving the role into the token.

Consequently, I have now included the role in the token:

To achieve this, I used the following code snippet: const token = jwt.sign({ userId: user._id, role: user.role }...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Collaborate on sharing CSS and TypeScript code between multiple projects to

I am looking for a solution to efficiently share CSS and TS code across multiple Angular projects. Simply copy-pasting the code is not an ideal option. Is there a better way to achieve this? ...

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...

Different ways to pass a component function's return value to a service in Angular

On my HTML page, I am presenting job details within Bootstrap panels sourced from a JSON array using an ngFor loop. Each panel showcases specific job information along with a unique job ID. The panel is equipped with a click event which triggers the execut ...

Unable to input text in an Angular2 input field

Encountering an issue with users on Windows 7 using IE11 while trying to input information into textboxes or textareas. The drop-downs and checkboxes are functioning properly, but additional fields cannot be filled out even after toggling visibility with t ...

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

After filling a Set with asynchronous callbacks, attempting to iterate over it with a for-of loop does not accept using .entries() as an Array

Encountering issues with utilizing a Set populated asynchronously: const MaterialType_Requests_FromESI$ = SDE_REACTIONDATA.map(data => this.ESI.ReturnsType_AtId(data.materialTypeID)); let MaterialCollectionSet: Set<string> = new Set<s ...

Exploring how enums can be utilized to store categories in Angular applications

My application has enums for category names on both the back- and front-end: export enum CategoryEnum { All = 'All', Category1 = 'Category1', Category2 = 'Category2', Category3 = 'Category3', Cate ...

The potential object null may lead to an absence of the 'value' property in the type 'EventTarget'

I am facing a problem that I am unable to resolve. The error in my HTML reads: Object is possibly 'null' and Property 'value' does not exist on type 'EventTarget'. HTML <select [(ngModel)]="selectedProvincia" (ch ...

Determine the specific cell involved in an HTML5 drag-and-drop interaction within a table

I've been experimenting with the HTML5 drag and drop functionality in an Angular project. Here's the setup I'm working with: A container containing draggable 'objects' A table where users can drop the dragged elements Following ...

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...

Leveraging async-await for carrying out a task following the deletion of a collection from a mongodb database

Trying to implement async await for executing an http request prior to running other code. Specifically, wanting to delete a collection in the mongodb database before proceeding with additional tasks. This is what has been attempted: app.component.ts: ...

Angular 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

Can you please clarify the purpose and functionality of @HostBinding(hostPropertyName)?

The @HostBinding() decorator requires an argument called 'hostPropertyName'. Are you familiar with this host and how can we discover its available properties? ...

Creating an Angular feature module with the aim of converting it into an Angular library

Currently, I am developing an angular feature module as a library to enable us to create individual modules without the need to rebuild the entire angular application. While this approach seems to be functioning well, my question is whether it is conside ...

How to toggle CSS class in Angular2/Typescript to mimic radio buttons behavior

Is there a way to create a radio button group using UL and LI elements in Angular2 and Typescript? The goal is to have all the anchors function like a radio button group where only one can be selected at a time. The selected anchor should remain "clicked" ...

Unable to perform a default import in Angular 9 version

I made adjustments to tsconfig.json by adding the following properties: "esModuleInterop": true, "allowSyntheticDefaultImports": true, This was done in order to successfully import an npm package using import * as ms from "ms"; Despite these changes, I ...

How to Make an HTTP POST Request in Angular without Including Headers

How can I configure Angular (version 4.0.2) to send a minimal HTTP POST request? When I use the default code like this: import { Http, Response } from '@angular/http'; export class MyService { constructor(public http: Http) { this.http.pos ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

Utilizing Angular 2 Observable for showcasing a seamless flow of real-time information

Currently, my Angular 2 Web application is utilizing a Couchbase Server as its database. The data communication occurs through WebAPIs that interact with the CouchBase server. As of now, I am uncertain if this method is optimal, but I am constantly polling ...

Using Angular 2 to showcase icons in the navbar post authentication

The structure of my components is as follows: The app component contains a navigation bar and router outlet. The navigation bar includes a logo, generic links, and specific links that are only shown after user login and authentication. The router outlet de ...