簡體   English   中英

Angular 6基於角色的身份驗證

[英]Angular 6 Role based Authentication

我的項目中有5個模塊。 在基於卷的創建,更新,刪除和查看訪問中滾動訪問這些模塊。

我如何在角度6中創建UI,當用戶登錄到應用程序並在共享服務中設置角色時,我需要該角色。 例如,admin roll訪問所有服務和員工角色只查看列表不能訪問創建和刪除。 我很想進入角度。

請幫我解決基於卷的身份驗證中的任何代碼或示例

您可以創建不同的組件並有條件地呈現組件。 考慮你的例子。 為此,我創建了2個組件1.視圖組件2.創建組件。

喜歡考慮代碼

<div>
   <button *ngIf="usertype!=='employeee">Delete</button> <!--show delete button if user is not employee-->
   <create *ngIf="usertype!=='employeee"></create> <!-- Show create component if usertype is not emplyee -->
   <view [data]="data"></view> <!-- view for all type of user-->
</div>

無論你打算創建,更新,刪除和查看創建按鈕后的任何方式,您都可以通過編程方式啟用或禁用按鈕。如果這是您的需要,請按照以下步驟操作

創建具有[禁用]選項的按鈕,例如,

<button text="click" [disabled]="isAuthorised">Create</button>

<button text="click" [disabled]="isAuthorised">Delete</button>

這里isAuthorised是typescript中的變量,根據用戶角色將變量設為boolean(true / false)。相應地啟用或禁用按鈕

您可以遵循許多不同的方法,但通過使用route-guards來限制基於特定條件的route-guards的基本思想。

在你的情況下,你可以有路由,當route-guard授權使用它時,懶洋洋地加載你的模塊,並進一步加載相同方式的嵌套路由。

確定您的路線模塊。

{
   path:'/dashboard',
   loadChildren: './lazy.module#LazyModule'
   canActivate:[ModuleRouteGuard],
   data: {
      accessRoles: ['Manager','HR']
   }
}

LazyModule_Routes.ts

{
   path:'/board',
   component: ManagerBoard
   canActivate:[ChildRouteGuard],
   data: {
      accessRoles: ['Manager']
   },
   resolve: {
      userRoles: 'userRolesResolver'  //use this resolver service to get data inside component so to decide if user can read/write . OR you can also use activatedRoutes data
   }
}

路由Gaurd.ts

@Injectable()
class ModuleRouteGuard implements CanActivate { (1)
  constructor(private userService: UserService) {}; (2)

  canActivate() {
    console.log("OnlyLoggedInUsers");
    if (this.userService.isLoggedIn()) { (3)
      return true;
    } else {
      window.alert("You don't have permission to view this page"); (4)
      return false;
    }
  }
}

您的應用解析器,它從服務器帶來用戶角色。

@Injectable()
class UserRolesResolver implements Resolve<Team> {
  constructor(private backend: Backend) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any>|Promise<any>|any {
    //return this.backend.fetchTeam(route.params.id);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM