首页 > 解决方案 > 带有自定义标头和声明的 jsonwebtoken

问题描述

Apple App Store 服务器进行身份验证,我的标题如下

{
  alg: "HS256", 
  typ: "JWT",
  kid: kid
}

和价值如下的索赔:

{
  iss: issuerID,
  aud: audience,
  ...
}

node-jsonwebtoken库中,我尝试使用标头作为有效负载和声明作为选项进行签名:

jwt.sign(jwtHeader(), key, jwtClaims(), cb)

这最终会引发异常,例如Error: "iss" is not allowed in "options". 否则,请继续收到401 Unauthorized回复。我如何使用这个库来适当地签署我的标题和声明?

标签: node.jsjwtapp-storeauth0

解决方案


当您使用 node-jsonwebtoken 签署令牌时,您通常只会获得默认标头

{
  alg: "HS256", 
  typ: "JWT"
}

如果您在标头中需要任何额外的值,例如 key-id kid,您可以将它们添加到options.header对象中。您需要将选项对象作为第三个参数传递给 sign 函数:

const keyId = 123
const jwtOptions = {
    header: { kid: keyId }
}

选项对象也是您可以添加到期时间、设置不同的签名算法(默认为HS256)或关闭自动生成的时间戳iat(发布于)的地方。

const jwt = require('jsonwebtoken');

// define the payload
const payload = {
    iss: "issuerID",
    aud: "audience"
}

const keyId = 123

// extra header values can be defined in the header parameter in the options:
const jwtOptions = {
    expiresIn: 300,      // 300 seconds
    //algorithm: 'HS512',  // only necessary if you want a different value than 'HS256' 
    //notimestamp: true, // don't added timestamp iat (issued at)
    header: { kid: keyId
            }
}
  
// pass the options as third parmater (optional)
const token = jwt.sign(payload, "supersecret", jwtOptions);

结果:

header:
{
  "alg": "HS256",
  "typ": "JWT",
  "kid": "123"
}

payload:
{
  "iss": "issuerID",
  "aud": "audience",
  "iat": 1630044877,
  "exp": 1630044887
}

推荐阅读