【问题标题】:jsonwebtoken with custom header and claims带有自定义标头和声明的 jsonwebtoken
【发布时间】:2021-10-26 19:30:10
【问题描述】:

验证到Apple App Store Server,我的标题如下

{
  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.js jwt app-store auth0


    【解决方案1】:

    当您使用 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
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-14
      • 2020-02-18
      • 2017-12-28
      • 2011-03-03
      • 2014-02-18
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 2018-04-26
      相关资源
      最近更新 更多