Is it necessary to refresh tokens every request?

John picture John · May 9, 2017 · Viewed 14.6k times · Source

I'm here because I wasn't satisfied with what I found on google.

I am generally building SPA's, so for me the process was simple: At succesful login generate a jwt and use it for every request I make from the client.

Someone told me that I should refresh that token and send back a new one for every request I make. Does this make sense for me to do? I mean, if someone is trying to hack me, sniffing the requests will give the hacker the same tokens I receive, so what's the catch?

I mean, what if I launch a request before another one is finished? Teoretically I would send the same token twice and one of the requests will be rejected.

How is this correctly handled? I'm sure there is more to this than what I could think myself.

Answer

Marko Vodopija picture Marko Vodopija · May 10, 2017

It is a compromise between security and convenience.

No, you don't need to refresh the token on each request. But you definitely want your JWTs to expire at some point. This is to protect you from JWT theft where malicious user could use stolen access token to gain access to target resource indefinitely.

Here is what you can do to handle token expiration:

  1. Implement a refresh token flow. You will issue an access JWT and a refresh JWT when authenticating. Once access JWT has expired you will use refresh JWT to obtain new access JWT.
  2. Implement sliding expiration. After the half of the JWT validity time has expired you would issue a new JWT. An example of it can be found here. I would recommend to include a deadline to when a token can be expired. For example, initial token validity is for 20 minutes and deadline is 8 hours. After 8 hours of sliding expiration you will stop issuing new tokens.