authenticationbackend

Why use tokens instead of sessions for user authentication in web apps?


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')

Solution

  • A Server has more than one session at the same time and it needs a way to figure out which incoming web request belongs to which session.

    To do that, servers generate session tokens, just a random ID for the session so the server can store information regarding that session somewhere.

    It's usually send to the client in a cookie header and the client keeps sending that cookie header in each request.

    Each time the server sees that cookie header in the request it knows where to find that session and within that session it can now find the username and other information.

    What your example does is to simply skip the part that allows servers to find the session. If you had just a single server-wide session, everyone would be the same user once someone logged on.