【问题标题】:Angular - How to manage menus using roles by KeycloakAngular - 如何使用 Keycloak 的角色管理菜单
【发布时间】:2022-06-22 21:47:12
【问题描述】:

我有一个使用 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],
      },
]

navBar.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

【问题讨论】:

    标签: angular authorization keycloak keycloak-services


    【解决方案1】:

    您找到解决方案了吗?找到了可以分享一下吗?

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      相关资源
      最近更新 更多