Integrating jsonwebtoken library in nodejs application
Among other numerous jwt advantages, I prefer one more crucial jwt advantage of generating and validating it before hand and avoid the need to store it in database. Storing it in database also can be helpful but that is later topic of discussion. We store credentials of user in database using Bcrypt password hashing algorith. There after use jsonwebtoken to establish the identity of the user for futures requests. We shall generate cryptographics keys to sign and verify the token which we wish to give to user for further requests.
Please remember that is not going into any detail of cryptographic keys, we will generate keys and get started with it in nodejs.
Generate Keys
1ssh-keygen -t rsa -b 2048 -m PEM -f private.key
2openssl rsa -in private.key -pubout -outform PEM -out public.key.pub
This generates private/public key and for other details execute ssh-keygen --help
Your should get output something like for private.key
1-----BEGIN RSA PRIVATE KEY-----
2Proc-Type: 4,ENCRYPTED
3DEK-Info: AES-128-CBC,D....A5B13DAEC97849331
4
5DBsZYdcw5nXKwZDwuMCyk+1nA2crZQSeyomOqbSFBAQfqeWThOU2VcP96OmjSrCY
6FSaqJCsgXyA/ey7ydMqdIG04Lwao5YmW5AvVj1YNmOZghGMjltjHHqR86ycrdAgz
7VDGc----
8-----END RSA PRIVATE KEY-----
And for public.key
1-----BEGIN PUBLIC KEY-----
2....+du4KkrTrc6J4p0n8pYSqSSTedE+VBaQbQWsh
3piIGrAE7wr4g7khGCV5nmsq87lujswzYJYNf2GKIeYkPyWRyhCgcfxvacAHvxLOG
4dllcm43ikXSqdBt4I3BKgSSADCB2zUwBIB5gWO6SeexSq2J2Z1eJg/wTGaG/O5Cg
5L8ma7j8A+C44XpvUlBLZ...
6-----END PUBLIC KEY-----
Integating with jsownwebtoken
install jsonwebtoken
for check for latest version here
1npm install jsonwebtoken
Generating token
Simply import jwt library in you authentication controller
1const jwt = require('jsonwebtoken')
Then import private and public key using fs
package
1var privateKey = fs.readFileSync('./path/to/private.key', 'utf8');
2var publicKey = fs.readFileSync('./keys/public.key', 'utf8');
In login controller, once you have verified user credentials using bcrypt#compareSync
and getting the user details from database, let's generate token using the following code:
1const userParams = {id: user._id, username: user.username, name: user.name};
2const keyParams = {key: privateKey, passphrase: 'qawsed'};
3const signOptions = {algorithm: 'RS256', expiresIn: '7 days'};
4const token = await jwt.sign(userParams, keyParams, signOptions);
Steps incolved in generating token:
- userParams is the payload we will encode inside token
- keyParams is privateKey recall from loading it from file using fs library
- sign options specifies extra sign option during encoding. There are few more sign options which we can use but are not mandatory more here.
RS256
public key does not needs to be kept secret so we can allow it to share this to multiple servers or clients who can authenticate the user against this token also called as access_token
. Sometime you might see the the server exposing public key using path called as JsonWebKeySet For more details in nodejs check this article from auth0 blog
1https://domain/.well-known/jwks.json
Verifying token
once we receive token as Bearer e.....
in header field Authorization
, we verify token using code given below:
1let verify = await jwt.verify(authorization[1], publicKey, {algorithms: ["RS256"]});
If the call return success we proceed furter with continuing the api otherwise return with unauthorized status to the caller.
Decode
It is possible to decode token without verifying first. To decode we simple use:
1jwt.decode(received_token_in_header);
This gives us the decoded payload we passed to jwt.sign(...)
method.
Thank you for reading.
comments powered by Disqus