angular2-jwt检查令牌是否在组件中过期? [英] angular2-jwt check if token is expired in component?

查看:216
本文介绍了angular2-jwt检查令牌是否在组件中过期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在角度2应用程序的组件内检查id令牌是否已过期?我通过该方法获得了AuthService

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();
}

在模板内部使用可以正常工作.如果用户注销,则在用户登录角度变化检测后,它会返回false,然后重新运行模板中的函数,并返回true.

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.

在组件内部使用

@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?

推荐答案

我目前正在我的办公桌上使用angular2 jwt令牌,遇到了同样的问题. 原来,我们需要将localStorage中的令牌设置为"id_token"

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"

tokenNotExpired-允许您检查本地存储中是否有未到期的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

注意:默认情况下,tokenNotExpired将假定令牌名称为 id_token ,除非将令牌名称传递给它,例如:tokenNotExpired('token_name').在将来的版本中将对此进行更改,以自动使用在AuthConfig中设置的令牌名称.

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.

希望有帮助!

这篇关于angular2-jwt检查令牌是否在组件中过期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆