This article volition last an extension of an existing one: https://ngeblognow.blogspot.com//search?q=how-to-secure-angular-app-using.
Normally inwards the front-end side (Angular), nosotros are exclusively describe of piece of job concern whether a user is authenticated or not. Authorization whether a user has plenty access to a given REST resources is configured inwards the api side. But what if nosotros desire to secure the front-end urls nonetheless? One of the many solution is to practise a guard together with either add together an say-so code inwards canLoad or canActivate. In this article nosotros volition bargain alongside canLoad, every bit nosotros are lazy-loading our modules (please get upwards to Angular documentation for to a greater extent than information).
In this detail example, nosotros are checking for the grouping claim tied to a user. Role would too do, merely I unremarkably used that on the REST api side.
Here are the steps:
- Create a permission-guard model that nosotros volition piece of job when defining the road
export interface PermissionGuard { Only?: Array string>, Except?: Array string>, RedirectTo?: string | Function }
- Add the road inwards your app-routing.module.ts file, together with define the Permission model inwards the information attribute.
{ path: 'dashboard/employee', canLoad: [AuthGuard], loadChildren: 'app/module/dashboard/employee/employee.module#EmployeeModule', data: { Permission: { Only: ['employee'], RedirectTo: '403' } every bit PermissionGuard } }
- In our keycloak.service, add together the next methods. It checks if a user is a fellow member of a grouping specified inwards the PermissionGuard.
static hasGroup( groupName: string ): boolean { supply KeycloakService.auth.authz != cypher && KeycloakService.auth.authz.authenticated && KeycloakService.auth.authz.idTokenParsed.groups.indexOf( "/" + groupName ) !== -1 ? truthful : false; } static hasGroups( groupNames: Array
): boolean { supply groupNames.some( v => { if ( typeof v === "string" ) supply KeycloakService.hasGroup( v ); } ); } - Going dorsum to the auth-guard.service, let's alter the canLoad method to procedure the authorization. In hither nosotros piece of job the previously defined method to banking venture gibe if the electrical current logged user is a fellow member of an specific group.
canLoad( route: Route ): boolean { if ( KeycloakService.auth.loggedIn && KeycloakService.auth.authz.authenticated ) { this.logger.info( "user has been successfully authenticated" ); } else { KeycloakService.login(); supply false; } this.logger.info( "checking authorization" ); permit information = route.data["Permission"] every bit PermissionGuard; if ( Array.isArray( data.Only ) && Array.isArray( data.Except ) ) { throw "Can't piece of job both 'Only' together with 'Except' inwards road data."; } if ( Array.isArray( data.Only ) ) { permit hasDefined = KeycloakService.hasGroups( data.Only ) console.log("hasDefined="+hasDefined); if ( hasDefined ) supply true; if ( data.RedirectTo && data.RedirectTo !== undefined ) this.router.navigate( [data.RedirectTo] ); supply false; } if ( Array.isArray( data.Except ) ) { permit hasDefined = KeycloakService.hasGroups( data.Except ) if ( !hasDefined ) supply true; if ( data.RedirectTo && data.RedirectTo !== undefined ) this.router.navigate( [data.RedirectTo] ); supply false; } }
- An additional bonus is having a directive that nosotros tin piece of job inwards the UI side to cover / present an chemical element when a user is either a fellow member of a grouping or non
import { Directive, OnInit, ElementRef, Input } from '@angular/core'; import { KeycloakService } from 'app/core/auth/keycloak.service'; @Directive( { selector: '[hasGroup]' } ) export degree HasGroupDirective implements OnInit { @Input( 'hasGroup' ) group: string; @Input( 'hasGroups' ) groups: string; constructor( someone element: ElementRef, ) { } ngOnInit() { if ( KeycloakService.hasGroup( this.group ) ) { this.element.nativeElement.style.display = ''; } else { this.element.nativeElement.style.display = 'none'; } } }
Questions:
- What is 403? It's an additional road to redirect when a user is non authorized.
{ path: '403', component: ForbiddenComponent },
Note: This article is inspired yesteryear ng2-permission.
Demo template is available for sale for $50. You tin ship payment via skype at: czetsuya@gmail.com
0 komentar:
Please comment if there are any that need to be asked.