我如何存储JWT并使用react将其与每个请求一起发送 [英] How do I store JWT and send them with every request using react

查看:478
本文介绍了我如何存储JWT并使用react将其与每个请求一起发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很高兴知道,因为我的基本注册/身份验证系统正在运行.

So happy right know because I got my basic registration/authentication system going on.

所以基本上我得到了这个:

so basically I got this :

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的安全,一切正常.

Then I secure my /admin routes and with POSTMAN whenever I send a get request with the jwt in the header everything works perfectly.

现在这是棘手的部分,基本上,当我要登录时(如果成功),然后将我重定向到管理页面,并且每次尝试访问admin/*路由时,我都想将jwToken发送到服务器,但是问题是,我该如何实现?我不是在使用redux/flux,而是在使用react/react-router.

Now here is the tricky part, basically When i'm going to login if this a sucess then redirect me to the admin page, and everytime I try to access admin/* routes I want to send to the server my jwToken but the problem is, how do I achieve that ? I'm not using redux/flux, just using react/react-router.

我不知道机械师的工作原理.

I don't know how the mechanic works.

谢谢大家

推荐答案

1-登录组件向API服务器端点发送登录请求

1- login component send a login request to the API server endpoint

2-服务器API端点返回令牌

2- server API endpoint returns a token

3-我将令牌保存在用户的localStorage中

3- I save the token in user's localStorage

4-从现在开始,所有API调用都将包含在标题中

4- all the API calls from now on will have in the header

示例: https://github.com/joshgeller/react-redux -jwt-auth-example

安全更新: 正如@Dan在评论中提到的那样,不应将令牌存储在Localstorage中,因为每个JavaScript脚本都可以访问该脚本,这意味着您不拥有的第三方脚本可以访问令牌并对其进行任何操作.

Security update: As @Dan mentioned in the comment, tokens should not be stored in Localstorage because every javascript script has access to that one, which means third party scripts you don't own could access tokens and do whatevery they want with it.

一个更好的地方是使用HttpOnly标志将其存储为Cookie.

A better place is to store it as a Cookie with HttpOnly flag.

这篇关于我如何存储JWT并使用react将其与每个请求一起发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆