【问题标题】:How to convert time::Tm to u64 for JWT expiration date如何将 time::Tm 转换为 u64 以获取 JWT 到期日期
【发布时间】:2017-03-06 13:46:13
【问题描述】:

我正在使用jwt crate,我想在Claims 结构中设置到期日期。 Registered 中的 exp 字段采用了 Option<u64>

我可以通过以下方式检索当前日期并添加 1 天:

let mut timer = time::now();
timer = timer + Duration::days(1);

但我不知道如何将此 time::Tm 转换为 u64

【问题讨论】:

    标签: time rust jwt


    【解决方案1】:

    exp 字段是“NumericDate”类型,根据RFC 7519 是“从 1970-01-01T00:00:00Z UTC 到指定 UTC 日期/时间的秒数,忽略闰秒。"

    此描述与the to_timespec method 相同,后者在 Tm 的当前时区中“将时间转换为 1970 年 1 月 1 日的秒数”。

    因此:

    let mut timer = time::now_utc();
    timer = timer + Duration::days(1); 
    token.claims.reg.exp = Some(timer.to_timespec().sec as u64);
    

    (请注意,虽然 time + duration 始终返回 v0.1.36 的 UTC 时间,但可以说是 a defect 可以在将来修复。为了向前兼容,我使用 now_utc() 而不是 now() .)

    (*: to_timespec 基本上在 POSIX 上调用 gmtime() 并且 POSIX 标准忽略闰秒。在 Windows 上,它将结构转换为 FILETIME which again ignores leap seconds。所以如果你真的关心 to_timespec 可以安全使用27 秒的差异。)


    如果你使用std::time::SystemTime,同样可以使用

    let mut timer = SystemTime::now();
    timer += Duration::from_secs(86400);
    token.claims.reg.exp = Some(timer.duration_since(UNIX_EPOCH).unwrap().as_secs());
    

    【讨论】:

    • 你拯救了我的一天!
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多