如何在nodejs中将jwt令牌到期时间设置为最大值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45207104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:22:48  来源:igfitidea点击:

How to set jwt token expiry time to maximum in nodejs?

node.jsjwt

提问by Jagadeesh

I dont want my token to get expire and shold be valid forever.

我不希望我的令牌过期并永久有效。

var token = jwt.sign({email_id:'[email protected]'}, "Stack", {

                        expiresIn: '24h' // expires in 24 hours

                         });

In above code i have given for 24 hours.. I do not want my token to get expire. What shall be done for this?

在上面的代码中,我已经给出了 24 小时。我不希望我的令牌过期。对此应该怎么做?

回答by Ved

To set expirey time in days: try this

以天为单位设置过期时间:试试这个

 var token = jwt.sign({email_id:'[email protected]'}, "Stack", {

           expiresIn: '365d' // expires in 365 days

      });

"expiresIn" should be a number of seconds or string that repesents a timespan eg: "1d", "20h",

“expiresIn”应该是代表时间跨度的秒数或字符串,例如:“1d”、“20h”、

Docs: jsonwebtoken

文档:jsonwebtoken

回答by pedrofb

The expclaim of a JWT is optional. If a token does not have it it is considered that it does not expire

exp一个智威汤逊的要求是可选的。如果令牌没有它,则认为它不会过期

According to documentation of https://www.npmjs.com/package/jsonwebtokenthe expiresInfield does not have a default value either, so just omit it.

根据https://www.npmjs.com/package/jsonwebtoken的文档,该expiresIn字段也没有默认值,因此只需省略它。

There are no default values for expiresIn,notBefore, audience, subject, issuer. These claims can also be provided in the payload directly with exp, nbf, aud, sub and iss respectively, but you can't include in both places.

expiresIn、notBefore、audience、subject、issuer没有默认值。这些声明也可以直接使用 exp、nbf、aud、sub 和 iss 直接在有效负载中提供,但不能同时包含在这两个位置。

var token = jwt.sign({email_id:'[email protected]'}, "Stack", {});

回答by AbolfazlR

you can set expire time in number or string :

您可以在 number 或 string 中设置过期时间:

expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js).
Eg: 60, "2 days", "10h", "7d".

A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc),
otherwise milliseconds unit is used by default ("120" is equal to "120ms").

以秒或描述时间跨度的字符串表示 [zeit/ms]( https://github.com/zeit/ms.js)。
例如: 60, "2 days", "10h", "7d"

数值被解释为秒计数。如果您使用字符串,请确保提供时间单位(天、小时等),
否则默认使用毫秒单位(“120”等于“120ms”)。

 var token = jwt.sign({email_id:'[email protected]'}, "Stack", {
        expiresIn: "10h" // it will be expired after 10 hours
        //expiresIn: "20d" // it will be expired after 20 days
       //expiresIn: 120 // it will be expired after 120ms
 });