很高兴知道,因为我的基本注册/身份验证系统正在进行中。
所以基本上我得到了这个:
app.post('/login', function(req,res) { Users.findOne({ email: req.body.email }, function(err, user) { if(err) throw err; if(!user) { res.send({success: false, message: 'Authentication Failed, User not found.'}); } else { //Check passwords checkingPassword(req.body.password, user.password, function(err, isMatch) { if(isMatch && !err) { //Create token var token = jwt.sign(user,db.secret, { expiresIn: 1008000 }); res.json({success: true, jwtToken: "JWT "+token}); } else { res.json({success: false, message: 'Authentication failed, wrong password buddy'}); } }); } }); });
然后,每当我在标头中发送带有jwt的get请求时,我就保护了/ admin路由和POSTMAN的安全,一切正常。
现在这是棘手的部分,基本上,当我要登录时是否成功,然后将我重定向到管理页面,并且每次尝试访问admin / *路由时,我都想将jwToken发送到服务器,但问题是,我该如何实现?我没有使用redux / flux,只是使用react / react-router。
我不知道机械师是如何工作的。
多谢你们
1-登录组件向API服务器端点发送登录请求
2-服务器API端点返回令牌
3-我将令牌保存在用户的localStorage中
4-从现在开始所有的API调用都将包含在标题中
示例:https://github.com/joshgeller/react-redux-jwt-auth- example
安全更新: 正如@Dan在评论中提到的那样,不应将令牌存储在Localstorage中,因为每个JavaScript脚本都可以访问该脚本,这意味着您不拥有的第三方脚本可以访问令牌并对其进行任何操作。
更好的地方是使用HttpOnly标志将其存储为Cookie。