0

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:

  1. 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.

  2. 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();
  }
Rohan Agarwal
  • 2,441
  • 2
  • 18
  • 35
  • Just clarifying, the token is expired and the token refresh expiry is expired too. Hence, the user should now be logged out. Is my understanding correct? – CodeWarrior Feb 03 '20 at 03:38
  • Yes, it's correct. Can you identify why isn't my app routing to the routes whenever a refresh token api call is made to fetch a new token. – Rohan Agarwal Feb 03 '20 at 06:38

1 Answers1

0

Inject Router instance in your constructor and when your condition (token expiry) is not satisfied, route the user to your Logout component.

constructor(private router: Router) { }

async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    const isAuthenticated = await this.auth.isAuthenticated();
    if (isAuthenticated) {
      return true;
    } else {
      this.router.navigate(['/logout']);
    }
}
CodeWarrior
  • 5,026
  • 6
  • 30
  • 46