【问题标题】:Perform multiple UserRole check执行多个 UserRole 检查
【发布时间】:2021-08-23 10:41:09
【问题描述】:

我需要为用户角色为1 or 2 的用户访问UserComponent。它在 AppRoutingModule 代码中显示为 (data : [1,2]})。

CanActivateGuard 服务我想如何执行此检查以允许具有UserRole 1 或2 的用户。目前我的代码为this.jwtHelperService.decodeToken("").role === router.data。但。我需要检查是否允许两个 UserRoles(1 和 2)。

AppRoutingModule

const routes: Routes = [
    ...
   {path:"user" , component:UserComponent, canActivate:[CanActivateGuard], data : [1,2]},
    ...

];

CanActivateGuard

canActivate(router : ActivatedRouteSnapshot) :boolean
{  
    var token = localStorage.getItem("token") ? localStorage.getItem("token"): null;

    if ( this.jwtHelperService.decodeToken("token").role === router.data )
    {
       return true;
    }
}

【问题讨论】:

    标签: angular jwt


    【解决方案1】:

    有很多方法可以继续,保持接近您的逻辑并使用includes,您可以执行以下操作:

    canActivate(router: ActivatedRouteSnapshot): boolean 
    {  
        var token = localStorage.getItem("token") ? localStorage.getItem("token") : null;
    
        // You can do this additional check to avoid a null pointer exception below
        if (token === null) return false;
    
        // If the decoded token has a role of 1 or 2, it will pass this check
        if (router.data.includes(this.jwtHelperService.decodeToken(token).role))
        {
           return true;
        }
    
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 2014-01-09
      • 2012-12-29
      • 2018-08-19
      • 1970-01-01
      相关资源
      最近更新 更多