How would you manage user roles and permissions using Angular 2

Roman Skydan picture Roman Skydan · Oct 5, 2017 · Viewed 22.9k times · Source

I'm working on a new Angular2 app, and I was wondering how would you manage routes accessible to certain roles and permissions to create, edit, and delete items for certain roles.

I want to know how do you solve the problem such this:

  • How do you manage access to some UI elements? How does the app know to show or hide it? Do you use single service for this? Or do you create different conditions for the different place in your app?

  • How do you manage your routing? Do you use CanActivate, CanActivateChild, CanLoad and etc? Do you build a single guard service for all routes or make different services for different modules or component?

  • And last question. What is the best way to divide the app then you can sell it like a CMS? I mean how can we realize possibility to load some other modules from the market for example, and add it in your app?

How do you solve the similar problem?

Any guidance, experience, or pointers to material covering these topics is greatly appreciated. Thanks in advance.

Answer

GreyBeardedGeek picture GreyBeardedGeek · Oct 8, 2017

As mentioned in the comments to your question, a complete answer is beyond the scope of a SO question/answer, and so you may find your question closed in the near future for that reason, but here's some quick suggestions for you to explore further on your own:

  • Get the user's permissions from the server during/after login via http/https. Store these permissions somewhere that makes sense for your app, perhaps in a service. If you're using JWT, the permissions can be returned in the JWT token.

  • To simplify things, only deal with permissions on the client. Roles are for the server code to figure out what permissions the user has. No need to muck things up by conflating roles with permissions on the client.

  • Protect routes with auth guards

  • Protect individual UI elements with *ngIf or ngSwitch/*ngSwitchCase

  • Dynamic Loading is a big topic area - go read about it - lots of resources on the web. However, as far as I know, while you can lazily load modules, they must be known to the application at compile-time. I may be mistaken, but I don't think that you can just load anything you want at runtime.