Session and token authentication

Session and token authentication methods are used by the server to verify the client request is authenticated or not.

Session Authentication

Session-based authentication is an example of stateful authentication, which involves storing user authentication data on the server. With this method, when a user logs into a website, the server creates a small file that stores user information such as a unique session ID, login time, expiration time, and other relevant data. This file is stored in the database or in-memory cache. This session ID is then sent back to the client and stored in the client’s browser as a cookie. For subsequent requests, this cookie is passed back to the server. This allows the server to verify the session ID and provide a response based on the current state.

This method is easy to use, as cookies are natively supported by browsers, so no additional JavaScript is needed. But when the application grows decoupling the frontend from the backend becomes essential. Session-based authentication can be limiting in this regard.

Token Authentication

Instead of relying on server-side sessions, token-based authentication uses tokens and it is an example of stateless authentication. When user log in, the server create a token (usually a JSON Web Token, or JWT) using a secret key and sent to the user. For subsequent requests, user will send this token along with request and server will verify if the token is valid or not.

This method gives more scalability and stateless for the apps, but the server does not authenticate the user, so linking a token to its user can be more difficult. Also in any chance an attacker got acess to the token, they will get access to the server.

References

LogRocket, Authfear, criipto.

Read More