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.