0

After introducing JWT in my own application. I am facing some issues, might be I do it in wrong way. Please Suggest me the best way of implementation.

Technology Stack : (MERN) MongoDB Expressjs React Node.

After successfully login , I am creating a new JWT token by adding "user-id" in to it and return back to UI layer. At UI end I am storing that token in session storage. This token I am using for all further requests to the server. Before going to the controller I am checking Token in middleware for validtaion by using JWT verify. if successfully verified then next() else return an error with an invalid token.

Issue accurs now :

  1. Register with USER 1
  2. Login with USER 1
  3. After successfully login copy Token from session storage.
  4. Then Logout USER 1
  5. Register with USER 2
  6. Login with USER 2
  7. Paste in session storage Token of USER 1 into USER 2
  8. After refreshing a page USER 1 dashboard again instead of USER 2.

Any help or suggestions for following two points:

  • How should I manage user Session by JWT?
  • How should I manage API Authentication by JWT?
Anurag G
  • 272
  • 4
  • 16
  • I think, you are incorrect if you are thinking to use JWT token for user session management , see [this](https://stackoverflow.com/questions/43452896/authentication-jwt-usage-vs-session) esp the Answer by Carl von Blixen and link in that answer. – Sabir Khan Mar 26 '18 at 08:20

1 Answers1

2

You should either not store tokens in the browser session or at least delete it when logging out. The token contains all information about the user as well as the signature, that verifies the validity of the token. If you copy & store it, it is still valid. Logging out the user doesn't invalidate the token.

You should add an expiry to the token to make it valid only a short time, but you need to refresh it then in intervals before it gets invalid. The normal way to do this is to use a refresh token which has a longer interval and keeps the user from logging in again and again.

When the user logs out, you should stop re-issuing access tokens from the refresh token.

See https://jwt.io/introduction/ for further information about JWT.

JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27
  • Thanks, Joachim, In my case, I am deleting token on Logout. you said that Token expiry should me less and Make the regular call to reset until it gets expired. But there is a possibility to decode "exp" and "iat" value from the encoded token. – Anurag G Mar 24 '18 at 16:47
  • In fact, you can decode JWT tokens and read the properties like "exp". When using node.js, I've made best experiences with https://www.npmjs.com/package/jsonwebtoken – JSchirrmacher Mar 25 '18 at 08:37