如何使用nodejs进行jwt令牌验证

时间:2019-04-25 12:17:44

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

如何在节点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);
        }
      })();

  });

1 个答案:

答案 0 :(得分:0)

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令牌的方式