【问题标题】:how to jwt token verify using nodejs如何使用nodejs进行jwt令牌验证
【发布时间】:2019-09-14 21:03:16
【问题描述】:

如何在节点js中实现jwt验证令牌实现。我已经尝试过但它没有显示错误但它显示未定义。如何解决这个问题。

auth.py

function jwtAccessAuthCheck(accessToken)
{
    if(accessToken)
    {
        console.log("Sucess")
        jwt.verify(accessToken,"secretkey",function(err){
            if(err) {
                console.log(typeof(err.message))
                return err.message
            } 
            else {
                return "token"
            }
          });

    }
    else
    {
        return "Invalid token"
    }
}

routes.py

//Get Data from Database
router.get('/', async (req, res,next) => {
    (async function() {
        try {
          await client.connect();
          console.log("Connected correctly to server");
          const db = client.db('olc_prod_db');
          const token_validation = validate_token.validate_token(req.headers.authorization)
          console.log((token_validation))
          const r = await db.collection('Ecommerce').find().toArray();
          client.close();
          res.send(r)
        } catch(err) {
          console.log(err.stack);
        }
      })();

  });

【问题讨论】:

  • 你使用的是 jsonwebtoken npm 包吗?还有哪里抛出了未定义的错误?
  • 是的..首先我传递给 auth.py 中的 jsonwebtoken 传递。然后它的检查令牌是否验证。token 不是验证返回错误消息给 router.py.那个消息我试图打印它显示未定义。
  • 另外我不明白 validate_token.validate_token(req.headers.authorization) 函数调用,你的验证函数是 jwtAccessAuthCheck 不是吗?
  • 是的,我尝试导出函数。 export.validate_token = jwtAccessAuthCheck;在 auth.py 文件中
  • 为什么你在 node.js 中使用 .py 后缀?

标签: node.js nodejs-stream nodejs-server


【解决方案1】:
const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const bodyparser = require('body-parser');
const user = {username : "user",password : "pass"}

app.use(bodyparser.json());

const checkToken = function (req,res,next)
{
    const header = req.headers['authorization'];
    if(typeof header !== 'undefined')
    {
       const bearer = header.split(' ');
       const token = bearer[1];
       req.token=token;
       next();
     }
     else
     {
        res.sendStatus(403);
     }
    }


app.post('/login',function (req,res)
{
    const { body } = req;
    const { username } = body;
    const { password } = body;

    if(username === user.username && password === user.password)
    {
        jwt.sign({user},'privatekey',{expiresIn : '1h'},function (err,token){
            if(err)
            {
                console.log(err)
            }
            console.log(token);
            res.end();
        });
    }
    else
    {
        console.log('Error : Could not log in');
    }
});

app.get('/data',checkToken,function(req,res)
{
    jwt.verify(req.token,'privatekey',function (err,authorizedata)
    {
        if(err)
        {
            console.log('Error : Could not connect to the protected route');
            res.sendStatus(403);
        }
        else
        {
            res.json({
                message : 'Successful log in',
                authorizedata
            });
            console.log('Success : Connected to protected route');
        }

    });

});

app.listen(3000,console.log("Server is running at 3000"));

这就是我实现 JWT 令牌的方式

【讨论】:

    猜你喜欢
    • 2016-01-17
    • 2016-12-13
    • 2018-11-01
    • 2020-11-18
    • 2020-11-22
    • 2021-08-17
    • 2018-10-16
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多