如何检查 JWT 令牌是否在 Angular 8 中过期 [英] How to check if JWT token is expired in Angular 8

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

问题描述

在 Angular 8 中检查 JWT 令牌是否已过期的不同方法.到期时间为 1 小时.工作代码/示例将不胜感激.

In Angular 8 what are different ways to check if the JWT token has expired. The expiry time is 1 hour. working code/samples will be highly appreciated.

推荐答案

选项 1 - 手动

令牌到期时间以 UTC 时间 格式编码在令牌中.因此可以根据 UTC 的当前时间手动获取和检查它.试试下面的

Token expiry time is encoded in the token in UTC time format. So it can be fetched and checked manually against current time in UTC. Try the following

private tokenExpired(token: string) {
  const expiry = (JSON.parse(atob(token.split('.')[1]))).exp;
  return (Math.floor((new Date).getTime() / 1000)) >= expiry;
}

ngOnInit() {
  if (this.tokenExpired(token)) {
    // token expired
  } else {
    // token valid
  }
}

选项 2 - 使用 JwtHelperService

您可以使用 JwtHelperServiceisTokenExpired() 方法检查令牌是否已经过期.

You could use the JwtHelperService's isTokenExpired() method to check if the token has expired already.

import {JwtHelperService} from '@auth0/angular-jwt';
.
.
constructor(private jwtHelper: JwtHelperService) { }

ngOnInit() {
  if (this.jwtHelper.isTokenExpired(token)) {
    // token expired 
  } else {
    // token valid
  }
}

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

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