我需要在 https://github.com/auth0/angular2-jwt/tree/v1.0
JWT Interceptor中使用基于角色的身份验证方面的建议 . 如何使用Angular 5执行"admin"角色身份验证?
现在我有:登录服务器发送回有效负载中的用户ID并使用canActivate的jwt令牌后,我的应用程序检查令牌是否存在然后允许进入安全站点 .
@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
你认为这是正确的方法吗?如果您有更好的解决方案,请告诉我 .
1 回答
是的,因为JWT在有效载荷部分编码您的数据 . 如果您想获得某些属性,则需要解码所有有效负载 .
当你在angular2-jwt中分析代码时,你会在JwtHelper类中找到获取令牌到期日期的方法 . 在其实现中,在第三行中查找要提取到期日期,您需要首先解码所有令牌有效负载 .
以下示例来自angular2-jwt