Search code examples
javascriptjwttoken

Javascript Tokens, JWT and numbers when decoded


I am totally new on using JWT and tokens; I just tried to do this:

console.log("logged " + data);  

//prints { _id: 5a82ee98e918b22e83d6c3e0,
//username: 'test2',
//name: 'test',
//surname: '2',
//password: '...'
//[etc]
 //}

console.log("logged _id " + data._id);

//prints 5a82ee98e918b22e83d6c3e0

var token = jwt.sign(data._id, secret, {
                    expiresIn: "24h" // expires in 24 hours
                });
console.log("saved token " + token);

//prints the token in style eyJhbGciOi[...].eyJfYnNvbn[...].usoLRz-[...]


console.log("decoded: " + JSON.stringify( jwt.decode(token) ) )


//prints the token in this way:
//{"_bsontype":"ObjectID","id":{"type":"Buffer","data":[90,130,238,152,233,24,178,46,131,214,195,224]},"iat":1519502719,"exp":1519589119}
  1. why it does not prints the id number in plain text?
  2. how can i get the id number i put in the token?

UPDATE: I am in a login function; data is the answer after login, and it contains the user logged in; i have

var login = function(req, res) { 
    passport.authenticate('local', function(err, data, info) { 
        if (err) { console.log(err); 
    } 
    console.log("data in auth " + data);
    if (!data) { 
        return res.status(404); 
    } 
    req.logIn(data, function(err) { 
        if (err) { 
            console.log("err " + err); 
        } 
        console.log("logged " + data);
        console.log("logged _id " + data._id);
        var token = jwt.sign[continues on top]
    [...]
}

Solution

  • Solved. Problem was that i put in the token data._id directly as string; as this link says, token payload must be built this way:

    {
        "_id" : data._id
    }
    

    so I do NOT have to do this:

    console.log("logged _id " + data._id);
    
    //WRONG
    var token = jwt.sign( data._id, secret, {
        expiresIn: "24h" 
    });
    

    but I do have to do THIS WAY:

    console.log("logged _id " + data._id);
    var myId = {
        "_id" : data._id
    }
    
    var token = jwt.sign( myId, secret, {
        expiresIn: "24h" 
    });
    

    so now if I use

    let decodeddata = jwt.decode(token,secret);
    console.log("decoded: " + JSON.stringify(decodeddata,null,4) )
    

    then THIS WORKS. Thanks to all for helping me finding the issue!