Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Expired Token From Api in Angular 4

I need help in handling expired token in my angular application. My api has the expired time but my problem is when i forgot to log out of my angular application, after some time, i still can access the homepage but without data. Is there something i can do about this? Are there libraries that can handle this? or are there something i could install? Better, if i nothing will be installed. Here's my authentication code below? Can i add anything that can handle expiration and I won't be able to access the homepage if it expires.

auth.service.ts

 export class AuthService {
  private loggedIn = false;

  constructor(private httpClient: HttpClient) {
  }

  signinUser(email: string, password: string) {  
    const headers = new HttpHeaders() 
    .set('Content-Type', 'application/json');

    return this.httpClient
    .post(
      'http://sample.com/login', 
       JSON.stringify({ email, password }), 
       { headers: headers }
    )
    .map(
        (response: any) => {
          localStorage.setItem('auth_token', response.token);
          this.loggedIn = true;
          return response;
        });
   }

    isLoggedIn() {
      if (localStorage.getItem('auth_token')) {
        return this.loggedIn = true;
      }
    }

   logout() {
     localStorage.removeItem('auth_token');
     this.loggedIn = false;
    }
}

authguard.ts

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    if (this.authService.isLoggedIn()) {
      // logged in so return true
      return true;
    }

    else {
      // not logged in so redirect to login page with the return url
      this.router.navigate(['signin'])
      return false;
      }
  }
}
like image 850
Joseph Avatar asked Sep 11 '17 02:09

Joseph


2 Answers

You can do this using http interceptors.

intercept(req: HttpRequest<any>, next: HttpHandler) {
  if(!localStorage.getItem('token'))
    return next.handle(req);

  // set headers
  req = req.clone({
    setHeaders: {
      'token': localStorage.getItem('token')
    }
  })

  return next.handle(req).do((event: HttpEvent<any>) => {
    if(event instanceof HttpResponse){
      // if the token is valid
    }
  }, (err: any) => {
    // if the token has expired.
    if(err instanceof HttpErrorResponse){
      if(err.status === 401){
        // this is where you can do anything like navigating
        this.router.navigateByUrl('/login');
      }
    }
  });
}

Here's the full solution

like image 152
Amirhosein Al Avatar answered Nov 12 '22 17:11

Amirhosein Al


I think there is two solution you can play with.

The first one you can just call you logout function when browser getting closed like:

  @HostListener('window:unload', ['$event'])
  handleUnload(event) {
    this.auth.logout();
  }

https://developer.mozilla.org/de/docs/Web/Events/unload

OR

 @HostListener('window:beforeunload', ['$event'])
      public handleBeforeUnload(event) {
        this.auth.logout();
      }

https://developer.mozilla.org/de/docs/Web/Events/beforeunload

This way alway when browser getting closed your this.auth.logout(); will be called automatically.

Second you can install library like angular2-jwt it can help you to detect if token has expired

jwtHelper: JwtHelper = new JwtHelper();

useJwtHelper() {
  var token = localStorage.getItem('token');

  console.log(
    this.jwtHelper.decodeToken(token),
    this.jwtHelper.getTokenExpirationDate(token),
    this.jwtHelper.isTokenExpired(token)
  );
}
like image 23
angularrocks.com Avatar answered Nov 12 '22 17:11

angularrocks.com