What is the proper way to scale JWT horizonatally in nodejs. I am using RSA
to generate token. So each server would be able to decode tokens that were generated by itself. All the load balancing is stateless so there is no way to knowing which server generated the token. The current code that i am using is
helper['generateToken'] = (user)=>{
return new Promise((fullfill,reject)=>{
try{
var cert = fs.readFileSync('pvt.key');
var token = jwt.sign(user,process.env.SECRET);
fullfill(token);
}catch(ex){
reject(new Error("Your token could not be generated"));
}
});
}
The generateToken
function can run on any of the image and all of them have different private key. What could be the best way to scale with this.
Just a side note i am running there instances on docker swarm
so each server would be able to decode tokens that were generated by itself. All the load balancing is stateless so there is no way to knowing which server generated the token.
...and all of them have different private key.
Since a server could receive a token issued by the other server, and you can't distinguish the originator, you need to use the same signing key.
Alternatives
share the secret key between instances using a shared folder or database (and consequently protect access to it)
Use a central authentication microservice shared by all instances to sign tokens. If is being used a key pair, signature verification can be done locally en each instance. Problem: Also would need load balancing, but you can reduce the complexity of key sharing
Test all possible keys (not very nice): use an assymetric key pair (RSA) and verify the token signature with all available public keys to check if any is correct