oderfla oderfla - 4 years ago 111
Node.js Question

Where does json web token save the data?

I have a node-app using json web token:

var jwt = require('jsonwebtoken');

If a login succedes then this library creates a token this way:

var payload = {mydata: 'abcd'};
var token = jwt.sign(payload, 'secret', {
expiresIn: 28800
});

return {
success: true,
message: 'Success',
token: token
};


What I don't understand is where the token is stored on the server.
If the same user that received the token makes a call to a protected resource, then I have this line:

jwt.verify(token_sent_by_used, 'secret', function (err, res) {
if(!err){
res.json({result: 'success'});
}
else{
res.json({result: 'failure'});
}
}


The reason why Im asking this is that I could not find explanation on how to handle jwt when running an application across several machines.
If my backend is put on different machines and user makes the requests to a load balancer, then the request can hit any machine.
If jwt writes token data on the file system, then I guess there can be issue if the request hits a machine that was not the one that created the token.
When using session, you can set the session handler to database. How do you solve this with jwt?

****EDIT****

Ok, let's take an eaxmple.
I have a node app that is running on machine .10 and the same node app also running on machine .11. Two different machines.

I go to machine .10 and send username password. App on machine .10 checks username/password. They are ok. Machine .10 creates a jwt token and send it to me.

I now make a curl request (to a resource that requires a valid jwt-token) to machine .11 and send the jwt-token that machine .10 had preciously sent to me. Machine .11 will not complain about the jtw-token? It will be considered valid? Even if it was not created on machine .11?

Answer Source

Both servers in your question must be able to verify the token - they must be able to generate the signature. If both servers share the same secret key (used to originally generate the token's signature on .10), then both would be able to verify its contents.

In the screenshot below, both the red part and the purple part are plaintext - anyone can read and modify them. However, the blue part is special - it can only be generated on the server, from the red and purple parts, using the secret key. So, it guarantees that the red and purple parts were not tampered with.

enter image description here

So, when you send the whole JTW back to a server, it can use the secret key to generate the blue part and compare it with the blue part that you're sending. If they don't match, then someone (illegitimately) changed the red or purple parts, so authentication is denied.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download