基于角色的角度路由

问题描述 投票:0回答:2

我正在使用Angular

这是我的身份验证检查

export class EnsureAuthenticated implements CanActivate {
    constructor(private auth: AuthService, private router: Router) {}
    canActivate(): boolean {
        if (localStorage.getItem('token')) {
            return true;
        }
        else {
            this.router.navigateByUrl('/login');
            return false;
        }
    }
}


{ 
      path: 'path', 
      component: myComponent,
      canActivate: [EnsureAuthenticated]
    }

它的工作正常我的问题是这个页面可以兼顾用户和管理员

我知道我没有设定任何条件

如何设置适当的条件

我不想访问该页面的管理员

angular angular2-routing
2个回答
0
投票

假设您有一项服务来检索已连接用户的角色,您只需检查该角色,如果用户是管理员,则返回false,以防止该类用户访问您的网页。如果您存储在lcoal存储中的令牌是JWT令牌,则有时会将用户角色编码到其中,您必须解码令牌以提取角色。


0
投票

您应该创建一个RoleGuardService,它期望来自用户的角色并检查此角色是否与所考虑的角色相同,如下所示:

  constructor(public auth: AuthService, public router: Router) {}

  canActivate(route: ActivatedRouteSnapshot): boolean {

    // this will be passed from the route config
    // on the data property
    const expectedRole = route.data.expectedRole;

    const token = localStorage.getItem('token');

    // decode the token to get its payload
    const tokenPayload = decode(token);

    if (
      !this.auth.isAuthenticated() || 
      tokenPayload.role !== expectedRole
    ) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  } 

并通过用户角色保护来保护您的路由:

{ 
    path: 'admin', 
    component: AdminComponent, 
    canActivate: [RoleGuard], 
    data: { 
      expectedRole: 'admin'
    } 
  }, 

此方案假定您在JWT中使用自定义角色声明,有关详细信息,我建议您阅读完整解释您的答案的文章:https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3

© www.soinside.com 2019 - 2024. All rights reserved.