Search code examples
phpsessionauthenticationjwttoken

How Jwt token really works in a login system?


I am struggle for a stable answer for this question and not getting any. My doubts are

  1. do we need to store the user name and password in the token and if yes then how that i.e where this data are getting store in the payload part is it in the sub?
  2. do we need to store the token in the DB while registering
  3. Does Jwt token are unique for same set of data ( I think no cause of the different time)
  4. how to verify user? that is first creating a token of the data from the inputs then creating token and verifying it with the token in the DB?
  5. How to logout?
  6. Is it better than session

Solution

  • 1) You need to store some user identification in JWT. Usually it makes sense to list her granted rights verified during authentication and something like display name. Definitely do not store password.

    2) No, token is not stored in the database. Tokens are short lived and need to be re-issued every few minutes transparently to user.

    3) Every time JWT is re-issued it is unique because one of the things encoded in it is the timestamp for when it expires.

    4) First token is created during authentication. Then each request validates the token by decoding it using the private key you used to encode it. If the token is expiring soon you issue the new one using the same data + updated expiration timestamp.

    5) Log out is now a front end's job. You need to stop sending requests with the token. Perhaps delete the cookie if you are sending JWT as a cookie.

    6) This is better than using session because it is stateless. First obvious win is that you no longer need to store session info in database/maintain client ip address affinity if you are running a cluster of multiple web servers.