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

问题描述

限时删除!!

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

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

所以基本上我明白了:

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 请求时,我都会使用 POSTMAN 保护我的/admin 路由,一切正常.

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.

谢谢大家

推荐答案

不要将token存储在localStorage中,使用xss攻击可能会破坏token.我认为最好的解决方案是在登录操作时向客户端提供访问令牌和刷新令牌.将访问令牌保存在内存中(例如 redux 状态),并且应该在服务器上使用 httpOnly 标志创建刷新令牌(如果可能,还要使用安全标志).访问令牌应设置为每 2-3 分钟过期一次.为了确保用户不必每 2-3 分钟输入一次凭据,我设置了一个间隔,在当前令牌过期之前调用 /refreshToken 端点(静默刷新令牌).

Do not store the token in localStorage, the token can be compromised using xss attack.I think the best solution will be to provide both access token and refresh token to the client on login action.save the access token in memory (e.g redux state) and the refresh token should be created on the server with httpOnly flag (and also secure flag if possible).The access token should be set to expire every 2-3 minutes.In order to make sure that the user will not have to enter his credentials every 2-3 minutes I have an interval which calls the /refreshToken endpoint before the current token expires (silent refresh token).

这样,访问令牌就不会被 xss/csrf 破坏.但是使用 xss 攻击,攻击者可以代表您调用 /refreshToken 端点,但这不会有害,因为返回的令牌不会被破坏.

that way, the access token cannot be compromised using xss/csrf.but using an xss attack, the attacker can make a call on your behalf to the /refreshToken endpoint, but this will not be harmful because the returned token cannot be compromised.

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

1403页,肝出来的..

09-06 23:29