简体   繁体   中英

Angular - How to manage menus using roles by Keycloak

I have an application using Angular 12, in this application I have menus and routes. I have two keycloak roles: admin and user, and two user test admin and testuser.

I need only the menus that each role has permission to appear in my 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

 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>

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

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:

so you can write in your ts file:

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

then do the test in your HTML file:

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM