MazMat
MazMat

Reputation: 2094

JsonWebToken has same value in requests done within 1 second

Im using jwt in my node application. My problem is that when I do multiple requests within a short time frame (around 1 second) the tokens that are generated within this time frame are identical.

This is how I generate the token:

const token = jwt.sign(loggedUser, config.auth.JWT_SECRET, {
                expiresIn: 7200
            });

Where JWT_SECRET is a const string

Is there a way to randomize JWT for EVERY request, no matter the time frame?

Upvotes: 1

Views: 872

Answers (1)

Emil Hotkowski
Emil Hotkowski

Reputation: 2343

Since JWT is a three part based string we should consider all of it parts and why it is indentical for your requests.

Header

Header often times consits of information like type of algorithm used for signing and the type of token which is JWT. Something like :

{
  "alg": "HS256",
  "typ": "JWT"
}

There's not much we can do here since we do not control it's value directly.

Signature

This part is an electronic signature created with private certificate/key to authenticate this token. Still not much of success in your case.

Payload

This part is what you can control. It claims information about entity you are authorizing. Payload is encoded with Base64 and put directly into JWT.

In your example you put loggedUser as your payload, and since it is exactly the same for all requests whole JWT stays the same.


Solution

The only way we can somehow influence how our JWT looks is payload.

Put some property called HASH into your loggedUser entity. Give it a random value, there are plenty ways to do it, for example UUID.

npm UUID is a library with over 20 milions weekly downloads, it should feed your needs for random hash

For more information about JWT itself and how it is build, please refer to JWT.IO


EDIT:

Instead of putting hash into loggedUser, you could also put it in jwtid which is an option in JWT.

Documentation states:

The jti (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The jti claim can be used to prevent the JWT from being replayed. The jti value is a case-sensitive string. Use of this claim is OPTIONAL.

Which seems to be exactly the way to go.

Upvotes: 1

Related Questions