简体   繁体   English

无法验证 JWT - UnhandledPromiseRejectionWarning: JsonWebTokenError: jwt 格式错误

[英]Cannot verify JWT - UnhandledPromiseRejectionWarning: JsonWebTokenError: jwt malformed

I have function that just send data to database (my posts).我有 function 只是将数据发送到数据库(我的帖子)。 I use private and public keys to sign and verify tokens.我使用私钥和公钥来签署和验证令牌。 I can send this token in header from front-end to back-end, but has problem with verifying it.我可以在 header 中将此令牌从前端发送到后端,但验证时遇到问题。 Here is how this flow looks like:下面是这个流程的样子:

Front-end前端

router.post(`/p-p`, async (req, res) => {
  try {
    const data = await api.post(`/post-post`, req.body, {
      headers: {
        Authorization: 'Bearer ' + req.body.token
      }
    })
    res.json(data.data)
  } catch (e) {
    res.status(e.response.status).json(e.response.data)
  }
})

Back-end后端

router.post(
  "/post-post",
  auth,
  wrapAsync(generalController.postPost)
)

Middleware auth中间件认证

const jwtService = require('./../services/jwtService')

module.exports = async(req, res, next) => {
  if (req.headers.authorization) {
    const user = await jwtService.getUser(req.headers.authorization.split(' ')[1])
    if (user) {
      next();
    } else {
      res.status(401).json({
        error: 'Unauthorized'
      })
    }
  } else {
    res.status(401).json({
      error: 'Unauthorized'
    })
  }
}

And JWT service和JWT服务

const jwt = require('jsonwebtoken');
const fs = require("fs");
const path = require("path");

const pathToKeys = path.resolve(__dirname, "../../keys");

module.exports = {
  sign(payload) {
    const cert = fs.readFileSync(`${pathToKeys}/private.pem`);
    return jwt.sign(
      payload,
      {
        key: cert,
        passphrase: process.env.JWT_PASSPHRASE
      },
      {
        algorithm: "RS256",
        expiresIn: "30m"
      }
    )
  },
  getUserPromise(token) {
    return new Promise((resolve, reject) => {
      jwt.verify(token, fs.readFileSync(`${pathToKeys}/public.pem`), (err, decoded) => {
        if(!err) {
          return resolve(decoded);
        } else {
          return reject(err);
        }
      })
    })
  },
  async getUser (token) {
    return await this.getUserPromise(token)
  }
}

The problem starts after getUserPromise function. This function can get a token, but can't verify it and I have this problem:问题在getUserPromise function之后开始。这个function可以拿到一个token,但是无法验证,我遇到了这个问题:

UnhandledPromiseRejectionWarning: JsonWebTokenError: jwt malformed

Actually, I have no idea where problem is.实际上,我不知道问题出在哪里。 I generated key pair, and sign function can sing and return token, which looks like this: 351e38a4bbc517b1c81e180479a221d404c724107988852c7768d813dd0510e6183306b1d837091b2cddaa07f2427b7a我生成了密钥对,并sign function 可以唱歌并返回令牌,它看起来像这样: 351e38a4bbc517b1c81e180479a221d404c724107988852c7768d813dd0510e6183306b1d837091b2cddaa07f2427b7a

So, what's the problem?所以有什么问题?

I have found the solution of this problem and it feels shame.我已经找到了这个问题的解决方案,感觉很惭愧。 In JWT service pay attention to this string:在 JWT 服务中注意这个字符串:

algorithm: "RS256"

As you can see I use RS256 , but I generated certificates in other format, so, because of this I got that error.如您所见,我使用RS256 ,但我生成了其他格式的证书,因此,我收到了该错误。

So, if you use RSA certificates, pay attention to algorithm!所以,如果你使用RSA证书,要注意算法!

EDIT:编辑:

Here is how you can generate pair for RS256:以下是如何为 RS256 生成对:

  1. Private私人的
openssl genrsa -out private.pem -aes256 4096
  1. Public from private从私人公共
openssl rsa -in private.pem -pubout > public.pem

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM