I understand the working of JWT based authentication, but I am struggling to understand the correct approach to create a role based access control in angular2.
Can some-one please provide a way to approach this problem, or some useful links.
In the Angular application you can do these things:
Remember that real authorization enforced on the server end, in the angular2 you are just dealing with presentation layer.
Here is the one possible approach:
You add custom claim to a JWT token. It can be something like this:
{
"user" : "JohnDoe",
"roles" : ["admin","manager","whatever"]
}
In the angular app, you create AuthService, where you decode the JWT token and store extracted claim in the variable, and in the localStorage
You can create a navigationService which will store the data about menu and roles required to access particular component in the object or array. It can be something like that (pseudocode):
const menuItems = [
{
"name":"Dashboard",
"routerLink":"/dashboard",
"rolesRequired":["user"]
},
{
"name":"ControlPanel",
"routerLink":"/cp",
"rolesRequired":["admin"]
},
.....
]
constructor(private authService:AuthService){}
getMenu(){
return this.menuItems.filter(
element => {
return
this.authService.user.role.haveElement(element.rolesRequired)
}
)
}
In the menu component you can use navigation service to retrive the list of allowed menu items.
You can use same navigationService in the AuthGuard.