About Lesson
Another issue -> Issue arises when a user has to navigate across multiple pages. Calling the login service each time to authenticate the user can be inefficient and put a heavy load on the login service, leading to increased time and processing demands.
Solution -> To address this, we can take inspiration from real-life scenarios. Imagine visiting an adventure park where various activities require additional payment beyond the entry ticket. Instead of authenticating for every paid service, which could be time-consuming, visitors are given a wristband upon entry. This wristband serves as authentication for all related paid services throughout the day. Similarly, in our system, we can generate a unique token at the time of login with an expiry time. This token can then be used for authentication across various pages or services, reducing the need for repeated authentication checks. Here we are still hitting db bultiple times but we avoided hashing process on every auth.
Authenticating Users Using Tokens:
First, the user logs in using their credentials. The request is then sent to a service, which verifies the credentials with the database. If the verification is successful, the service generates a token, saves it in the database, and includes it in the response to the user’s request.
Now, the question arises:
Do we need to store the token in the database, or can we store it in a cache and revalidate requests? Storing it in a cache poses a challenge if we’re using multiple servers because each server may have its own cache. Therefore, it’s necessary to store the token in the database.
The next time the user visits another page, they send this token along with their request. We then check if the token is present and valid. If it is, we respond with success and allow the user to access the page. Think of the token as a temporary password here.