The internet primarily communicates using the HTTP(S) protocol. However, this protocol is stateless (meaning it does not store states). Now, imagine that the internet is stateless—how does it know whether we are authenticated or not?
Systems classify users in two categories: authenticated users and unauthenticated users. Authenticated users have logged in to the system, and because the system has information about these users, it recognizes them.
Unauthenticated users, on the other hand, are users who haven't logged in. The system doesn’t have any information about them, and some actions may be restricted for them (since they are considered "anonymous").
But, given that the HTTP(S) protocol is stateless, how does the system know whether the user has logged in or not?
Session Authentication
When a user logs into the system using a username/phone and password, the system creates a unique session ID specifically for that user. This session ID is stored both on the server's database and in the user's browser. So, each time the user sends a request to the server, they send their session ID. If the server recognizes the session ID, it means the server knows the user is authenticated. If no such session ID exists, the system automatically logs out the user. If the user logs out, the server deletes the session ID associated with that user from its records.
Drawbacks:
- Resource consumption: If a user logs in from multiple devices at the same time, a separate session ID is created for each one. Now, imagine 1 billion users logging in from 3 devices each.
- Temporary: Session IDs are temporary. If the user hasn’t logged in for a while, the system deletes the session, and when the user returns, they will see that they’ve been logged out and need to log in again.
- And there are other reasons you can explore...
Cookie Authentication
When a user logs into the system, the server sends a special cookie to the user's browser (this is not the "cookie" you might be thinking of). A cookie is a small file (up to 4 KB in size) that is stored in the browser.
- Every HTTP request is sent with the cookie, which increases the overall traffic size.
- It is not entirely secure; cookies are vulnerable to CSRF (Cross-Site Request Forgery) attacks.
- Cookies can store up to 4 KB of data. If you need more storage, this may not be the solution for you.
In the second part of this post, I will write about Tokens, JWT, and Passwordless authentication. Stay tuned by following my channel!