You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 2中管理用户级别访问权限?附JSP权限控制代码

Implementing User Level Access Control in Angular 2

Great question! Let's break down how to replicate your JSP-based permission control in Angular 2, covering both UI-level rendering and route-level protection to keep things secure.

1. First, Create a Permissions Service

This acts as your equivalent of the ${pms} object in JSP—storing user permissions and providing a simple way to check them:

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class PermissionsService {
  private userPermissions: { [key: string]: boolean } = {};

  // Call this after login to load permissions from your backend
  loadUserPermissions(permissions: { [key: string]: boolean }) {
    this.userPermissions = { ...permissions };
  }

  // Check if the user has a specific permission
  hasPermission(permissionKey: string): boolean {
    return this.userPermissions[permissionKey] || false;
  }
}

2. Conditionally Render UI Elements (Like Your JSP Menu Items)

Just like your <c:if> tags, we can use Angular's built-in *ngIf directive with our service to show/hide elements.

First, inject the service into your component (make it public so we can access it in the template):

import { Component } from '@angular/core';
import { PermissionsService } from './permissions.service';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html'
})
export class SidebarComponent {
  constructor(public permissionsService: PermissionsService) {}
}

Then in your template, replace the JSP <c:if> with Angular's *ngIf:

<!-- Equivalent to your WManageRoles check -->
<li class="treeview" *ngIf="permissionsService.hasPermission('WManageRoles')">
  <a [routerLink]="['/admin/manageroles/roles']">
    <img src="assets/images/Icons_1-03.png" />
    <span>ACCESS</span>
  </a>
</li>

<!-- Equivalent to your WSmartrackerManageDevice check -->
<li class="treeview" *ngIf="permissionsService.hasPermission('WSmartrackerManageDevice')">
  <a [routerLink]="['/admin/smartracker/managedevices']">
    <img src="assets/images/Icons_1-04.png" />
    <span>DEVICE</span>
  </a>
</li>

Optional: Custom Directive for Closer Syntax to <c:if>

If you want a directive that feels more like your JSP <c:if>, create a custom structural directive:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { PermissionsService } from './permissions.service';

@Directive({ selector: '[hasPermission]' })
export class HasPermissionDirective {
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private permissionsService: PermissionsService
  ) {}

  @Input() set hasPermission(permissionKey: string) {
    if (this.permissionsService.hasPermission(permissionKey)) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}

Use it like this in your template:

<li class="treeview" *hasPermission="'WManageRoles'">
  <!-- Same content as above -->
</li>

3. Protect Routes with Guards

Hiding UI elements isn't enough—users could still navigate directly to restricted routes via the URL. Use Angular's route guards to block unauthorized access.

Create a PermissionGuard:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, Router } from '@angular/router';
import { PermissionsService } from './permissions.service';

@Injectable({ providedIn: 'root' })
export class PermissionGuard implements CanActivate {
  constructor(
    private permissionsService: PermissionsService,
    private router: Router
  ) {}

  canActivate(route: ActivatedRouteSnapshot): boolean {
    const requiredPermission = route.data['requiredPermission'];
    
    if (!requiredPermission || this.permissionsService.hasPermission(requiredPermission)) {
      return true;
    }

    // Redirect to an unauthorized page or login
    this.router.navigate(['/unauthorized']);
    return false;
  }
}

Add the guard to your route configuration:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RolesComponent } from './admin/manageroles/roles.component';
import { ManagedDevicesComponent } from './admin/smartracker/managedevices.component';
import { PermissionGuard } from './permission.guard';

const routes: Routes = [
  {
    path: 'admin/manageroles/roles',
    component: RolesComponent,
    canActivate: [PermissionGuard],
    data: { requiredPermission: 'WManageRoles' }
  },
  {
    path: 'admin/smartracker/managedevices',
    component: ManagedDevicesComponent,
    canActivate: [PermissionGuard],
    data: { requiredPermission: 'WSmartrackerManageDevice' }
  },
  // Add other routes here
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

Final Notes

  • Don't forget to load the user's permissions after login: call permissionsService.loadUserPermissions() with the permission object fetched from your backend (similar to how ${pms} is populated in JSP).
  • Always validate permissions on the backend too—client-side checks are for UI convenience, not security.

内容的提问来源于stack exchange,提问作者Santhosh Rapolu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:29:47