0
我使用代碼來驗證jwt是否已過期(來自angular2-jwt)。 但是,如果用戶更改localStorage中令牌的值,例如: id_token =>「123」,它會顯示錯誤並停止應用程序。 但我想在Guard中處理這個錯誤。在Angular中處理來自正常函數的錯誤2/4
//錯誤:
core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: JWT must have 3 parts
Error: JWT must have 3 parts
我如何處理在後衛這個錯誤,如果擲被激發?
//Guard.ts:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean
{
if (this.tokenService.isTokenExpired(token)) {
this.auth.loggedIn = false;
this.loginService.logout();
this.notifications.success = false;
this.notifications.status = 401;
this.notifications.state = 'alertFail';
this.notifications.message = 'Token Expirado! Faça o login novamente.';
this.notifications.arrayError = [];
this.notifications2.setNotifications(this.notifications);
this.router.navigate(['/login']);
return false;
}
return true;
}
//功能之一:
public decodeToken(token: string): any {
let parts = token.split('.');
if (parts.length !== 3) {
throw new Error('JWT must have 3 parts');
}
let decoded = this.urlBase64Decode(parts[1]);
if (!decoded) {
throw new Error('Cannot decode the token');
}
return JSON.parse(decoded);
}
我猜我對你試圖完成的事情感到困惑。警衛不能正常工作嗎? 老實說,驗證令牌的最好方法是將其發送回可以通過並通過驗證的API。如果您的應用可以解碼令牌,那麼您已經失去了使用令牌驗證身份的任何安全性。 – joshrathke