nodejs – Json Web Token (JWT) en Node.js con express

Question:

I am working with the Json Web Token Javascript library, where I create the token with the function:

var token = jwt.sign({data: 'foobar', 'secret', { expiresIn: 60 * 60 });

To verify my token use, the function:

jwt.verify(token, 'shhhhh')

Which is what the library suggests, but I want it to be able to use some kind of certificate in the field where it receives the secret parameter. The library indicates that to generate the token with the certificate, it is done as follows:

var cert = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});

To verify the token using the certificate, read a file with a .pem extension, as follows:

var cert = fs.readFileSync('public.pem');  
   jwt.verify(token, cert, function(err, decoded) {
   console.log(decoded.foo) // bar
});

Now my question is, how do I generate those certificates that are requested in the token section? This to work with that certificate.

Answer:

Good

To generate the certificates locally, you can use openssl , which allows you to generate the required certificates with their respective extensions .key or .pem through the console, for my particular case I base myself on this tutorial to generate the certificates in windows.

Once the files are generated, the location of the file is saved in a variable, using the fs javascript module. Then it would be as follows:

var cert = fs.readFileSync('private.pem');
var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});

Now to validate the token it is done as follows:

var cert = fs.readFileSync('private.pem');  
   jwt.verify(token, cert, function(err, decoded) {
   console.log(decoded.foo) // bar
});

Then the token is generated and validated using the certificates.

Scroll to Top