User role from jwt angular/nestjs

Viewed 41

i'm having issues to retrieve the user's role from the jwt token, it's working for the id but not for the role.

This 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 {};
   }

But i can get datas to fill a form by doing this in a component.ts

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();

Here's what I get from the jwt :

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

Looks like the user's role is undefined in the authGuard. Any idea of what i'm doing wrong ? Thanks

1 Answers

You can anytime test your JWT token on official site and decode it. In your case there is no an user_role property, but it has the role.

Related