Answer the question
In order to leave comments, you need to log in
Angular 5 JWT where to store user roles? How to check?
It is necessary to differentiate access to the view (button admin panel). So that the roles are not stored in localStorage, as in many tutorials.
Answer the question
In order to leave comments, you need to log in
There are several options. But no matter what method you use, everything on the front can be transferred under itself, and open the same inaccessible buttons that do not fit the role. Therefore, you always need to check on the back.
Of the options, this is storage in cookies, globally in the service, in the right places, make a request for back and receive permission or prohibition. The most important thing is never to transfer the list of roles. Nobody needs to know what roles exist.
You can write a directive like:
@Directive({ selector: '[hasRole]' })
export class HasRoleDirective implements OnInit {
@Input() hasRole: string[] | string | undefined;
constructor(private _viewContainer: ViewContainerRef,
private _template: TemplateRef<any>) {
}
ngOnInit(): void {
this._checkRoles(GlobalService.userRole);
}
private _checkRoles(userRole: string): void {
if (!this.hasRole || this.hasRole === 'undefined' || this.hasRole.indexOf(userRole) !== -1) {
this._viewContainer.createEmbeddedView(this._template);
} else {
this._viewContainer.clear();
}
}
}
store it in the store (ngrx-store), when you start the application, you read the JWT token and: in the token itself, a list of roles or make a request and then push it all to the store
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question