Jwt令牌验证时出现了“无效签名”的JsonWebTokenError

3

我正在实现一个包含聊天机器人的Web应用程序,该机器人将提醒用户即将发生的谷歌日历事件。我已成功生成了JWT令牌,并获得了用户授权,但是在验证令牌时出现了错误"JsonWebTokenError: invalid signature"。由于这些概念对我来说还很新,所以我非常感谢任何帮助。

以下是我签署令牌的位置:

  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签名?是为了访问Google日历API吗?Oauth2 - Linda Lawton - DaImTo
1
在签署令牌时,您使用一个密钥,在验证时则使用不同的密钥,即私钥与公钥。那么尝试使用相同的密钥呢? - Hairi
@Hairi 签名算法是RS256,这是一种使用RSA加密的非对称算法。使用私钥进行签名和公钥进行验证是绝对正确的。当然,重要的是它是匹配的密钥对。 - jps
@DalmTo 是的,JWT 用于访问用户的 Google 日历。 - Iman Ashour
@jps,根据您的评论,我的理解是您在说我必须为两个键拥有相同的内容? - Iman Ashour
@ImanAshour,不确定您所说的“相同内容”是什么意思。我只是指使用一对密钥,一个私钥和一个公钥,它们彼此配对。我的评论主要是针对另一条评论中错误的建议。 - jps
1个回答

3
  1. 你使用私钥和公钥是很好的选择。使用非对称签名比对称签名更好。
  2. 在你的代码中,我看到你将JWT令牌发送到httpOnly cookie中,但是在landingPage中却从Authorization头中读取它。不确定这该怎么工作。你确定你正在向/landingPage端点发送正确的JWT吗?
  3. 如果你想使用自己发布的JWT来访问用户在Google日历中的数据,那么是行不通的。要访问此数据,您需要谷歌发行的访问令牌。查看谷歌的文档以了解如何从他们那里获取允许您调用日历API的访问令牌。您仍然可以使用您创建的令牌来保护自己的端点。因此:用户将需要您的令牌才能调用您的端点,然后将使用来自谷歌的令牌来调用日历API。

谢谢Michal!你的评论非常有帮助。 - Iman Ashour

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接