Session vs Token Based Authentication

Why do we need session or token for authentication?

HTTP is stateless. All the requests are stateless. However, there are situations where we would like our states to be remembered. For example, in a on-line shop, after we put bananas in a shopping cart, we don’t want our bananas to disappear when we go to another page to buy apples. ie. we want our purchase state to be remembered while we navigate through the on-line shop!

To overcome the stateless nature of HTTP requests, we could use either a session or a token.

Session Based Authentication

Session Based Authentication flow

Token Based Authentication

Token Based Authentication flow

The biggest difference here is that the user’s state is not stored on the server, as the state is stored inside the token on the client side instead. Most of the modern web applications use JWT for authentication for reasons including scalability and mobile device authentication.

Node Modules for JWT

{
method: "GET",
headers:{
"Authorization": "Bearer ${JWT_TOKEN}"
}
}

Middleware, express-jwt, can be used to validate the JWT token by comparing the secret.

Scalability

Token based authentication: There is no issue with scaling because token is stored on the client side.

Multiple Device

Token based authentication: There is no issue with cookies as the JWT is included in the request header.

Token Based Authentication using JWT is the more recommended method in modern web apps. One drawback with JWT is that the size of JWT is much bigger comparing with the session id stored in cookie because JWT contains more user information. Care must be taken to ensure only the necessary information is included in JWT and sensitive information should be omitted to prevent XSS security attacks.

Reference

A software engineer passionate about learning and growth

A software engineer passionate about learning and growth