angular2-jwt check if token is expired in component?

不羁的心 提交于 2019-12-08 03:36:42

问题


Is it possible to check whether a id token is expired or not inside a component of angular 2 app? I got an AuthService with the method

public isAuthenticated(): boolean {
  /* check if id_token is expired or not */
  return tokenNotExpired();
}

Used inside the template it works fine. If a user is signed out it returns false, after the user signed in angular change detection reruns the function in the template and it returns true.

Used inside a component

@Component({
  selector: 'app',
  providers: [
    Auth
  ],
  templateUrl: 'app.template.html'
})

export class AppComponent implements OnInit {

  public isAuthorized: Object = {};

  constructor(private auth: Auth) {
    this.auth.handleAuthentication();
  }

  ngOnInit() {
    console.log(this.auth.isAuthenticated());
  }
}

it does not get updated after the user signed in. A page refresh is needed. How could I solve this?


回答1:


I am currently working with angular2 jwt token at my desk right now and run into the same problem. It turns out that we need to set the token in localStorage as "id_token"

From angular2-jwt:

tokenNotExpired - allows you to check whether there is a non-expired JWT in local storage. This can be used for conditionally showing/hiding elements and stopping navigation to certain routes if the user isn't authenticated

Note: tokenNotExpired will by default assume the token name is id_token unless a token name is passed to it, ex: tokenNotExpired('token_name'). This will be changed in a future release to automatically use the token name that is set in AuthConfig.

Hope it helps!



来源:https://stackoverflow.com/questions/42677155/angular2-jwt-check-if-token-is-expired-in-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!