jsonwebtoken

    技术2022-07-12  72

    jsonwebtoken

    用法

    jwt.sign(payload, secretOrPrivateKey, [options, callback])

    (异步)如果提供回调,则使用err或JWT 调用回调。

    (同步)将JsonWebToken返回为字符串。

    payload必须是一个object, buffer或者string。请注意, exp只有当payload是object字面量时才可以设置。 secretOrPrivateKey 是包含HMAC算法的密钥或RSA和ECDSA的PEM编码私钥的string或buffer。 options:

    algorithm:加密算法(默认值:HS256)

    expiresIn:以秒表示或描述时间跨度zeit / ms的字符串。如60,“2 days”,“10h”,“7d”,Expiration time,过期时间

    notBefore:以秒表示或描述时间跨度zeit / ms的字符串。如:60,“2days”,“10h”,“7d”

    audience:Audience,观众

    issuer:Issuer,发行者

    jwtid:JWT ID

    subject:Subject,主题

    noTimestamp

    header

    keyid

    mutatePayload 如果为真,符号函数将直接修改有效载荷对象。如果在声明被应用到负载之后,但在它被编码到令牌之前,您需要对负载的原始引用,这将非常有用

    ​ 如果payload不是buffer或string,它将被强制转换为使用的字符串JSON.stringify()。 ​ 在expiresIn,notBefore,audience,subject,issuer没有默认值时。也可以直接在payload中用exp,nbf,aud,sub和iss分别表示,但是你不能在这两个地方同时设置。 ​ 请记住exp,nbf,iat是NumericDate类型。 ​ 生成的jwts通常会包含一个iat值除非指定了noTimestamp。如果iat插入payload中,则将使用它来代替实际的时间戳来计算其他事情,诸如options.expiresIn给定一个exp这样的时间间隔。

    // sign with default (HMAC SHA256) var jwt = require('jsonwebtoken'); var token = jwt.sign({ foo: 'bar' }, 'shhhhh'); //backdate a jwt 30 seconds var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh'); // sign with RSA SHA256 var cert = fs.readFileSync('private.key'); // get private key var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256'}); // sign asynchronously jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err, token) { console.log(token); });

    Token期限:Token Expiration (exp claim)

    签署1小时期限的token:

    jwt.sign({ exp: Math.floor(Date.now() / 1000) + (60 * 60), data: 'foobar' }, 'secret');

    使用此库生成令牌的另一种方法是:

    jwt.sign({ data: 'foobar' }, 'secret', { expiresIn: 60 * 60 }); //or even better: jwt.sign({ data: 'foobar' }, 'secret', { expiresIn: '1h' });

    jwt.verify(token,secretOrPublicKey,[options,callback])

    验证token的合法性

    //签名 var secret = 'shhhhh' jwt.sign({ data: 'foobar' }, 'secret', { expiresIn: 60 * 60 }); //验证 // verify a token symmetric - synchronous var decoded = jwt.verify(token, 'shhhhh'); console.log(decoded.foo) // bar // verify a token symmetric jwt.verify(token, 'shhhhh', function(err, decoded) { console.log(decoded.foo) // bar }); // invalid token - synchronous try { var decoded = jwt.verify(token, 'wrong-secret'); } catch(err) { // err } // invalid token jwt.verify(token, 'wrong-secret', function(err, decoded) { // err // decoded undefined }); // verify a token asymmetric var cert = fs.readFileSync('public.pem'); // get public key jwt.verify(token, cert, function(err, decoded) { console.log(decoded.foo) // bar }); // verify audience var cert = fs.readFileSync('public.pem'); // get public key jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) { // if audience mismatch, err == invalid audience }); // verify issuer var cert = fs.readFileSync('public.pem'); // get public key jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) { // if issuer mismatch, err == invalid issuer }); // verify jwt id var cert = fs.readFileSync('public.pem'); // get public key jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) { // if jwt id mismatch, err == invalid jwt id }); // verify subject var cert = fs.readFileSync('public.pem'); // get public key jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) { // if subject mismatch, err == invalid subject }); // alg mismatch var cert = fs.readFileSync('public.pem'); // get public key jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) { // if token alg != RS256, err == invalid signature }); // Verify using getKey callback // Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys. var jwksClient = require('jwks-rsa'); var client = jwksClient({ jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json' }); function getKey(header, callback){ client.getSigningKey(header.kid, function(err, key) { var signingKey = key.publicKey || key.rsaPublicKey; callback(null, signingKey); }); } jwt.verify(token, getKey, options, function(err, decoded) { console.log(decoded.foo) // bar });

    jwt.decode(token [,options])

    (同步)返回解码没有验证签名是否有效的payload。 警告:这不会验证签名是否有效。你应该不为不可信的消息使用此。你最有可能要使用jwt.verify()。

    错误与代码

    TokenExpiredError

    如果令牌过期,则抛出错误。

    错误对象:

    name:‘TokenExpiredError’

    message:‘jwt expired’

    expiredAt:[ExpDate]

    jwt.verify(token, 'shhhhh', function(err, decoded) { if (err) { /* err = { name: 'TokenExpiredError', message: 'jwt expired', expiredAt: 1408621000 } */ } });

    JsonWebTokenError 错误对象:

    name:‘JsonWebTokenError’

    message:

    jwt malformed

    jwt signature is required

    invalid signature

    jwt audience invalid. expected: [OPTIONS AUDIENCE]

    jwt issuer invalid. expected: [OPTIONS ISSUER]

    jwt id invalid. expected: [OPTIONS JWT ID]

    jwt subject invalid. expected: [OPTIONS SUBJECT]

    jwt.verify(token, 'shhhhh', function(err, decoded) { if (err) { /* err = { name: 'JsonWebTokenError', message: 'jwt malformed' } */ } });

    NotBeforeError

    如果当前时间在nbf声明之前,则抛出

    错误对象:

    name: ‘NotBeforeError’

    message: ‘jwt not active’

    date: 2018-10-04T16:10:44.000Z

    jwt.verify(token, 'shhhhh', function(err, decoded) { if (err) { /* err = { name: 'NotBeforeError', message: 'jwt not active', date: 2018-10-04T16:10:44.000Z } */ } });

    支持的算法

    alg Parameter ValueDigital Signature or MAC AlgorithmHS256HMAC using SHA-256 hash algorithmHS384HMAC using SHA-384 hash algorithmHS512HMAC using SHA-512 hash algorithmRS256RSASSA-PKCS1-v1_5 using SHA-256 hash algorithmRS384RSASSA-PKCS1-v1_5 using SHA-384 hash algorithmRS512RSASSA-PKCS1-v1_5 using SHA-512 hash algorithmPS256RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0)PS384RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0)PS512RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0)ES256ECDSA using P-256 curve and SHA-256 hash algorithmES384ECDSA using P-384 curve and SHA-384 hash algorithmES512ECDSA using P-521 curve and SHA-512 hash algorithmnoneNo digital signature or MAC value included
    Processed: 0.012, SQL: 9