【问题标题】:Angular 5 role based autherntication with @auth0/angular-jwt使用 @auth0/angular-jwt 的 Angular 5 基于角色的身份验证
【发布时间】:2018-01-06 16:38:25
【问题描述】:

我需要使用https://github.com/auth0/angular2-jwt/tree/v1.0 JWT 拦截器获得基于角色的身份验证的建议。 如何使用 Angular 5 执行“管理员”角色身份验证?

现在我有:在登录服务器发送回 jwt 令牌和有效负载中的用户 ID 并使用 canActivate 后,我的应用程序检查令牌是否存在,然后允许进入安全站点。

@Injectable()
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;
    }
  }
}

和我的安全死记硬背:

export const SECURE_ROUTES: Routes = [
    { path: 'home', component: HomeComponent, canActivate: [EnsureAuthenticated] },
    { path: 'homeadmin', component: HomeadminComponent, canActivate: [AuthenticatedAdmin] },
];

然后我想创建类似的东西:

@Injectable()
export class AuthenticatedAdmin implements CanActivate {
  constructor(private auth: AuthService, private router: Router) {}
  canActivate(): boolean {
    if ("in token is admin") {
      return true;
    } else {
      this.router.navigateByUrl('/login');
      return false;
    }
  }
}

在这种方法中,我需要使用https://github.com/auth0/jwt-decode 解码令牌 你认为这是正确的方法吗?如果您对此问题有更好的解决方案,请告诉我。

【问题讨论】:

    标签: javascript authorization roles angular5 angular2-jwt


    【解决方案1】:

    是的,因为 JWT 在有效负载部分对您的数据进行编码。如果你想获得一些属性,你需要解码所有的有效载荷。

    当您在 angular2-jwt 中分析代码时,您会在 JwtHelper 类中找到获取令牌到期日期的方法。在其实现中,在第三行中找到要提取到期日期,您需要首先解码所有令牌有效负载。

    以下示例来自angular2-jwt

    public getTokenExpirationDate(token: string): Date {
      let decoded: any;
      decoded = this.decodeToken(token);
    
      if (!decoded.hasOwnProperty('exp')) {
        return null;
      }
    
      let date = new Date(0); // The 0 here is the key, which sets the date to the epoch
      date.setUTCSeconds(decoded.exp);
    
      return date;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-25
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 2017-11-17
      • 2020-08-13
      • 1970-01-01
      相关资源
      最近更新 更多