Save Token in local Storage using node

前端 未结 2 1203
梦毁少年i
梦毁少年i 2021-02-04 17:59

I\'m using JWT (\"jsonwebtoken\": \"^5.4.0\") with express 4 and jade. I\'m able to create the right Token, but How can i Pass this token in each call? Where I have

2条回答
  •  失恋的感觉
    2021-02-04 18:33

    You do not need to save and check the token from the database. This token such a mechanism can be decoded with only your-server, and if it was done that the token is valid. The code that you want to do should look like.

    var cookieParser = require('cookie-parser')
    app.use(cookieParser())
    
    app.get('/login', function(req, res, next) {
      var user = {name:'test'}; //!! find the user and check user from db then
    
        var token = jwt.sign(user, 'secret', {
                expiresInMinutes: 1440
              });
    
        res.cookie('auth',token);
        res.send('ok');
    
    });
    
    app.use(function(req, res, next) {
    
      var token = req.cookies.auth;
    
      // decode token
      if (token) {
    
        jwt.verify(token, 'secret', function(err, token_data) {
          if (err) {
             return res.status(403).send('Error');
          } else {
            req.user_data = token_data;
            next();
          }
        });
    
      } else {
        return res.status(403).send('No token');
      }
    });
    

    Here you can find very nice article : https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

提交回复
热议问题