jwt.sign()每次都将令牌添加到前一个令牌

时间:2017-11-26 06:37:36

标签: node.js angular mongoose jwt

每次当我向验证路由发送请求时,将令牌添加到前一个令牌。我找不到这个问题的原因

const express = require("express");
const router = express.Router();
const User = require("../models/user");
const bcrypt = require("bcryptjs");
const config = require("../config/data");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");

//Registration route
router.post("/register",(req,res)=>{
    let date=new Date();
    let newUser = new User({
        name:req.body.name,
        email:req.body.email,
        password:req.body.password,
        role:"User",
        isActive:true,
        created:date,
        updatedToken:"JWT"

    });
    User.addUser(newUser,(err,user)=>{
        if(err){
            res.json({success: false, msg:'Failed to register user'});
          } else {
            res.json({success: true, msg:'User registered'});
          }
    });


});

//Authentication route
router.post('/authenticate', (req, res) => {
    const email = req.body.email;
    const password = req.body.password;

    User.getUser(email, (err, user) => {
      if(err) throw err;
      if(!user){
        return res.json({success: false, msg: 'User not found'});
      }

      User.comparePassword(password, user.password, (err, isMatch) => {
        if(err) throw err;
        if(isMatch){
          let payload={
            name:user.name,
            email:user.email,
            role:user.role,
            deleted:user.deleted,
            isActive:user.isActive,
            created:user.created,
            updatedToken:user.updatedToken,
          };

          let token=jwt.sign(payload,config.secret)

          User.saveToken(email,token,(err,success)=>{
            if(err) return err;
            console.log("Success");
            res.json({
              success: true,
              token: token
            });
          }); 


        } else {
          return res.json({success: false, msg: 'Wrong password'});
        }
      });
    });
  });
//   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
//         jwt.verify(token, app.get('superSecret'), 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.' 
//         });

//       }
//     });

//     // Dashboard
// router.get('/dashboard', (req, res) => {
//   res.json({user: req.user});
// });

module.exports = router;
  

这是Schema和函数

const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const config = require("../config/data");
const jwt = require("jsonwebtoken");

let userSchema = mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    },
    role:{
        type:String,
        required:true
    },
    deleted:{
        type:Date,
        default:null,

    },
    isActive:{
        type:Boolean,
        required:true
    },
    created:{
        type:Date,
        required:true
    },
    updatedToken:{
        type:String,
        required:true
    }
});

let User = module.exports = mongoose.model('User',userSchema,'Users');


module.exports.getUser = function(username, callback){
    let query = {email: username}
    User.findOne(query, callback);
}

module.exports.addUser = function(newUser, callback){
    bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(newUser.password, salt, (err, hash) => {
        if(err) throw err;
        newUser.password = hash;
        newUser.save(callback);
    });
    });
}

module.exports.comparePassword = function(candidatePassword, hash, callback){
    bcrypt.compare(candidatePassword, hash, (err, isMatch) => {
    if(err) throw err;
    callback(null, isMatch);
    });
}
module.exports.saveToken = function(username,token,callback){
    let query = {email:username};
    let updateToken={updatedToken:token};
    User.findOneAndUpdate(query,updateToken,callback);
}
module.exports.generateToken=function(payload,secret){
    let token = jwt.sign(payload,secret,{
        expiresIn: 604800
    })
    return token;
}
  

这是服务器

const express = require ("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const config = require("./config/data");
const cors = require("cors");
const morgan = require("morgan");

const route = require("./routes/users");
mongoose.Promise = global.Promise;

let options = {
    useMongoClient: true,
    reconnectTries: Number.MAX_VALUE, 
    reconnectInterval: 500, 
    poolSize: 10,
    bufferMaxEntries: 0
  };

mongoose.connect(config.database,options);

let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
 console.log( `DB connected ${new Date()}...`);
});


app.use(bodyParser.json());

app.use(cors());

app.use(morgan('dev'));

app.get('/',(req,res)=>{
    res.send("Works aziz");
});

app.use("/users",route);


app.listen(config.port,()=>{
    console.log(`Server running ${config.port}...`);
});

我需要这样,如果用户做post认证路由请求,它必须生成令牌并将其提供给变量令牌,而不是每次用户做post请求时都连接。 非常感谢!!!!!!

1 个答案:

答案 0 :(得分:0)

看起来错误在于有效负载内的updatedToken:user.updatedToken,。当您第一次注册JWT时,因为这是您在注册控制器中设置的内容。例如。有实际价值

let payload={
  name: "testuser",
  email: "test@example.com",
  role: "user",
  deleted: false,
  isActive: true,
  created: 2017-11-26,
  updatedToken: "JWT",
};

首次身份验证后,user.updatedToken会使用您在saveToken()中设置的令牌进行更新。那是 ey ...... 的东西。

在第二次身份验证之后,您要在有效负载内添加长JWT令牌( ey ... ):

let payload={
  name: "testuser",
  email: "test@example.com",
  role: "user",
  deleted: false,
  isActive: true,
  created: 2017-11-26,
  updatedToken: "ey1232abc456...",
};

这是保存到user.updatedToken的新令牌的有效负载。您将旧令牌保存在新令牌中。

所以我非常确定有效负载内的updatedToken必须去。