Angular 6+ 中基于角色的重定向

Role based redirection in Angular 6+

在我的 Angular8 应用程序中,有 2 个用户和管理员的仪表板页面,我想通过使用用户角色到 PanelComponent 来加载相应的仪表板。我想在 PanelComponent.html 中使用 ngIf 并根据角色加载相应的仪表板,但不确定这是否是个好主意:(

另一方面,有一些问题,例如 How to achieve Role Based redirection after login in Angular-5?,但没有很好的例子。那么,实施这种方法的最佳方式是什么?

Angular Route Guards 是支持基于角色的访问的最佳实践。 但是,如果您只想支持两个页面的基于角色的访问,并且需求不会及时扩展,那么我认为使用 ngIf 没有任何问题。在这种情况下我会这样做。

如果你仍然想使用路由守卫,那么你应该相应地实现 CanActivate 接口。这将是你的路由守卫实施。此 class 负责根据角色显示或不显示请求的页面。如果用户没有所需的角色,则会重定向到您创建的 http 404 或 403 页面。

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

@Injectable()
export class RouteGuardService implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {
  }
  canActivate(route: ActivatedRouteSnapshot): boolean {
    if (
      !this.auth.isAuthorized(route.data.roleCode)
    ) {
      this.router.navigate(NotFoundPage.PATH);
      return false;
    }
    return true;
  }
}

您可以在您的应用程序中设置路由的角色组-routing.module如下

export const ROUTES: Routes = [
  { 
    path: 'admin',
    component: AdminDashBoardComponent,
    canActivate: [RouteGuardService],
    data: { 
      roleCode: 'admin'
    } 
  },
  { 
    path: 'user', 
    component: UserDashBoardComponent, 
    canActivate: [RouteGuardService],
    data: { 
      roleCode: 'user'
    } 
  },
  { 
    path: 'other', 
    component: OtherPageComponent, 
    canActivate: [RouteGuardService], 
    data: { 
      roleCode: 'user'
    } 
  },
  { path: '**', redirectTo: '' }
];

为简洁起见,我没有分享身份验证服务,它可以做的只是比较用户的角色代码和 route.data.roleCode。 如果用户未登录,您还可以将您的身份验证逻辑集成到此 RouteGuardService 中,您可以将其再次重定向到登录页面。

所有这些都是为了防止未经授权访问您的页面。

您要求在登录后重定向到正确的页面,这听起来像是您想要一个动态主页。登录后立即根据角色组进行重定向不是一个好的做法。

您可以改为在主页组件的 ngOnInit 中重定向。这提供了更好的设计。

export class HomePageComponent {  
...
    ngOnInit() {
        if (this.auth.isAuthorized('admin')) {
          this.router.navigateByUrl('/admin');
        } else if (this.auth.isAuthorized('user')) {
        this.router.navigateByUrl('/user');
    } 
}