JsonWebTokenError:jwt格式错误(在ExpressJs中创建API) [英] JsonWebTokenError: jwt malformed (creating an API in ExpressJs)

查看:227
本文介绍了JsonWebTokenError:jwt格式错误(在ExpressJs中创建API)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上检查了许多答案,但我想我也在犯其他错误.我的问题与使用JWT(这是POST请求)保护/contribute 路由严格相关.我的API在 expressjs 中.首先,我使用正确的凭据点击/login 路由并获得令牌.我在 jwt.io 上进行了交叉检查,并说无效签名".这是令牌: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWJqZWN0IjoiNWVhZDlkOGY4N2VjMjkwMDE3YzRkODkziiwiaWF0IjoxNjA3ZnzR4JJ4_JF_JJ4_JF_JJ4_JF_JJ4_JF_JJ4_JF_JJ4B

然后我将使用相同的令牌命中/contribute 路线.这是我的代码:

api.js

  const express = require('express');const router = express.Router();...const jwt = require('jsonwebtoken');...router.post('/login',(req,res)=> {让userData = req.bodyUser.findOne({电子邮件:userData.email},(错误,用户)=> {如果(错误){console.log(错误)} 别的 {如果(!user){res.status(401).send('无效的电子邮件')} else if(user.password!== userData.password){res.status(401).send('无效的密码')} 别的 {让payLoad = {subject:user._id};//也尝试过{subject:'foobar'}让令牌= jwt.sign(payLoad,'secretKey');res.status(200).send({令牌,userData,用户});}}})})router.post('/contribute',verifyToken,(req,res)=> {console.log('推送新文章');让userPost = req.body;let post = new Post(userPost);post.save((错误,registeredPost)=> {如果(错误){console.log(错误);} 别的 {res.status(200).send(registeredPost);}})})函数verifyToken(req,res,next){如果(!rehead.headers.authorization){返回res.status(401).send('未经授权的请求')}让令牌= req.headers.authorization.split('')[1];如果(令牌==='null'){返回res.status(401).send('未经授权的请求')}让有效负载= jwt.verify(token,'secretKey')如果(!payload){返回res.status(401).send('未经授权的请求')}req.userId = payload.subject下一个()}module.exports =路由器; 

但是当我点击/contribute 时,我得到了:

JsonWebTokenError:jwt格式错误在Object.module.exports [作为验证](C:\ Users \ 320050772 \ Documents \ socialcoderapinodejs \ node_modules \ jsonwebtoken \ verify.js:63:17)在verifyToken(C:\ Users \ 320050772 \ Documents \ socialcoderapinodejs \ routes \ api.js:86:23)在Layer.handle上[作为handle_request](C:\ Users \ 320050772 \ Documents \ socialcoderapinodejs \ node_modules \ express \ lib \ router \ layer.js:95:5)在下一个(C:\ Users \ 320050772 \ Documents \ socialcoderapinodejs \ node_modules \ express \ lib \ router \ route.js:137:13)在Route.dispatch(C:\ Users \ 320050772 \ Documents \ socialcoderapinodejs \ node_modules \ express \ lib \ router \ route.js:112:3)在Layer.handle上[作为handle_request](C:\ Users \ 320050772 \ Documents \ socialcoderapinodejs \ node_modules \ express \ lib \ router \ layer.js:95:5)

请指出我的错误.

我也检查了邮递员.令牌已生成,但再次无效.为什么我的代码生成无效令牌.

解决方案

已注意到生成的令牌有效.但是它没有到​​达即将到来的下一个呼叫的后端,例如/contribute的帖子.显示一些无效的值.因此,让有效令牌到达后端,以便jwt.varify可以正确验证它.

I've checked many answers on the internet but I think I'm doing some other mistake also. My question is strictly related to guarding /contribute route using JWT (which is a POST request). My API is in expressjs. First I hit /login route with correct credentials and get a token. This token I cross checked on jwt.io and it says "Invalid Signature". Here is that token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWJqZWN0IjoiNWVhZDlkOGY4N2VjMjkwMDE3YzRkODkzIiwiaWF0IjoxNjA3ODczNjY2fQ.H5RI-lOBzfJo4_FgParuJA4ULnJ_An6uihiF31bzNtU

Then I would hit /contribute route with the same token. Here is my code:

api.js

const express = require('express');
const router = express.Router();
...
const jwt = require('jsonwebtoken');
...
router.post('/login', (req, res) => {
    let userData = req.body
    User.findOne({ email: userData.email }, (error, user) => {
        if (error) {
            console.log(error)
        } else {
            if (!user) {
                res.status(401).send('Invalid email')
            } else if (user.password !== userData.password) {
                res.status(401).send('Invalid password')
            } else {
                let payLoad = { subject: user._id };  // tried { subject: 'foobar' } also
                let token = jwt.sign(payLoad, 'secretKey');
                res.status(200).send({ token, userData, user });
            }
        }
    })
})

router.post('/contribute', verifyToken, (req, res) => {
    console.log('Pushing new article');
    let userPost = req.body;
    let post = new Post(userPost);
    post.save((error, registeredPost) => {
        if (error) {
            console.log(error);
        } else {
            res.status(200).send(registeredPost);
        }
    })
})

function verifyToken(req, res, next) {
    if (!req.headers.authorization) {
        return res.status(401).send('Unauthorized request')
    }
    let token = req.headers.authorization.split(' ')[1];
    if (token === 'null') {
        return res.status(401).send('Unauthorized request')
    }
    let payload = jwt.verify(token, 'secretKey')
    if (!payload) {
        return res.status(401).send('Unauthorized request')
    }
    req.userId = payload.subject
    next()
}

module.exports = router;

But the moment I hit /contribute I get this:

JsonWebTokenError: jwt malformed at Object.module.exports [as verify] (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\jsonwebtoken\verify.js:63:17) at verifyToken (C:\Users\320050772\Documents\socialcoderapinodejs\routes\api.js:86:23) at Layer.handle [as handle_request] (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\express\lib\router\layer.js:95:5)

Please point out my mistake.

I checked on Postman also. Token is generated but again it is invalid. Why my code is generating invalid tokens.

解决方案

It been noticed that Generated Token is valid. But its not been reaching to backend with upcoming next call e.g Post of /contribute. showing some non-valid value. Therefore, let the valid token to be arrived on Backend so that jwt.varify could validate it correctly.

这篇关于JsonWebTokenError:jwt格式错误(在ExpressJs中创建API)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆