0

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

授权文件

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"
    }
}

路线.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);
        }
      })();

  });
4

1 回答 1

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

于 2019-06-05T12:17:08.857 回答