【问题标题】:JsonWebTokenError: invalid signature when verifying the jwt tokenJsonWebTokenError:验证 jwt 令牌时签名无效
【发布时间】:2021-06-28 15:19:36
【问题描述】:

我正在实现一个网络应用程序,其中包含一个聊天机器人,它将提醒用户他即将发生的谷歌日历活动。当用户授权时,我已成功生成 jwt 令牌,但是,当我验证令牌时,我收到此错误“JsonWebTokenError:无效签名”。我对这些概念还很陌生,所以我非常感谢任何帮助。

这是我签署令牌的地方:

  let iss = 'GoogleCalender'
  let sub = 'example@gmail.com'
  let aud = 'xxxxxxxxxxxxxx'
  let exp = '24h'

  let sighOptions = {
    issuer: iss,
    subject: sub,
    audience: aud,
    expiresIn: exp,
    algorithm: "RS256"

  }

  app.get('/landingPage', (req, res) => {
    const token = jwt.sign({ user: 'iman' }, privateKey , sighOptions);
    res.cookie('token', token,{ httpOnly: true });
    res.sendFile(path.join(__dirname, "./landingPage.html"));
  });

这是我验证令牌的地方:


  let verifyOptions = {
    issuer: iss,
    subject: sub,
    audience: aud,
    maxAge: exp,
    algorithms: "RS256"

  }

  function verifyToken(req,res,next){
    const baererHeader = req.headers['authorization']
    if(typeof baererHeader !== 'undefined'){
      const baerer = baererHeader.split(' ')
      const baererToken = baerer[1]
      req.token = baererToken
      next()
    }
    else{
      res.sendStatus(403)
    }
  }

  app.post('/landingPage',verifyToken, express.json(),(req,res)=>{
    token = req.token
    jwt.verify(token, publicKey, verifyOptions, (err,authData) =>{
        const calendar = google.calendar({version: 'v3' , auth:createConnection()});
        const agent = new dfff.WebhookClient({
            request : req,
            response : res
          })
          if(err) {
            console.log(err)
            function welcome(agent){
              agent.add("Hi, Im helen, Please log in so i can remind you on your upcoming events")
            }
            }
           else{
              function welcome(agent){
                agent.add("Hi, I'm Rem. Please click on remind me button if you want to be reminded on your upcoming events!")
              
        } ) 
  
  });

有什么我做错了吗??

【问题讨论】:

  • 为什么要生成 JWT 签名?访问谷歌日历 api? Oauth2
  • 在签署令牌时使用一个密钥,在验证它时使用不同的密钥 privateKey 和 publicKey。尝试使用相同的密钥怎么样?
  • @Hairi 签名算法是 RS256,这是一种使用 RSA 加密的非对称算法。使用私钥签名和公钥验证是绝对正确的。当然重要的是它是一个匹配的密钥对。
  • @DalmTo 是的,jwt 是用来访问用户谷歌日历的。
  • @jps 所以我从您的评论中了解到,您是说我的两个键必须具有相同的内容?

标签: node.js express google-api jwt google-calendar-api


【解决方案1】:
  1. 最好使用一对私钥和公钥。使用非对称签名比使用对称签名更好。

  2. 在您的代码中,我可以看到您在 httpOnly cookie 中发送 JWT 令牌,但是在 landingPage 中,您从 Authorization 标头中读取它。不知道这应该如何工作。您确定将正确的 JWT 发送到 /landingPage 端点吗?

  3. 如果您想使用您自己发布的 JWT 来访问 Google 日历中的用户数据,那么它将无法正常工作。要访问这些数据,您需要 Google 颁发的访问令牌。查看 Google 的文档以检查如何从他们那里获取访​​问令牌,这将允许您调用日历 API。您仍然可以使用您正在创建的令牌来保护您自己的端点。因此:用户需要您的令牌才能调用您的端点,然后将使用来自 Google 的令牌来调用日历 API。

【讨论】:

  • 谢谢米哈尔!你的评论很有帮助。
猜你喜欢
  • 2018-07-14
  • 2017-03-08
  • 2019-11-01
  • 2018-05-29
  • 1970-01-01
  • 2017-09-18
  • 2020-05-11
  • 2021-02-12
  • 2017-05-30
相关资源
最近更新 更多