P
P
Pavel Talaiko2018-05-27 14:31:55
Angular
Pavel Talaiko, 2018-05-27 14:31:55

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

2 answer(s)
I
Ivan Stroykin, 2018-05-27
@jsdevel

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 for displaying elements in the interface depending on the role
@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();
    }
  }
}

You can rewrite this directive for yourself. That is, when opening the page, make a request to the backend to receive permission / prohibition to view elements and, using this directive, placed on certain elements, control the display

D
Dasha Tsiklauri, 2018-05-27
@dasha_programmist

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 question

Ask a Question

731 491 924 answers to any question