Authgard JWT refresh undefined

Published

I am currently integrating authgard in my angular application.
I’ve also set up a token refresh system if the token has expired.
Everything works pretty well, but I still have a problem with redirection after the token refresh.

The "canActivate" function doesn’t wait for the response from the "isAuthenticated" function and receives an "undefined" instead of true or false.
I understood that it was because of my refresh function which makes a call to an API again but I’m having trouble finding a solution.

Thanks in advance for your help.

auth-guard.service.ts :

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
import {HttpHeaders} from '@angular/common/http';
import {ToastController} from '@ionic/angular';
import { map } from 'rxjs/operators';



@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

  constructor(public auth: AuthService, public router: Router, public toastController: ToastController) {}

  canActivate() {

    const authenticated = this.auth.isAuthenticated();

    if (authenticated !== true) {
      this.router.navigate(['tabs/login']);
      this.afficherMessageErreur();
      return false;
    }
    console.log(true);
    return true;
  }

  async afficherMessageErreur() {
    const toast = await this.toastController.create({
      message: 'Une erreur est survenue. Veuillez vous reconnecter.',
      duration: 2000,
      position: 'top'
    });
    toast.present();
  }
}

auth.service.ts

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {JwtHelperService} from '@auth0/angular-jwt';


@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(public jwtHelper: JwtHelperService, public http: HttpClient) {

  }

  refreshToken(token: string){
    const emailUser = localStorage.getItem('emailUser');
    const headerOptions = new HttpHeaders({
      Authorization: 'Bearer ' + token,
      isRefreshToken: emailUser
    });
    return this.http.post<Response>(`http://IPHERE:8080/refresh`, {email: emailUser}, {observe: 'response', headers: headerOptions});
  }

  public isAuthenticated(): boolean {
    const token = localStorage.getItem('tokenJWT');
    let expired = true;
    if (!token){
      return false;
    }
    else{
      try{
        expired = this.jwtHelper.isTokenExpired(token);
      }
      catch {
        return false;
      }
    }
    if (expired){
      try{
        this.refreshToken(token).subscribe(response => {
          let newToken = JSON.stringify(response.body);
          newToken = JSON.parse(newToken);
          localStorage.setItem('tokenJWT', newToken['token']);
          return true;
          // return undefined here because of the observable
        });
      }
      catch {
        return false;
      }
    }
    else{
      return true;
    }
  }

}

Source: Angular Questions

Published
Categorized as angular, auth-guard, canactivate, refresh, undefined Tagged , , , ,

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq