I have a question about user authentication in web applications. I learned that typically, when a user first logs in, the server validates the credentials and then generates a token. This token is saved in cookies or local storage, and for subsequent requests, the token is sent to the server to verify the user.
My question is: Why do we need to use tokens at all? Why don’t we just save a variable (like user) in a session and check if it exists on each request? Wouldn’t this be simpler and just as effective?
I’m trying to understand the benefits of using tokens over sessions. Any insights would be greatly appreciated!
Thanks in advance!
Example:
User First Login
// login_process
start_session()
if request_method == 'POST':
username = request_parameters['username']
password = request_parameters['password']
if validate_credentials(username, password):
set_session_variable('user', username)
redirect_to('protected_page')
else:
redirect_to('login_page?error=invalid_credentials')
Handling Subsequent Requests
// protected_page
start_session()
if session_variable_exists('user'):
// User is authenticated, proceed with protected content
display_protected_content(user)
else:
// Redirect to login page if user is not authenticated
redirect_to('login_page')
Mostafa Aourik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.