简体   繁体   English

在node.js中使用jsonwebtokens进行身份验证

[英]authentication with jsonwebtokens in node.js

i am using jsonwebtoken for generating JSON webtokens for authenticating users, i am done with generating tokens but whenever i send token to the server it doesnot get verified it always end with TypeError: jwt.verify is not a function someone please help on this how to verify token, 我正在使用jsonwebtoken生成用于验证用户身份的JSON webtokens,已经完成了生成令牌的工作,但是每当我将令牌发送到服务器时,它都没有得到验证,它总是以TypeError结尾:jwt.verify不是一个函数,请有人对此提供帮助验证令牌,

var express = require('express');
var app = express();
 var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var moment = require('moment');

 var jwt = require('jwt-simple'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
var User = require('./models/users'); // get our mongoose model


 var port = process.env.PORT || 8080; // used to create, sign, and verify    tokens
 mongoose.connect(config.database); // connect to database
app.set('superSecret', config.secret); // secret variable

 // use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// use morgan to log requests to the console
app.use(morgan('dev'));


 var router = express.Router();
router.post('/authenticate', function(req, res, next) {
console.log(req.body.name);
User.findOne({ name: req.body.name }, function(err, user) {
    if (err) {
        throw err;
    }
    if (!user) {
        res.json({ success: false, message: 'Authentication failed. User not found.' });
    } else if (user) {
        if (user.password != req.body.password) {
            res.json({ success: false, message: 'Authentication failed. Wrong password.' });
        } else {
             // now create token here
            var token = jwt.sign(user,app.get('superSecret'),{
                expiresIn:1440 
            });

            res.json({
                success: true,
                message: 'Enjoy your token!',
                token: token
            });
        }
    }
})
})
//decoding jwt
  router.use(function(req, res, next) {

   // check header or url parameters or post parameters for token
  var token = req.body.token || req.query.token || req.headers['x-access- token'];

  // decode token
   if (token) {

   // verifies secret and checks exp
   var decode =  jwt.verify(token, "jsonWebTokens", function(err, decoded) {      
      if (err) {
         return res.json({ success: false, message: 'Failed to authenticate token.' });    
      } else {
        // if everything is good, save to request for use in other routes
       req.decoded = decoded;    
      next();
     }
    });

  } else {

    // if there is no token
  // return an error
  return res.status(403).send({ 
    success: false, 
    message: 'No token provided.' 
  });

  }
   });

 router.get('/', function(req, res, next) {
    res.send("hello and welcome to express routing");
 })

router.get('/users', function(req, res, next) {
    User.find({}, function(err, users) {
        res.json(users);

   // decode token

    })
     })

 app.use('/api', router);
 // basic route
 app.get('/', function(req, res) {
     res.send('Hello! The API is at http://localhost:' + port + '/api');
     });

 //for users
 app.get('/setup', function(req, res) {

    // create a sample user
    var nick = new User({
    name: 'Nick Cerminara',
    password: 'password',
    admin: true
    });

    // save the sample user
    nick.save(function(err) {
      if (err) throw err;

      console.log('User saved successfully');
      res.json({ success: true });
  });
 });

app.listen(port);
console.log('Magic happens at http://localhost:' + port);

i followed this tutorial https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens#authenticating-and-creating-a-token 我遵循了本教程https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens#authenticating-and-creating-a-token

var jwt = require('jwt-simple');

You should be using the npm module jsonwebtoken instead. 您应该改为使用npm模块jsonwebtoken The jwt-simple module is for encoding and decoding jsonwebtoken only. jwt-simple模块仅用于编码和解码jsonwebtoken。

See: https://www.npmjs.com/package/jwt-simple 请参阅: https//www.npmjs.com/package/jwt-simple

It does not provide you with those sign , create and verify api. 它不为您提供这些signcreateverify api。

While module jsonwebtoken does provide those APIs. 虽然jsonwebtoken模块确实提供了这些API。

JsonWebToken: JsonWebToken:
https://www.npmjs.com/package/jsonwebtoken https://www.npmjs.com/package/jsonwebtoken

To fix this, 要解决此问题,

  1. Install jsonwebtoken module, if you haven't got it. 如果没有,请安装jsonwebtoken模块。 npm install jsonwebtoken
  2. Modify variable jwt to import jsonwebtoken instead. 修改变量jwt改为导入jsonwebtoken。 var jwt = require('jsonwebtoken');

Let me know if this works. 让我知道这个是否奏效。 Glad to look further if it doesn't. 如果没有的话,很高兴进一步寻找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM