2017-01-15 82 views
0
apiRoutes.post('/authenticate', function(req, res) { 
    User.findOne({ 
    name: req.body.name 
    }, function(err, user) { 
    if (err) throw err; 

    if (!user) { 
     res.send({success: false, msg: 'Authentication failed. User not found.'}); 
    } else { 
     // check if password matches 
     user.comparePassword(req.body.password, function (err, isMatch) { 
     if (isMatch && !err) { 
      // if user is found and password is right create a token 
      var expires=moment().add(1,'days').valueOf(); 
      var token = jwt.encode(user, config.secret,{ 
      exp: expires}); 
      // return the information including token as JSON 
      res.json({success: true, token: 'JWT ' + token}); 
     } else { 
      res.send({success: false, msg: 'Authentication failed. Wrong password.'}); 
     } 
     }); 
    } 
    }); 
}); 

它提示錯誤: /home/oracle/node/ang_backend1/node_modules/jwt-simple/lib/jwt.js:130 拋出新的錯誤('算法不支持'); ^如何添加到期日期智威湯遜 - 簡單令牌

錯誤:在/家裏Object.jwt_encode [如編碼(/home/oracle/node/ang_backend1/node_modules/jwt-simple/lib/jwt.js:130:11) 不支持 算法/oracle/node/ang_backend1/app.js:198:27 at /home/oracle/node/ang_backend1/app/models/user.js:48:9 at/home/oracle/node/ang_backend1/node_modules/bcryptjs /dist/bcrypt.js:261:17 at /home/oracle/node/ang_backend1/node_modules/bcryptjs/dist/bcrypt.js:1198:21 at Immediate.next [as_onImmediate](/ home/oracle/node /ang_backend1/node_modules/bcryptjs/dist/bcrypt.js:1078:21) 在processImmediate [按_immediateCallback](timers.js:383:17)

回答

0

我想你沒有得到令牌,你應該這樣做:

var expires=moment().add(1,'days').valueOf(); 
      var token = jwt.encode(user, config.secret,{ 
      exp: expires}),app.get('jwtTokenSecret')); 
+0

它仍然提示同樣的錯誤添加app.get後('jwtTokenSecret'),還有其他建議嗎? –

+0

任何人都可以幫忙?謝謝 –

0

你的安全路由應該被定義爲:

router.get('/enums', passport.authenticate('jwt', {session: false}), async (req, res) => { ... 

其中const passport = require('passport')

爲了增加到期時間令牌您必須設置兩個參數(以秒爲單位):expnbf這樣的:

let expires = (Date.now()/1000) + 60 * 30 
let nbf = Date.now()/1000 

let token = await jwt.encode({nbf: nbf, exp: expires, id: user_id}, jwtSecret). 

其中const jwt = require('jwt-simple')