DEV Community

Cover image for Day 49 of #100DaysOfCode: Review session-based authentication and token-based authentication (same origin)
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on • Updated on

Day 49 of #100DaysOfCode: Review session-based authentication and token-based authentication (same origin)

Session-based authentication (sessions + cookies)

Procedures

  1. The browser send the request with the user name and the password
  2. The server verifies the credential with the database
  3. The server generates the session for the user
  4. The server set the cookie with the session ID
  5. The browser send the request with the session ID
  6. The server verifies the session with the database
  7. The server destroy the session and clear the cookie when the user log outs

Alt Text

Features

  • Used for: SSR web apps, frameworks (Spring, Rails), scripting langs (PHP)
  • Stateful in the server-side: session is stored server-side and linked by session ID

Pros

  • session IDs are no meaningful data

Cons

  • server must store each user session in memory
  • horizontal scaling is challenging: need sticky sessions with load balancing

Token-based login (stateful JWT: JWT + cookies)

I think that it's safer to use JWT by Double tokens policy: HttpOnly Cookie + CSRF token which is called stateful JWT. It can keep several
advantages for storing JWT in cookies.

  1. HttpOnly: avoid being manipulated by JavaScript (XSS)
  2. Secure: cookie can only be sent to the server by HTTPS

Procedures

  1. The browser send the request with the user name and the password
  2. The server verifies the credential with the database
  3. The server generates the JWT for the user
  4. The server set the cookie(HttpOnly, Secure) with the JWT
  5. The browser send the request with the JWT
  6. The server verifies the JWT

Alt Text

Features

  • Used for: SPA (CSR), web APIs, mobile maps
  • Stateless: session is not stored server-side
  • Self-contained: carries all required user data in the payload. Reduces databases lookup

Pros

  • FE and BE architecture is decoupled, can be used with mobile apps

Cons

  • The server still has to maintain a blacklist of revoked tokens
  • When scaling, the secret must be shared between servers

That's it!

Articles

There are some of my articles and released projects. Feel free to check if you like!

References

Top comments (0)