Authentication methods secure the communication between a server and a client. They're also used to make a server trust a request sent by an authorized user over the internet. In this Answer, we'll compare the session-based and token-based authentication.
A session is a small file that stores the information about the user (user ID, login and expiration time, and more). The session is created and stored in the server when we log in.
Here's the basic flow of session-based authentication:
The user (browser) sends a request to the server. The request contains the credentials of the user and the info it is requesting.
The web server authenticates the user. It creates a session, stores the information in a database, and returns a sessionId
to the user.
This sessionId
is stored in browser cookies. The next time the user requests, it sends the cookies in the HTTP header.
The web server looks at its sessionId
and checks if it has any information. sessionId
.
If the sessionId
is valid, the web server authenticates the user and returns the requested information.
A token is an authorization file that can store all the user information in an encrypted format. This token can be stored on the client-side. The user sends the token to the server with every new request so that the server can verify its signature and authorize the requests.
Here's the basic flow of token-based authentication:
The client sends a request to the server with their credentials.
The application validates the credentials and generates a secure, signed token for the client.
The token is sent back to the client and stored there.
When the client needs to access something new on the server, it sends the token through the HTTP header.
The server decodes and verifies the attached token. If it is valid, the server sends a response to the client.
The token is destroyed when the client logs out.
Now, let's compare session-based and token-based authentication:
Criteria | Session Authentication | Token Authentication |
Suitable for | User-to-server connections | Server-to-server connections |
Connection store | Server | User |
Which one is more secure? | Less secure | More secure |
What does the client send to have their requests authorized? | Cookie | Token |
Vulnerabilities | Prone to MITM, CSRF | Prone to MITM, token steal, breaches of the secret key |
The main difference between the session and token authentication is that the authentication details are stored on the server side in session authentication and on the user side in token authentication. Token authentication is more secure than session authentication because a token cannot be tampered with. Both methods have inherent vulnerabilities which can be resolved. So, it is on the developer to decide as to which method he wants to adopt based on his needs.
Free Resources