Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

express - How do I store JWT and send them with every request using 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'});

       }
     });
    }
 });
});

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

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.

Thanks guys

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...