jsonWebToken整理手册

jsonWebToken整理手册
 最后更新于 2024年10月02日 08:08:46

An implementation of JSON Web Tokens.

This was developed against draft-ietf-oauth-json-web-token-08. It makes use of node-jws

Install

$ npm install jsonwebtoken

Usage

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

(异步)使用 errJWT 调用回调 (同步)返回 JsonWebToken 字符串

  • payload 必须是一个 object, bufferstringexp 只有当 payload 是 object字面量时才可以设置
  • secretOrPrivateKey 包含HMAC算法的密钥 或 RSAECDSA 的PEM编码私钥的 stringbuffer
  • options:
    • algorithm 加密算法 (默认: HS256)
    • expiresIn 过期时间。以秒表示或描述时间跨度 zeit/ms 的字符串。如 60"2 days""10h""7d"
    • notBefore 以秒表示或描述时间跨度 zeit/ms 的字符串。如 60"2days""10h""7d"
    • audience 接收方
    • issuer 签发方
    • jwtid
    • subject
    • noTimestamp
    • header
    • keyid

####注意

  1. 如果 payload 不是 Buffer或String,它将被 JSON.stringify() 强制转换为字符串。
  2. expiresInnotBeforeaudiencesubjectissuer没有默认值时。可以直接在 payload 中用 expnbfaudsubiss 分别表示,但是不能在这两个地方同时设置。
  3. 请记住 expnbfiatNumericDate 类型。
  4. 生成的jwts通常会包含一个 iat值除非指定了 noTimestamp。如果 iat 插入到payload中,它将被用来代替真正的时间戳来计算其他东西,例如 options.expiresIn 给定一个 exp 这样的时间间隔。
  5. issueraudience 在签发时缩写为 issaud,否则在 "jsonwebtoken": "^8.0.1" 的版本中使用 jwt.verify 校验时无法通过

####示例

// 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' }, cert, { algorithm: 'RS256'});

// sign asynchronously
jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err, token) {
  console.log(token);
});

Token 到期 (exp claim)

exp 包含自纪元以来的秒数。

有效时间为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 是有效的,可选值 expiration, audienceissuer 是有效的,则解码成功并回调。否则,错误回调。 (同步)token 有效时返回 expiration, audienceissuer。否则抛出错误。

  • token JsonWebToken 字符串
  • secretOrPublicKey HMAC算法生成的StringBuffer, 或 RSAECDSA 编码生成的私钥文件

如果要使用 base64 的加密数据,则使用 Buffer.from(secret, 'base64') 解析成原始的字符串传入

  • options
    • algorithms 加密算法,例如 ["HS256", "HS384"]
    • audience 接收方
    • issuer 签发方,可选。值为 StringArray
    • ignoreExpiration 如果为 true 不要验证令牌的到期时间
    • ignoreNotBefore
    • subject
    • clockTolerance 检查 NBFexp 时允许的误差时间(秒数),以应对不同服务器之间的时钟差异
    • maxAge: 令牌的最大允许有效期。以秒表示或描述时间跨度 zeit/ms 的字符串。如 1000, "2 days", "10h", "7d"
    • clockTimestamp
// 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
});

jwt.decode(token , options)

(同步) 返回解码后的 payload ,但不验证签名是否有效。

  • token is the JsonWebToken string
  • options:
    • json force JSON.parse on the payload even if the header doesn't contain "typ":"JWT".
    • complete 解码后是否包含 payloadheader

示例

// get the decoded payload ignoring signature, no secretOrPrivateKey needed
var decoded = jwt.decode(token);

// get the decoded payload and header
var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload)

Errors & Codes

TokenExpiredError

令牌过期的错误

Error 对象:

  • 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

Error 对象:

  • 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'
      }
    */
  }
});

支持的算法

支持算法数组。目前支持以下算法。

参数值算法
HS256HMAC using SHA-256 hash algorithm
HS384HMAC using SHA-384 hash algorithm
HS512HMAC using SHA-512 hash algorithm
RS256RSASSA using SHA-256 hash algorithm
RS384RSASSA using SHA-384 hash algorithm
RS512RSASSA using SHA-512 hash algorithm
ES256ECDSA using P-256 curve and SHA-256 hash algorithm
ES384ECDSA using P-384 curve and SHA-384 hash algorithm
ES512ECDSA using P-521 curve and SHA-512 hash algorithm
noneNo digital signature or MAC value included