How safe is JWT?

in3pi2 picture in3pi2 · Mar 5, 2016 · Viewed 11.7k times · Source

I am learning about JWT for the security of my project, but I have a question. If I recieve the token correctly after I did the login, but someone else (hacker) in other place steals this specific token, can he access to my session? The server that use JWT authentication is able to detect this and protect me? How?

Answer

Sunil D. picture Sunil D. · Mar 5, 2016

Only the server should know the "secret" that is used to generate the JWT. If someone modifies the data contained in the JWT, the server will fail to decode it. So the server can trust any JWT that it can decode.

However, if a hacker got access to your computer, they could see the JWT that is stored in the browser and use it. This same threat exists w/cookies, so it's not really a flaw of the JWT.

One way to mitigate this threat is the expiration date of the JWT. For a banking app, your JWT might expire after a few minutes. For Facebook, it might expire after a few months. However, there's no bullet proof solution to this if someone gets access to your browser.

Another approach for hackers would be a "man in the middle" attack to intercept the network traffic between client and server and get at the cookie/JWT. The cookie/JWT should always be sent over HTTPS to prevent this.

IMPORTANT EDIT

Finally, to answer the question in your title, "How safe is JWT?": It depends on how you store the token. Local storage is not as secure as using cookies (reference) but cookies can be subject to CSRF or XSRF exploits.

This answer used to say JWT was safer than cookies, because cookies were subject to CSRF attacks. But storing JWT in local storage is not safe either. As a result, I'm no longer storing my JWT in local storage and using well known techniques to mitigate CSRF attacks.