[英]Role Based Access Control in Angular2?
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. 我理解基于JWT的身份验证的工作,但我很难理解在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: 在Angular应用程序中,您可以执行以下操作:
Remember that real authorization enforced on the server end, in the angular2 you are just dealing with presentation layer. 请记住,在服务器端强制执行真正的授权,在angular2中你只是处理表示层。
Here is the one possible approach: 这是一种可能的方法:
You add custom claim to a JWT token. 您将自定义声明添加到JWT令牌。 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 在角度应用程序中,您可以创建AuthService,在其中解码JWT令牌并将提取的声明存储在变量中,并存储在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. 您可以创建一个navigationService,它将存储有关访问对象或数组中特定组件所需的菜单和角色的数据。 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. 您可以在AuthGuard中使用相同的navigationService。
Following link might help: 以下链接可能有所帮助
There is also ngx-permissions library the key difference of this library that it will remove object from DOM instead of hiding it via css. 还有ngx-permissions库这个库的关键区别在于它将从DOM中删除对象而不是通过css隐藏它。 Include it in the project
将其包含在项目中
@NgModule({
imports: [
NgxPermissionsModule.forRoot()
],
})
export class AppModule { }
Define role 定义角色
NgxRolesService
.addRole('ROLE_NAME', ['permissionNameA', 'permissionNameB'])
NgxRolesService.addRole('Guest', () => {
return this.sessionService.checkSession().toPromise();
});
NgxRolesService.addRole('Guest', () => {
return true;
});
Use in template 在模板中使用
<div *ngxPermissionsOnly="['ADMIN', 'GUEST']">
<div>You can see this text congrats</div>
</div>
您可以将Ng2Permission模块用于角度2.0应用程序的基于角色和权限的访问控制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.