๐ฆ๐๐ฎ๐๐ฒ๐ณ๐๐น ๐ฆ๐ฒ๐๐๐ถ๐ผ๐ป๐: ๐ง๐ต๐ฒ ๐ฅ๐ฒ๐ฎ๐น ๐๐ผ๐น๐ฑ ๐ฆ๐๐ฎ๐ป๐ฑ๐ฎ๐ฟ๐ฑ ๐ถ๐ป ๐ช๐ฒ๐ฏ ๐๐ฒ๐๐ฒ๐น๐ผ๐ฝ๐บ๐ฒ๐ป๐
Why do the most secure apps still use traditional sessions?
Even with the rise of stateless APIs and JWTs, session-based authentication remains a robust choice. It gives you total control over user access.
The web is stateless by nature. Each HTTP request is independent. Sessions create a bridge of trust. They allow the server to remember who you are without compromising security.
Think of a gym membership. You show a card with a unique barcode. The gym scans it and checks a central database to see if your membership is active.
In this analogy:
- The gym is the web server.
- Your membership card is the session_id in a cookie.
- The central database is the Session Store.
How the flow works:
- You log in with your credentials.
- The server validates you and creates a random session_id.
- The server saves this ID in a Session Store.
- The server sends the ID to your browser via a Set-Cookie header.
- Your browser automatically sends this cookie back with every future request.
- The server looks up the ID to confirm your identity.
Where to store sessions:
- Local Memory: Fast, but bad for production. If the server restarts, everyone logs out. It also fails when you use multiple servers.
- Relational Databases: Very persistent, but slow. Checking a database on every single request creates a bottleneck.
- Redis: The best choice. It is an external, ultra-fast memory store. Multiple servers can connect to one Redis cluster, allowing your app to scale.
Security is non-negotiable. You must use these cookie flags:
- HttpOnly: Prevents JavaScript from reading the cookie. This stops XSS attacks.
- Secure: Ensures the cookie only travels over HTTPS. This stops network interception.
- SameSite=Lax: Protects against CSRF attacks by controlling how cookies are sent during cross-site requests.
The biggest advantage is instant revocation. If a user reports a stolen account, you can delete their session from your store immediately. The next request they make will fail. This is a major security edge over JWTs.
Final checklist for production:
- Use a cryptographically secure random generator for IDs.
- Ensure IDs are at least 128 bits long.
- Set an idle timeout for inactivity.
- Set an absolute timeout to force re-login after a set period.
- Always use Redis or a similar distributed store for scaling.
Source: https://dev.to/jcmexdev/sesiones-stateful-el-verdadero-estandar-de-oro-en-la-web-hgj