Search code examples
node.jsjwtaccess-token

Signing for a jwt web token returns null - nodejs


The jwt signing fails and returns a null for token. Here is my implementation:

var jwt = require('jsonwebtoken');

var jwt_session_secret = "rnwR_apwvkWjdHovcmmQuoDwLR8av9oFjbJm2KhS7oEX9aSiBu9e96jxCDM9vj5_x8OlCCEiXwIGkagL-KDgnDsulc2e0QU5qYN75lzomrc4P9gqgGXB7HVfpaBcKgW3oLsXRBWAoFT5ICsOSwT-70hdQtJfE7a3NK6j3jmxcSE";

var payload = { ud: 23 };
var exp = Math.floor((new Date(+new Date + 12096e5).getTime())/1000);
var opts = { issuer: 'gateway', expiresIn: exp };

console.log(payload);

jwt.sign( payload, jwt_session_secret, opts, function(token) {

    console.log("token = " + token);

        jwt.verify(token, jwt_session_secret, function(err, decoded) {
            if(err) {
                console.log("Error failed: " + err);
                return;
            }
            console.log("decoded");
            console.log(decoded);
            });
        });

The code looks good to me but not sure if im missing something here. This is the output:

{ ud: 23 } token = null Error failed: JsonWebTokenError: jwt must be provided


Solution

  • You need to accept two parameters in the callback, err and token as follow:

    jwt.sign( payload, jwt_session_secret, opts, function(err, token) {