Session Authentication
A session is a small file, most likely in JSON format, that stores information about the user, such
as a unique ID, time of login and expirations, and so on.
1. The user sends a login request to the server.
2. The server authenticates the login request, sends a session to the database, and returns a
cookie containing the session ID to the user.
3. The server checks in the database for the ID found in the cookie, if the ID is found it sends
the requested pages to the user.
4. Now, the user sends new requests (with a cookie).
Pros/Cons
Since sessions are stored on the server, its administrators are in power over them. For
example, if a security team suspects an account is compromised, they can immediately
invalidate the session ID, so that the user is immediately logged out. On the other hand, since
a session is stored on the server, the server is in charge of looking up the session ID that the
user sends. This can cause scalability problems.
Cookies may be exposed to cross-site request forgery attacks. The attacker may mislead the
user to a hostile website, where some JS scripts may exploit cookies to send malicious
requests to the server. Another vulnerability regards the chances of a man-in-the-middle attack,
where an attacker can intercept the session ID and perform harmful requests to the server.
Token-Based Authentication
A token is an authorization file that cannot be tampered with. It is generated by the server using
a secret key, sent to and stored by the user in their local storage.
1. The user sends a login request to the server.
2. The server authorizes the login and sends a token to the user.
3. The server checks the token is valid or not, if the token is valid it sends the requested pages
to the user.
4. Now, the user sends a new request(with a token).
Pros/Cons
Tokens can be useful when the user wants to reduce the number of times they must send their
credential. In the case of server-to-server connections, using credentials becomes difficult, and
tokens overcome this problem. Moreover, servers that use tokens can improve their
performances, because they do not need to continuously look through all the session details to
authorize the user’s requests.
However, the authentication details are stored on the client, so the server cannot perform
certain security operations as in the session method. As written above, the server does not
authenticate the user, so linking a token to its user can be more difficult. If a hypothetical
attacker manages to get a valid token, they may have unlimited access to the server databases.
If the server generates keys using older algorithms, these keys can be breached.