令牌无效:JsonWebTokenError:jwt格式错误的nodejs

时间:2017-10-11 17:49:57

标签: node.js jwt

我正在学习如何使用NodeJS,并且在遵循在线教程时我在标题中出现了错误。

我使用的是最新版本的NodeJS和jsonwebtoken身份验证。

这是我生成令牌的方式:

 router.post('/login', (req, res) => {
    // Check if username was provided
    if (!req.body.username) {
      res.json({
        success: false,
        message: 'No username was provided'
      }); // Return error
    } else {
      // Check if password was provided
      if (!req.body.password) {
        res.json({
          success: false,
          message: 'No password was provided.'
        }); // Return error
      } else {
        // Check if username exists in database
        User.findOne({
          username: req.body.username.toLowerCase()
        }, (err, user) => {
          // Check if error was found
          if (err) {
            res.json({
              success: false,
              message: err
            }); // Return error
          } else {
            // Check if username was found
            if (!user) {
              res.json({
                success: false,
                message: 'Username not found.'
              }); // Return error
            } else {
              const validPassword = User.comparePassword(req.body.password, user.password); // Compare password provided to password in database
              // Check if password is a match
              if (!validPassword) {
                res.json({
                  success: false,
                  message: 'Password invalid'
                }); // Return error
              } else {
                const token = jwt.sign({
                  userId: user._id
                }, 'goodsecret', {
                  expiresIn: '24h'
                }); // Create a token for client
                res.json({
                  success: true,
                  message: 'Success!',
                  token: token,
                  user: {
                    username: user.username
                  }
                }); // Return success and token to frontend
              }
            }
          }
        });
      }
    }
  });

我在这里评估它:

const jwt = require('jsonwebtoken');

/* ================================================
  MIDDLEWARE - Used to grab user's token from headers
  ================================================ */
  router.use((req, res, next) => {
    const token = req.headers.authorization; // Create token found in headers
    // Check if token was found in headers
    if (!token) {
      res.json({
        success: false,
        message: 'No token provided'
      }); // Return error
    } else {
      // Verify the token is valid
      console.log(token);
      jwt.verify(token, 'goodsecret', (err, decoded) => {
        // Check if error is expired or invalid
        if (err) {
          res.json({
            success: false,
            message: 'Token invalid: ' + err
          }); // Return error for token validation
        } else {
          req.decoded = decoded; // Create global variable to use in any request beyond
          next(); // Exit middleware
        }
      });
    }
  });

  /* ===============================================================
     Route to get user's profile data
  =============================================================== */
  router.get('/profile', (req, res) => {
    // Search for user in database
    User.findOne({
      _id: req.decoded.userId
    }).select('username email').exec((err, user) => {
      // Check if error connecting
      if (err) {
        res.json({
          success: false,
          message: err
        }); // Return error
      } else {
        // Check if user was found in database
        if (!user) {
          res.json({
            success: false,
            message: 'User not found'
          }); // Return error, user was not found in db
        } else {
          res.json({
            success: true,
            user: user
          }); // Return success, send user object to frontend for profile
        }
      }
    });
  });

每当我尝试从HttpRequester生成请求,发送令牌时,我会在标题中收到错误。我发送的令牌是

  

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1OWRlMTYzNTMwOWY2NDM1YjBjOWRmM2UiLCJpYXQiOjE1MDc3NDMzODYsImV4cCI6MTUwNzgyOTc4Nn0.uJwpYN7IHYg_lmCVCpFg-zfo0QVPglEvWHs7SD9cPkg

并在https://jwt.io/上运行正常,使用代码中的秘密'goodsecret'。我错过了什么?

这是一个关于我如何生成请求的屏幕。

感谢您的帮助

0 个答案:

没有答案