所以我必须在我开发的应用程序上实现类似的东西,这就是我处理它的方式。
我创建了一个身份验证服务,其中包含一个检查用户是否具有管理角色的方法:
auth.service.ts
public isManager(): boolean {
let isManager = false;
let user = this.getUserToken();
//Stored my allowed groups in a config file, comma separated string
let allowedGroups = AuthenticationParams.filters.split(',');
let userGroups: any;
if (user !== null && user !== undefined) {
try {
let userGroups: any = user.role;
if (userGroups !== undefined && userGroups !== null && userGroups.length > 0) {
try {
userGroups.forEach((e: any) => {
if (allowedGroups.indexOf(e) > -1) {
isManager = true;
}
});
} catch (e) {
if (allowedGroups.indexOf(userGroups) > -1) {
isManager = true;
}
}
}
} catch (e) {
isManager = false;
}
}
return isManager;
}
public getUserToken(): any {
return localStorage.getItem('jwtTokenName');
}
我按如下方式创建了一个身份验证守卫:
guard.component.ts
import { Injectable, OnInit } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';
import { Router } from '@angular/router';
import { AuthenticationService } from '../services/helper/security/auth.service';
@Injectable()
export class GuardComponent implements CanActivate {
constructor(private authenticationService: AuthenticationService, private _router: Router) {
}
canActivate() {
let isManager: boolean = this.authenticationService.isManager();
if (!isManager) {
this._router.navigate(['unauthorized']);
}
return isManager;
}
}
guard.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GuardComponent } from './guard.component';
@NgModule({
declarations: [],
imports: [ CommonModule ],
exports: [],
providers: [ GuardComponent ],
})
export class GuardModule { }
然后,我将守卫用于处理导航到管理部分的路线
app-routing.module.ts
{ path: 'management', component: AdminComponent, canActivate: [GuardComponent] }
在我的导航栏上,我只调用isManager 方法并将其存储在一个变量中,并使用它来确定是否需要显示管理链接。
navbar.component.ts
public isManager: boolean = false;
ngOnInit(): void {
this.isManager = this.authenticationService.isManager();
}
navbar.component.html
<li [routerLinkActive]="['active']" *ngIf="isManager"><a [routerLink]="['management']">Management Portal</a></li>
我不得不从每种方法中删除一些数据,但这将为您提供基本概念。希望这会有所帮助。