Session vs Token based Authentication

Session Cookie

  • They are stateful
  • They contain data that the server sends to the browser for temporary use
  • The authentication data inside a cookie is stored on both the client and server.
  • The server keeps track of active sessions in a database, while the browser holds the identifier to the active session.
  • little space needed
  • generally a SessionID is stored in a cookie
  • Disadvantages:
    • vulnerable to XSS, hence always send cookie with HttpOnly flag
    • tied to one server, problems in scaling, need to use shared DB
    • generally not used in mobile apps and SPAs
  • Ensure Secure flag is set to send over HTTPS

JWT Tokens

  • stateless in nature
  • server doesn’t need to keep a record of the token
  • Each token is self-contained, holding the information needed for verification and identification on the server.
  • Cross Platform
  • Suitable for API server
  • Can be stored anywhere like localStorage, SessionStorage, Cookie etc.
  • Disadvantages:
    • Cannot be revoked
    • more space needed
    • Can be Stale if user info changed
  •  Lifespan of a JWT should be kept short to limit