node.js - 带有自定义标头和声明的 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-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
}
推荐阅读
- python - 使用 python 创建 cassandra db 用户/角色
- javascript - 使用jquery ajax从url加载json文件的问题
- php - Cakephp 在 finder 中发出请求
- c++11 - CMake FindThreads 与现代 C++ 的正确用途是什么?
- python - 类或 __init__ 构造函数中的文档字符串?
- ios - Swift,我需要哪些项目设置和配置代码才能将 Objective C CocoaPod 与 swift 项目一起使用?
- javascript - 如果值为 true,则使用拼接删除数组项
- javascript - 隐藏所有其他子元素并添加关闭按钮
- python - Python - Matplotlib - 保持轴均匀和线性,并在网格上绘制点
- python - 使用 Ansible 进行 Vagrant 配置 - mysql_db 找不到 PyMySQL