Search code examples
mongodbauthenticationtokenrefresh-token

Is my mongodb the right place to store my refresh tokens?


I am trying to implement a JWT Token/RefreshToken Auth Backend server. There is a lot of resources out there, and it has been really helpful, but somehow nothings tell me how/where to save my refresh tokens.

I am working so far with a mongo db to store the information of my app. Is it safe to store my refresh token in the same db? Is there any more secured, or more performant solution I am not seeing?


Solution

  • Ideally, you should not even have to store your access or refresh tokens in any database. One of the main motivations behind the JWT pattern was to eliminate the need to persist session state in the server. Instead, the session state is maintained in the JWT tokens themselves. To better understand this, let's examine the simplest sequence of events when the server receives an incoming access token.

    When the server receives an incoming access token, the first thing it will do is to check the claims section of that token. One of the claims, typically called exp, contains the token expiry date. Any access attempt in the server which uses an expired token will be rejected. The server also can ensure that the incoming JWT has not been tampered with by computing the checksum. Any token whose expiry or other claims have been doctored would fail the checksum test.

    The main point here is that ideally a JWT acts as a standalone passport of sorts. There should not be a need to store it in a database for comparison or lookup. Sometimes, there might be a need to blacklist certain JWT. In this case, the need might arise to store them on the server. But here we would still not use a database, but rather a lightweight cache with really fast access times. And, we would only be storing a very small number of blacklisted JWT, so the server would still remain largely stateless.