how to generate API Keys for the user of your nodejs application on the basis of different parameters of the user in the database for giving access to our server endpoints.
how to generate API Keys for the user of your nodejs application on the basis of different parameters of the user in the database for giving access to our server endpoints.
When we talk about generating API keys, I always preferred to use uuid or crypto library. To securing your keys, encrypt the keys before saving them into the database. To encrypt the keys, you can use Google's Key Management Service (KMS) and JWT but I will prefer to use KMS.
You can use randomUUID which is part of node's crypto module. Then you can take the generated uuid, hash it using bcrypt and store it in db.
const saltRounds = 10;
const token = crypto.randomUUID();
const hashedToken = await bcrypt.hash(token, saltRounds);
And in subsequent requests, you can validate it like so:
const token = req.body.token // this is an example
bcrypt.compare(token, hashedToken, function(err, result) {
// result == true
});
You can also store the creation date and use it to invalidate tokens if they've passed certain time.
Hashing the token protects it in case a malicious use was able to access the database. Combined with time and scope restrictions you have a pretty solid solution.
You can use different parameters to generate an API key and store it in the database for different users.
data = req.body.email+req.body.username;
let apiKey = Buffer.from(data).toString('base64')
Update your database column of that user with this API Key which the user can use to access to your server endpoints.