[英]Best practice to validate JWT in Angular (detecting Token changes)
I have a very basic property that checks if token is expired or not: 我有一个非常基本的属性,可以检查令牌是否过期:
get isExpired():boolean {
return !!localStorage &&
!!localStorage.getItem("token") &&
!this.jwt.isTokenExpired(localStorage.getItem("token"));
}
What is the best practice to keep watching this property in angular? 保持最佳状态的最佳做法是什么?
It might not be the best practice but in AngularJs I could use $scope.$watch
这可能不是最佳实践,但在AngularJs中,我可以使用$scope.$watch
Is there any similar way to achieve the same functionality in Angular 4? 在Angular 4中是否有任何类似的方法来实现相同的功能?
Thanks in advance! 提前致谢!
I see different solutions 我看到了不同的解决方案
Use Guards to check your token expiration date on every change of route https://angular.io/guide/router#milestone-5-route-guards 使用Guards来检查每次更改路线https://angular.io/guide/router#milestone-5-route-guards的令牌到期日期
Create a service that checks on the token expiration every second , 创建一个服务,每秒检查一次令牌到期,
Observable .interval(1000) .timeInterval() .flatMap(() => this.authenticationService.isTokenExpired()) .filter(isExpired => isExpired) .subscribe(isExpired => { this.router.navigateByUrl("/login") });
this assumes that this.authenticationService.isTokenExpired()
returns an Observable<boolean>
这假定this.authenticationService.isTokenExpired()
返回一个Observable<boolean>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.