简体   繁体   English

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

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

I have an application using Angular 12, in this application I have menus and routes.我有一个使用 Angular 12 的应用程序,在这个应用程序中我有菜单和路线。 I have two keycloak roles: admin and user, and two user test admin and testuser.我有两个 keycloak 角色:admin 和 user,以及两个用户 test admin 和 testuser。

I need only the menus that each role has permission to appear in my html我只需要每个角色有权出现在我的 html 中的菜单

app-routing:应用程序路由:

    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导航栏.TS

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

HTML 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>

keycloak guard:钥匙斗篷守卫:

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));
  }
}

I'm using Keycloak angular and the official keycloack client library, from this tutorial: https://www.npmjs.com/package/keycloak-angular我正在使用 Keycloak angular 和官方 keycloack 客户端库,来自本教程: https://www.npmjs.com/package/keycloak-angular

Sorry, my answer is a bit late but I was facing the same issue and I didn't find any solution online.抱歉,我的回答有点晚了,但我遇到了同样的问题,我在网上没有找到任何解决方案。 in fact, there is a predefined boolean variable in keycloack service called isUserInRole that has a parameter where you can specify the role's name:事实上,在 keycloack 服务中有一个预定义的 boolean 变量称为 isUserInRole,它有一个参数,您可以在其中指定角色的名称:

so you can write in your ts file:所以你可以在你的 ts 文件中写:

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

then do the test in your HTML file:然后在您的 HTML 文件中进行测试:

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

if you didn't find the solution, hope that would help如果您没有找到解决方案,希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在角度2中管理角色和权限 - How to manage the roles and permission in angular 2 您将如何使用 Angular 2 管理用户角色和权限 - How would you manage user roles and permissions using Angular 2 如何基于角度的用户角色/权限管理菜单 - How to manage menu based on user roles/permissions in angular Keycloak用户角色angular和.net核心 - Keycloak user roles angular and .net core 如何使用 Angular 添加角色 - How can I add roles using Angular 如何在 Angular 6 中实现 Keycloak? - How to implement Keycloak in Angular 6? 如何在由 angular 和 .net 核心 web api 组成的全栈应用程序中管理用户角色和权限 - how to manage user roles and permission in a full stack application made up of angular and .net core web api 使用keycloak-angular终止Keycloak session后如何从Angular应用程序注销 - How to logout from Angular app once Keycloak session is terminated using keycloak-angular 如何在angular-keycloak中获取keycloak令牌 - How to get keycloak token in angular-keycloak 如何使用服务和BehaviorSubject管理Angular中的state? - How to manage state in Angular using services and BehaviorSubject?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM