JsonWebTokenError: invalid signature when verifying the jwt token

JsonWebTokenError: invalid signature when verifying the jwt token

我正在实施一个网络应用程序,其中包含一个聊天机器人,可以在即将到来的 google 日历活动时提醒用户。当用户授权时,我已成功生成一个 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!")
              
        } ) 
  
  });

我做错了什么吗??

  1. 您使用一对私钥和 public 很好。使用非对称签名比使用对称签名更好。

  2. 在您的代码中,我可以看到您在 httpOnly cookie 中发送 JWT 令牌,但随后在 landingPage 中您从 Authorization header。不确定那应该如何工作。您确定要将正确的 JWT 发送到 /landingPage 端点吗?

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