Aruna Aruna - 1 month ago 22
Node.js Question

How to use a generated nonce in NodeJS and do validation without a database call?

I am generating a nonce to validate the wizard steps to secure it one after another.

I know how to create the nonce in nodejs and store the same in database to make sure it can be used once.

But I was wondering, whether there is an idea to generate and validate a nonce as above like to be used only once and if possible, can be used within a time limit (expiry) without storing the same in the database but simply returning it to the client in one wizard step and validate the same on the next step.

I normally use the below method to generate the nonce, normalize it and store it in a mongodb with a time to expire so that mongodb will delete it after a particular time if its not been used.

var crypto = require('crypto');

crypto.randomBytes(32, function (err, bytes) {
if (err) {
next(err);
} else {
next(null, normalize(bytes));
}
});


Please suggest if any good/optimized way of generating the nonce than this and a possibility to take care of the one time usage and expiry without a database call.

Answer

It's always better practise to have a database to store and validate the nonce. To restrict with time, either you can use a mongodb with expiry or you can generate the timestamp, then generate a hmac with timestamp, nonce & private key. Then send the nonce, timestamp & hmac to the client. This way you can secure the timestamp as well you can restrict the nonce with particular time if your database is not supporting the document expiry as mongodb. Hope it explains.