I have been working on adding route guard and token interceptor in an Angular 6 project.
In the route-guard's canActivate, I call an async method which checks, if the access token has expired:
If yes, checks for refresh token expiry and if that has expired too, it logs the user out, else, gets a new access token using the refresh token.
If no, navigates the user to the route.
However, whenever the access token has expired, (point 1), the route is not navigated to. I have tried everything and all combinations , but it still dosent work.
AuthGuard.service.ts
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const isAuthenticated = await this.auth.isAuthenticated();
if (isAuthenticated) {
return true;
} else {
return false;
}
}
Auth.service.ts
public async isAuthenticated() {
// Check whether the token is expired and return true or false
const token = sessionStorage.getItem('token');
if (token) {
if (await this.checkTokenValidity(token)) {
return true;
} else {
return false;
}
}
return false;
}
public checkTokenValidity = async (token) => {
//checking if access token is valid or not
const isAccessTokenExpired = this.tokenService.tokenExpiry(token);
if (isAccessTokenExpired) {
const response = await this.tokenService.getNewToken();
}
const isSignatureValid = this.tokenService.isSignatureValid(sessionStorage.getItem('token'));
if (!isSignatureValid) {
return false;
}
return true;
}
getNewToken = async () => {
const url = 'api/refresh/';
const refreshToken = Object.assign({}, { refresh: refreshToken });
sessionStorage.removeItem(TOKEN);
// if refresh token has expired then log the user out.
if (this.tokenExpiry(refreshToken)) {
sessionStorage.clear();
this.router.navigate([''])
return;
}
return this.apiService.postData(url, refreshToken).toPromise();
}