Angular/NestJS user roles and authentication through JWT tokens

I am encountering difficulties in retrieving the user's role from the JWT token. It seems to be functioning properly for the ID but not for the role.

Here is my guard:


if (this.jwtService.isTokenExpired() || !this.authService.isAuthenticated()) {
    const userRole = this.authService.getUserRole();
        if (route.data.role && route.data.role.indexOf(userRole) === -1) {
           return false;
        }
        // Authorized
        return true;
    }
    this.snackbar.open("You can't go there, please login first.", 'Close', {
       duration: 5000,
       horizontalPosition: 'left',
       verticalPosition: 'bottom',
    });
    this.router.navigate(['login']);
    return false;

AuthService:


login(loginForm: LoginForm): Observable<LoginResponseI> {
   return this.http.post<LoginResponseI>('http://localhost:3000/api/auth/login', loginForm).pipe(
      tap((res: LoginResponseI) => localStorage.setItem(JWT_NAME, JSON.stringify(res))),
      tap(() =>
         this.snackbar.open('Login Successfull', 'Close', {
            duration: 2000,
            horizontalPosition: 'left',
            verticalPosition: 'bottom',
         })
      )
   );
}
getUserId(): Observable<any> {
   return of(localStorage.getItem(JWT_NAME)).pipe(
      switchMap((jwt: any) =>
         of(this.jwtHelperService.decodeToken(jwt)).pipe(
            map((jwt: any) => JSON.parse(jwt.user_id))
         )
      )
   );
}
getUserRole(): Observable<any> {
   return of(localStorage.getItem(JWT_NAME)).pipe(
      switchMap((jwt: any) =>
         of(this.jwtHelperService.decodeToken(jwt)).pipe(
            map((jwt: any) => JSON.parse(jwt.user_role))
         )
      )
   );
}
isAuthenticated(): boolean {
   const token = localStorage.getItem(JWT_NAME);
   if (token) {
      return true;
   } else return false;
}

public getToken(): string | null {
   return window.sessionStorage.getItem(JWT_NAME);
}

public getUser(): any {
   const user = window.sessionStorage.getItem(USER_KEY);
   if (user) {
      return JSON.parse(user);
   }

   return {};
}

However, I can retrieve data to populate a form by utilizing the following code in a component.ts file:


this.authService
     .getUserId()
     .pipe(
        switchMap((id: number) =>
           this.userService.findOne(id).pipe(
              tap((user: User) => {
                 this.updateUserForm.patchValue({
                    id: user.id,
                    first_name: user.first_name,
                    last_name: user.last_name,
                    username: user.username,
                    profileImage: user.profileImage,
                 });
              })
           )
        )
     )
     .subscribe();

Upon inspecting the contents of the JWT token:


access_token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAdGVzdC5mciIsInJvbGUiOiJ1c2VyIiwidXNlcl9pZCI6MSwiaWF0IjoxNjYyNDcxNzMwLCJleHAiOjE2NjI0NzUzMzB9.CbZkcFU28P7D0btrJzyOQIEEiM63t8iZjPXYMQJBLTg"
expires_in: "3600s"
type: "jwt"
user_id: 1
user_role: "user"

It appears that the user's role is undefined in the authGuard. Any suggestions on what might be going wrong? Thank you.

Answer №1

Feel free to verify your JWT token at the authorized website and unveil its contents. Although your specific token does not contain a property named user_role, it does include the role property.

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

What is the process for incorporating personalized variables into the Material Ui Theme?

In the process of developing a react app with TypeScript and Material UI, I encountered an issue while attempting to define custom types for my themes. The error message I received is as follows: TS2322: Type '{ mode: "dark"; background: { default: s ...

ReactJS: error occurs when trying to fetch data and encountering issues with reading properties

I am currently attempting to initiate an API call (a GET request) in order to download a document. However, I am encountering an error when making the API call: TypeError: Cannot read properties of undefined (reading 'payload') const printPin ...

Bizarre npm setup

I'm new to Node and struggling with upgrading my package to enable web workers. I'm attempting to move from Angular 6.x.x to 7.x.x and then to 8.x.x. However, every time I try to install updates, it initially seems like it's successful but e ...

Angular's HostListener triggers twice when the browser's back button is clicked

In my Angular application, I have implemented a @HostListener that triggers when the back button on the browser is clicked. However, I have noticed that the event handler seems to be firing twice - prompting two dialogue boxes when clicking 'Ok'. ...

I'm puzzled as to why my createDoorMethod is returning a string value instead of a number, even though I am passing it a number. Can someone help me

Currently enrolled in a web development course, I am diving into the world of Angular 2 and TypeScript. Despite following along with the video tutorial and using the same code, my implementation is not working as expected, leaving me puzzled. Here is the ...

The color overlay for the class label map segmentation in AMI JS is not appearing as expected

I came across this example in vanilla JavaScript. In my project using Angular 7.3.8 with AMI version 0.32.0 (ThreeJS 0.99.0), I imported everything as an angular provider service. When trying the test examples from the provided link, I noticed that the o ...

Sharing assets across different Angular applications is a powerful way to improve code

I am currently developing a series of small applications that will utilize common modules and shared assets. For guidance on how to structure the projects, refer to this answer: The organization of my project folders is as follows: -root --projects ---ap ...

Exploring Model Object Properties with ngFor in Angular

Currently, I am developing an Angular application with a Model object that consists of properties of various types. My goal is to loop through these properties in the component and generate form fields for each property. Unfortunately, the implementation i ...

The Authentication Key (FCM Token) was not provided in the request. For further details, please consult the "Authentication" section in the FCM documentation

When sending Firebase notifications from my NativeScript app using the Angular HTTP post module, I sometimes encounter an error stating that the request is missing an Authentication Key (FCM Token). The FCM documentation provides more information on this. ...

Issue with Angular 7: In a ReactiveForm, mat-select does not allow setting a default option without using ngModel

I have a Angular 7 app where I am implementing some reactive forms. The initialization of my reactive form looks like this: private initFormConfig() { return this.formBuilder.group({ modeTransfert: [''], modeChiffrement: [' ...

ESlint is unable to parse typescript in .vue files

After using vue ui to build my project, here is the content of my package.json: "@vue/cli-plugin-eslint": "^4.1.0", "@vue/cli-plugin-typescript": "^4.1.0", "@vue/eslint-config-standard": "^4.0.0", "@vue/eslint-config-typescript": "^4.0.0", "eslint": "^5.1 ...

The TypeScript compiler is unable to locate the module react-scripts within the lerna webpack configuration

Recently, I've been working on setting up a new project using lerna, react-scripts, webpack, and sass. Here is my current directory structure: myApp /packages /myReactApp -> a react create app application /tsconfig.json /package ...

The Angular module loaded lazily encountered a 401 error

Currently, I am working on an Angular application that consists of multiple lazy-loaded modules built using Angular CLI. The resources (JS, CSS, and HTML) within these modules require authorization, which is managed through a cookie system. If a user attem ...

How to automatically scroll to the most recently added element in an *ngFor loop using Angular 2

In my web page, I have a dynamic list rendered using an ngFor loop. Users can add or remove elements from this list by clicking on a button. What I want to achieve is to automatically scroll the browser view to the latest element added when a user clicks o ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

What causes the "Method Not Allowed" error while trying to restore the package.json package in VS2015?

When trying to restore a package.json file in VS2015, I am encountering a "Method Not Allowed" error. https://i.stack.imgur.com/OgK5P.png https://i.stack.imgur.com/AAkoQ.png The error log displays the following: npm ERR! Error: Method Not Allowed npm ER ...

Exploring the capabilities of the Angular 2 expression parser alongside the functionality of the

Is there a way to create an equivalent of the Angular 1.x ngInit directive in Angular 2? I am familiar with the ngOnInit hook, which is recommended for initialization code. The ngInit directive seems like a quick and declarative way to prototype or fix a ...

Having trouble connecting my chosen color from the color picker

Currently, I am working on an angularJS typescript application where I am trying to retrieve a color from a color picker. While I am successfully obtaining the value from the color picker, I am facing difficulty in binding this color as a background to my ...

The error message "TypeError: self.parent.parent.context.parseInt is not a function" indicates that

My goal is to set the height of an image using ngStyle by calculating it with a Math operation in the following way: <div [ngSwitch]="tbNm?tbNm:'itm0'"> <ion-list *ngFor="let vl of scrnshot;let ind=index"> <img *ngSwitch ...

Proper management of setTimeout in an Angular application

I am working on a one-page web application where the main component's ngOnInit() function triggers a recursive function called loopDoSomething() using setTimeout: ngOnInit(): void { // Perform some operations this.loopDoSomething(); } loopDoSome ...