当您使用 node-jsonwebtoken 签署令牌时,您通常只会获得默认标头
{
alg: "HS256",
typ: "JWT"
}
如果您在标题中需要任何额外的值,例如密钥 ID kid,您可以将它们添加到 options.header 对象中。您需要将 options 对象作为第三个参数传递给 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
}