0
votes

I have developed a webapp in Angular 2, backed by a set of RESTful services. Those RESTful services are all secured, and each endpoint requires authenticated user with one or more user roles. Different services can have different roles.

To consume these services, the webapp first authenticates the user, then a received JWT-token is sent in each request to the services. This token contains all the information about the user, such as username, roles etc.

Now, how can I easily present only those elements in my webapp which the logged inn user has acccess to. Are there any standard ways to that? Or are there any best-practices for that? I want to avoid hard-coding stuff in my webapp as much as possible.

2

2 Answers

1
votes

It depends on what you consider a feature element. There are few (or even more than that) approaches.

  • show/hide based on JWT content. That can be done with a service such as FeatureService that has something like isFeatureAvailable method. then you can use ngIf to show/hide elements in the template or even do conditional checking in the code.
  • if you use lazy-loading and each feature lives in their own lazy-loaded module, you could use canActivate feature of the router to prevent loading selected features

Hope that make sense

0
votes

If I would have to do it, then I would divide the screen into businessEntities and privileges. There should be a REST API which will on the basis of the roles of the logged in user, send the Angular UI the combinations of valid BusinessEntities and Privileges. Based on this information you can show/hide components on the screen. A businessEntity can be a button, form, textbox etc and a Privilege can be Read/Write etc.

If it is a small application, then all this information of valid businessEntity/privilege combinations can go directly into the JWT to speed-up the application. But then if we have many such combinations then the JWT will be huge and this approach will not be recommended.

There can certainly be better ways of doing it, this is just my approach.

Hope it helps.