简体   繁体   中英

Using a config file for JWT secret in Node.js

I am learning Node.js, and while implementing JWT I want to put a separate config.js file to set the secret to generate and verify tokens, but I am having trouble with this.

First I create the config file as follows:

// JWT config
module.exports.jwt_secret = 'mysecret';

Then I require it at the API endpoint as:

const jwt_secret = require('../../../../../config');

And finally, I try to use it as follows:

jwt.verify(token, (jwt_secret), function(err, decoded) { ... }

But it does not work, so I tried a console.log with the jwt_secret, and I get this:

{ jwt_secret: 'mysecret' }

I checked code and searched here at Stack Overflow but I do not see how to solve this. I know probably it is pretty obvious but as I said I am quite new at programming and I am learning.

Thank you in advance.

Taking a quick look at the node-jsonwebtoken api, verify seems to expect a string as the second argument. The way that you've set up your export and require means that your variable jwt_secret is the entire exports object from your config module, not the string. Try changing it to

jwt.verify(token, jwt_secret.jwt_secret, function(err, decoded) { ... }

and if that works, you may want to modify your require statement to something like

const config = require('some/path/config');

and then use config.jwt_secret as the argument. That's just style though, do what works for your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM