Handling Expired Token From Api in Angular 4 -


i need in handling expired token in angular application. api has expired time problem when forgot log out of angular application, after time, still can access homepage without data. there can this? there libraries can handle this? or there install? better, if nothing installed. here's authentication code below? can add can handle expiration , won't able access homepage if 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 return true       return true;     }      else {       // not logged in redirect login page return url       this.router.navigate(['signin'])       return false;       }   } } 

i think there 2 solution can play with.

the first one can call 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 this.auth.logout(); called automatically.

second can install library angular2-jwt can 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)   ); } 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -