在JS中将Tick转换为Date

问题描述 投票:3回答:1

我正在尝试检查JWT令牌的到期日期,我尝试的所有内容都没有让我得到正确的日期。

"exp": 1522210228 => real answer => Wednesday, March 28, 2018 12:10:28 AM

我已经尝试过libs而且我没有让它们工作......

  1. https://github.com/auth0/angular2-jwt/blob/master/src/jwthelper.service.ts
  2. https://github.com/auth0/jwt-decode

1

const helper = new JwtHelperService();
const decodedToken = helper.decodeToken(this.authentificationInfos.token);
const expirationDate = helper.getTokenExpirationDate(this.authentificationInfos.token);

console.log(expirationDate); => null?

2

import * as decode from 'jwt-decode';

const token = decode<{ data: { exp: number, iat: number, iss: string, nbf: number, username: string } }>(this.authentificationInfos.token);
const date = new Date(token.data.exp);
console.log(date); => Sun Jan 18 1970 09:50:10 GMT-0500 (Eastern Standard Time)

const d = new Date(0);
d.setUTCMilliseconds(token.data.exp);
console.log(d); => Sun Jan 18 1970 09:50:10 GMT-0500 (Eastern Standard Time)

这是完整的标记:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXJuYW1lIjoiYmlsb2RlYXV2aW5jZW50QG91dGxvb2suY29tIiwiaWF0IjoxNTIyMjA2NjI4LCJpc3MiOiJtbnAuY29tIiwibmJmIjoxNTIyMjA2NjI4LCJleHAiOjE1MjIyMTAyMjh9fQ.1WRlQatauXw2HEWj9B9VL6fIVR-4nAoKuWvkS4_m86k

https://jwt.io/正在解码令牌,显示的exp是正确的。

如何从token.exp获取实际日期?

javascript typescript jwt
1个回答
4
投票

JWT中的时间戳是UNIX时间戳,从01.01.1970 00:00 UTC开始计算:https://tools.ietf.org/html/rfc7519#section-4.1.4解释了数字日期用于exp声明(以及nbf(不是之前)和iat(已发出)声明)

https://tools.ietf.org/html/rfc7519#section-2定义数字日期:

一个JSON数值,表示从1970-01-01T00:00:00Z UTC到指定的UTC日期/时间的秒数,忽略闰秒。

var jwtDecode = require('jwt-decode');
var jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXJuYW1lIjoiYmlsb2RlYXV2aW5jZW50QG91dGxvb2suY29tIiwiaWF0IjoxNTIyMjA2NjI4LCJpc3MiOiJtbnAuY29tIiwibmJmIjoxNTIyMjA2NjI4LCJleHAiOjE1MjIyMTAyMjh9fQ.1WRlQatauXw2HEWj9B9VL6fIVR-4nAoKuWvkS4_m86k";

const token = jwtDecode(jwt);
const d = new Date(0);
d.setUTCSeconds(token.data.exp);
console.log(d);

输出:

2018-03-28T04:10:28.000Z

使用d.getHours()d.getMinutes()等来获取当地时间。

© www.soinside.com 2019 - 2024. All rights reserved.