2017-05-07 69 views
0

我知道jwt可以保存在本地存儲或cookie中。但我無法在網上找到一份好的材料以獲得指導。我如何指示服務器識別未來會話的用戶。在Cookie或本地存儲(node/angular 2網站)中保存JWT

//authenticating users by username 
router.route('/authentication').post(function(req, res) { 
    User.findOne({username : req.body.username}, function(err, user){ 
     if (err) throw err; 
     if (!user) { 
      res.json({ success: false, message: 'Authentication failed. User not found.' }); 
     } else if (user) { 

      // check if password matches 
      if (user.password != req.body.password) { 
       res.json({ success: false, message: 'Authentication failed. Wrong password.' }); 
      } else { 

       // if user is found and password is right 
       // create a token 
       var token = jwt.sign({usern : user.username}, app.get('superSecret'), { 
       //expiresInMinutes: 1440 // expires in 24 hours 
       }); 
       res.cookie('auth',token); 
       // return the information including token as JSON 
       res.setHeader('token', token); 
       res.json({ 
       success: true, 
       message: 'Enjoy your token!', 
       token: token 
       }); 
      } 
     } 
    }); 
}) 

app.use('/api', router); 

回答

0

令牌不需要在服務器上保存,這是令牌最好的事情之一。 在服務器中,您需要檢查「嘿,這個標記是由我簽署的嗎?這個標記已過期?」。 這樣的代碼:

nJwt.verify(token, secretKey, function(err, jwt){ 
    if (err) { 
    // something wrong 
    } 
} 
+0

是的但是服務器如何檢索令牌?創建一個令牌後,它保存在客戶端? –

+0

創建令牌後,發送給客戶端。在客戶端,您應該將令牌保存在變量中,並將每個請求再次發送給服務器。 – farbod

+0

我試過res.cookie('auth',令牌),它不工作。你的建議是什麼? –