Where should I store jwt token for authentication on server side
Asked Answered
F

2

7

In my nodejs app, I am using jwt tokens for authentication. Now after the token gets created , it is going to be verified. For that, it should be stored somewhere for verification purpose. So, my question is, should I store it in separate database schema against concerned userid or should I store it somewhere else?

Flapper answered 23/3, 2017 at 5:38 Comment(0)
I
16

JWTs do not need to be stored on the server side. When you create a JWT, you encrypt it using a secret - think of this as the "password." Then you send it to the client where it can be stored.

When the client makes a request, it sends the JWT along with it. On the server side, you can the decrypt it using the same secret. If the secret does not work, you know it is an invalid JWT.

For obvious reasons, your JWT secret should be kept secret! The best way to do this is to store it as an environment variable.

Irrelievable answered 23/3, 2017 at 5:43 Comment(3)
Suppose, I have multiple request from client side, So different client will have different jwt tokens, So as per your say, I should only store secret which was used to generate all these tokens in environment variable. or did I interpret it wrong?Flapper
Correct. As an example, when a user logs in you may want to store their ID and email address in the JWT. That gets encrypted with your secret. Whenever that user makes a request, you decrypt it with the same secret which yields their ID and email address so you know who made the request. Since you are the only one that knows secret, you can use the same secret for every JWT.Irrelievable
just to be accurate, you don't necessarily "encrypt it", you sign it.Imbalance
F
4

There isn't any need to store JWTs on the server side. That is the whole point as JWTs enable "asynchronous" token verification on the server side.

Here is a series of steps involved, putting in a simplified way:

1- Server creates a JWT using a secret (maintaining this secret across server nodes, if they are more than one, is important as the client can connect to any one of them servers with the given JWT)

2- Client stores this JWT and furnishes it in the subsequent requests to the server

3- The server (or any given server node in the farm) verifies the incoming JWT based on the secret that was used earlier to encrypt/create a JWT

HTH

Flagstaff answered 23/3, 2017 at 6:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.