Session-based authentication (sessions + cookies)
Procedures
- The browser send the request with the user name and the password
- The server verifies the credential with the database
- The server generates the session for the user
- The server set the cookie with the session ID
- The browser send the request with the session ID
- The server verifies the session with the database
- The server destroy the session and clear the cookie when the user log outs
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.
- HttpOnly: avoid being manipulated by JavaScript (XSS)
- Secure: cookie can only be sent to the server by HTTPS
Procedures
- The browser send the request with the user name and the password
- The server verifies the credential with the database
- The server generates the JWT for the user
- The server set the cookie(HttpOnly, Secure) with the JWT
- The browser send the request with the JWT
- The server verifies the JWT
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!
- My blog-posts for software developing
- Facebook page
- My web resume
- Twitter bot
- Side project - Daily Learning
Top comments (0)