Json Web Token (JWT) in Node.js with express

5

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

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

To verify my usage token, the function:

jwt.verify(token, 'shhhhh')

What is suggested by the library, but I want that in the field where you receive the secret parameter, you can use some kind of certificate. The library indicates that in order to generate the token with the certificate, it is done in the following way:

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 extension .pem , 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.

    
asked by j-j suarez 13.07.2018 в 21:15
source

1 answer

5

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 module fs of javascript . Then it would look like this:

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

Now to validate the token 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.

    
answered by 17.07.2018 в 19:27