Is JWT safe if someone knows the secret? If not, how can you make JWT secure?

I recently read a lot of articles talking about how JWT can be used for authentication to improve performance by not saving any session related data. Based on my understanding, it signs the data (usually user_id) with a secret to generate a JWT token. Then each client request sends the token. The server just check whether the signature can be verified and trust what's stored in the payload of the JWT.

My concern is that if someone knows your secret, he can easily create a JWT token himself and pretend to be any user in the system. One simple case is that anyone who can see the source code can easily do that. (eg: internal members)

How do you prevent it from happening? One thing I can think of is to use a randomly generated secret at each sever restart. (this may still not be secure if you sever runs a long time without changing the secret)

1 answer

  • answered 2018-01-13 17:13 Cooper Campbell

    Many people seem to have issues with regards to the security of a JWT for this reason, and the inability to white-list/black-list people without losing the benefits from using a JWT. In regards to generating a new secret on each server restart, keep in mind that each time you change the secret, you essentially 'logout' every user who currently is logged in, or for whatever other purpose you are using it for. I think common practice is to just make sure the secret remains just that, a secret. A long, randomly generated string that is kept in a file that extremely few people have access is the best way to prevent a current secret from escaping, as far as I know.

    Another thing to keep in mind is that the data is in no way hidden from anyone within the JWT. Anyone can see what you have stored so don't store any sensitive data in there. You probably already knew that from your reading, but it is an extremely easy and fatal mistake to accidentally leave sensitive data in the body of the JWT.