簡體   English   中英

Angular - 如何使用 Keycloak 的角色管理菜單

[英]Angular - How to manage menus using roles by Keycloak

我有一個使用 Angular 12 的應用程序,在這個應用程序中我有菜單和路線。 我有兩個 keycloak 角色:admin 和 user,以及兩個用戶 test admin 和 testuser。

我只需要每個角色有權出現在我的 html 中的菜單

應用程序路由:

    const routes: Routes = [
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      {
        path: 'home',
        loadChildren: () => import('./core/modules/home/home.module').then((m) => m.HomeModule),
        canActivate: [AuthGuard],
      },
      {
        path: 'template',
        loadChildren: () =>
        import('./core/modules/template/template.module').then((m) => m.TemplateModule),
        canActivate: [AuthGuard],
      },
]

導航欄.TS

 navBarItem = [
    {
      name: 'Home',
      icon: '',
      route: 'home',
      children: [],
    },
    {
      name: 'Template',
      icon: '',
      route: 'template/listar-template',
      children: [],
    },
]

HTML

<mat-nav-list *ngFor="let navItem of navBarItem">
      <div *ngIf="navItem.children.length === 0" class="teste">
        <a routerLink="{{ navItem.route }}">{{ navItem.name }}</a>
      </div>
</mat-nav-list>

鑰匙斗篷守衛:

import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard extends KeycloakAuthGuard {
  constructor(
    protected readonly router: Router,
    protected readonly keycloak: KeycloakService
  ) {
    super(router, keycloak);
  }

  public async isAccessAllowed(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):Promise<boolean> {
    // Force the user to log in if currently unauthenticated.
    if (!this.authenticated) {
      await this.keycloak.login({
        redirectUri: window.location.origin + state.url,
      });
    }

    // Get the roles required from the route.
    const requiredRoles = route.data.roles;

    // Allow the user to to proceed if no additional roles are required to access the route.
    if (!(requiredRoles instanceof Array) || requiredRoles.length === 0) {
      return true;
    }

    // Allow the user to proceed if all the required roles are present.
    return requiredRoles.every((role) => this.roles.includes(role));
  }
}

我正在使用 Keycloak angular 和官方 keycloack 客戶端庫,來自本教程: https://www.npmjs.com/package/keycloak-angular

抱歉,我的回答有點晚了,但我遇到了同樣的問題,我在網上沒有找到任何解決方案。 事實上,在 keycloack 服務中有一個預定義的 boolean 變量稱為 isUserInRole,它有一個參數,您可以在其中指定角色的名稱:

所以你可以在你的 ts 文件中寫:

role : boolean
constructor( private kc : KeycloakService ) {
this.role=kc.isUserInRole("roleName") }

然后在您的 HTML 文件中進行測試:

<ng-container *ngIf="role">
**menu elements that you want it to appear**
</ng-container>

如果您沒有找到解決方案,希望對您有所幫助

暫無
暫無

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

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