How to implement authorization based on ACL / role using angular 2?

What is the best way to implement ACL / paper using angular 2?

My scenario, in a nutshell, is this: roles are dynamic and based on permissions that the client can configure, which can also be dynamic.

I need to prevent the user from having access to a specific resource for which he is not authorized to do. For this, I thought about using the Angular Guards concept. With CanActivate Guard, I could set whether to allow the user to pass or not based on the information that I would put on each route. This information will be the name of the resource to which this route belongs. When I got to the guard, I was able to compare his role and see if his role has access to this function and whether its navigation allows.

But with this, two more problems may fall:

1 - How to redirect the user to a resource to which he has access? Should I list the route files and look for someone who is compatible with his role and then redirect there?

2 - How to disable components that he cannot see on pages that he can access? For example, he has access to the list X page, but she does not have access to create a new item, so I need to remove the "Create something" button. Rather, how to do this with divs that contain certain information for some roles, but not for its role?

I would like to know how best to approach this scenario in the angular ecosystem.

Thank you for listening.

+6
source share
2 answers

You can use ngx-permissions for this . It supports syntax, lazy loading, isolated lazy loading. Add a library to the project:

@NgModule({ imports: [ NgxPermissionsModule.forRoot() ] }) export class AppModule { } 

Download Roles

 NgxRolesService .addRole('ROLE_NAME', ['permissionNameA', 'permissionNameB']) NgxRolesService.addRole('Guest', () => { return this.sessionService.checkSession().toPromise(); }); NgxRolesService.addRole('Guest', () => { return true; }); 

use in templates

 <div *ngxPermissionsOnly="['ADMIN', 'GUEST']"> <div>You can see this text congrats</div> </div> 

protect your guard

 const appRoutes: Routes = [ { path: 'home', component: HomeComponent, canActivate: [NgxPermissionsGuard], data: { permissions: { only: ['ADMIN', 'MODERATOR'], except: ['GUEST'] } } }, ]; 

To check the documentation of the wiki page documentation.

+1
source

Check out CASL , there are articles about integration in Vue and Aurelia , but for Angular 2+ the implementation should be very similar

The basic idea is that you can identify opportunities for each user.

 import { AbilityBuilder } from 'casl' // allow to read and create Todo-s for everybody and update for assignees export default AbilityBuilder.define(can => { can(['read','create'], 'Todo') can(['update'], 'Todo', { assignee: user.id }) }) 

The documentation also has an article on how to display capabilities for different roles.

0
source

Source: https://habr.com/ru/post/1012609/


All Articles