首页 > 解决方案 > Angular 11 - 基于角色的身份验证不与其他角色一起使用(只有“操作员”在工作)

问题描述

只有 'operator' 可以访问该页面,当其他具有 'super_admin' 角色的帐户不能再访问该页面。我想限制某个角色的其他页面。

html:

<a mat-list-item
   routerLink="/webinarcrud"
   routerLinkActive="active"
   *ngIf="dataService.roleMatch(['operator']) || dataService.roleMatch(['super_admin'])"
   class="menuNav">
  <mat-icon class="icon">computer</mat-icon>
  Webinars
</a>
<a mat-list-item
   routerLink="/organizationcrud"
   routerLinkActive="active"
   *ngIf="dataService.roleMatch(['super_admin'])"
   class="menuNav">
  <mat-icon class="icon">apartment</mat-icon>
  Organizations
</a>

路由模块:

{
  path: 'dashboard', 
  component: DashboardComponent, 
  canActivate:[AuthGuardGuard], 
  data:{ roles:['operator']} || {roles:['super_admin'] }
}

数据服务:

public roleMatch(allowedRoles): boolean {
  let isMatch = false;
  const userRoles: any = this.token.getRoles();

  if (userRoles != null && userRoles) {
    for (let i = 0; i < userRoles.length; i++) {
      for (let j = 0; j < allowedRoles.length; j++) {
        if (userRoles[i].name === allowedRoles[j]) {
          isMatch = true;
          return isMatch;
        } else {
          return isMatch;
        }
      }
    }
  }
}

令牌服务:

public getRoles(){
  return JSON.parse(localStorage.getItem("roles"));
}

身份验证:

  if (this.token.getToken() !== null) {
    const role = route.data["roles"] as Array<string>;
    const accessToken = route.data.accessToken as string;

    if (role) {
      const match = this.dataService.roleMatch(role);

      if (match) {
        return true;
      } else {
        this.router.navigate(["/login"]);
        return false;
      }
    }
  }
  this.router.navigate(["/login"]);
  return false;
}

标签: angulartypescriptauthentication

解决方案


尝试以下更改 -

路由模块:

{path: 'dashboard', component: DashboardComponent, canActivate:[AuthGuardGuard], data:{roles:['operator','super_admin']}}

数据服务:

public roleMatch(allowedRoles) :boolean{
let isMatch = false;
const userRoles: any = this.token.getRoles();
if(userRoles) {
  for(let i = 0; i<userRoles.length; i++) {
    if(allowedRoles.indexOf(userRoles[i].name) !== -1){
     isMatch = true;
     break;
    }
  }
}
return isMatch;
}

推荐阅读