Friday 19 May 2017

How to add user's information on a JWT?

I'am using JWT to authenticate users but I want also to add some informations to the token like the username.

This is how I create the tokens after I've authenticated the user :

app.post('/authenticate', function(req, res){
    User.findOne({
      username: req.body.username
    }, function(err, user){

      if(!user){
        console.log('Authentication failed. User not found');
      }
      else if(user){
        if(user.password != req.body.password){
          console.log('Authentication failed. Wrong password');
        }
        else{

          var token = jwt.sign(user, app.get('secretWord'), {
            expiresIn : 10800,
          });

          res.send({
            token: token
          });
        }
      }
    })
  });

How can I associate a username to the token? I tried :

var token = jwt.sign(user, app.get('secretWord'), {
                expiresIn : 10800,
                username : user.username
              });

But that throws an error : "ValidationError: "username" is not allowed.



via Mit

No comments:

Post a Comment