Session vs Token Authentication

Sessions and Tokens, which of these authentication methods best suits your website or application? Let’s find out.

 min. read
Published on
November 26, 2021

There are two main ways to do user authentication on the web, sessions and tokens.

Before determining which method is better, it’s crucial to understand how they work. Also, which of these authentication methods best suits your website or application? Let’s find out.

What is Authentication?

At its simplest level, authentication is the process of verifying your identity when you attempt to access a system. Note that authentication is different from authorization, which deals with granting access. In more complex terms, it also involves the verification of your device’s identity. For instance, authentication may be required when you or your device attempts to connect with your database stored on a server.

What is Session Authentication

Session-based authentication has been the default method for a long time. With this method, a session is created by the server after you log in. Traditionally, a session ID will be stored on a cookie in your browser. As long as you remain logged in, the cookie will be sent to the server upon subsequent requests. 

Upon receiving the cookie, the server compares the session ID it contains against the information stored in its memory. This allows the server to verify your identity and provide a response based on the corresponding state.

How Session Authentication Works

Here’s a summary of a typical flow of how session authentication verification works.

  1. You attempt to log in using your credentials.
  2. Your login credentials are verified, and the server creates a session with a session ID for you.
  3. Your session ID is stored in your browser (client) as a cookie.
  4. Upon subsequent requests, your cookie is verified against the session ID stored in the server. If it’s a match, the request is considered valid and processed.
  5. If you log out of an application, the session ID is destroyed on both the client and server sides.

Here’s an example of a session-based authentication request;

> GET /api_path HTTP/1.1

> Host: yourdomain.com

> cookie: session=<AUTHGEAR_SESSION_ID>

Advantages of Session Authentication

Depending on your use case, session authentication with cookies can offer many benefits. 

Easy to use

If you are working on a web-based application, cookies are supported by the browser on the client-side. There is no need to use any JavaScript to create interactivity. 

Storage Size

Session cookies are naturally small in size. This small size makes it efficient for storage on the client-side.

Limitations of Session Authentication

Many factors make the limitations of session authentication more pronounced. These factors include the need to decouple the front end from the backend and the rise of single-page applications in recent times.

Limited Scalability

Since Cookies are stored in your Server’s memory, it becomes inherently difficult to scale, especially where there are too many simultaneous users on the system. This is, however, quite the opposite with Token-based authentication. Read on to find out more.

Multiple Domains Challenge

The use of cookies for authentication can be very problematic where APIs requests are sent to services of different domains. This is because cookies typically work on a single domain or subdomains.

Security

Cookies are relatively more susceptible to Cross-Site Request Forgery (XSRF or CSRF) attacks and protective measures should be employed in your servers.

Best Practices for Session Authentication

  1. Keep Session IDs long and random to prevent brute force attacks. The recommended length is 128 bits.
  2. Record Session ID without sensitive or user-specific data. Ideally, the ID should be a random and meaningless string of characters.
  3. Enforce mandatory HTTPS communications for all session-based apps.
  4. Create Cookies with secure and HTTP-only attributes.
  5. Securely manage your sessions. For instance, you could destroy all sessions when you close your browser, where there’s a timeout, or when you log in or log out from different locations.

When to use Session Authentication

Session authentication is typically suitable for websites in the same root domain.

What is Token Authentication

Note that talks about Token Authentication typically refer to the JSON Web Token. Nowadays, it’s very common for web applications to use the JSON Web Token (JWT Token) rather than sessions for authentication. This can perhaps be linked to the rise of Single Page Applications (SPAs) in recent times. The Server creates a JWT Token with a secret and sends it to the Client for Token-based apps. The JWT is stored by the client and included in the header with every request. When a request is made from a Client, the Server validates the JWT before sending a response.

How Token Authentication Works

Let’s explore how Token authentication typically works.

  1. You attempt to log in using your user credentials.
  2. The server verifies your credentials, and if valid, it returns a signed token.
  3. The signed token is then stored on the client-side. It can either be stored in your local storage, in your session storage, or within a cookie.
  4. The token is placed in the header for subsequent requests to your server as an “authorization header”. The server then decodes the token in the header and processes it if it is valid.
  5. If you log out from an application, the token is deleted from the client-side, preventing further interactions.

A web api authentication request usually looks like:

> GET /api_path HTTP/1.1

> Host: yourdomain.com

> Authorization: Bearer <AUTHGEAR_ACCESS_TOKEN>

Advantages of Token Authentication

Token authentication improves upon the limitations of cookie authentication and offers much more.

Mobile Ready

While native mobile platforms may not combine seamlessly with cookies, Tokens are easier to implement on iOS and Android. It’s also easier to enforce Tokens for IoT applications or services that do not necessarily have a cookie store.

Improved Speed and Performance

With Cookie authentication, your backend would have to perform a lookup to an SQL database or a non-SQL alternative. This lookup will take significantly more time than it would take to decode a token. Similarly, since you can store additional data like permission levels and roles within a JWT, you essentially save the time and resources it would take to make other lookup calls.

Scalability and Statelessness

One of the biggest attractions to JWT Token authentication is that it is stateless and highly scalable. The backend does not need to store the JWT token, and each one contains all the data required for verification. With this authentication method, the server is essentially tasked with signing tokens upon successful login requests and verifying whether incoming tokens are valid. In some cases, you can use third-party services like Authgear to issue tokens that are subsequently verified by your server.

Supports Multiple Domains

While cookies are bound to a single domain, you can send tokens to any domain you want. Imagine a single-page app which is making multiple requests to multiple services, the same token can be used to authenticate in these servers.

Limitations of Token Authentication

Token authentication offers many benefits but isn’t perfect as you might experience some drawbacks depending on your use case.

Size of JWT Tokens

Unlike cookies, JWT Tokens are significantly larger in sizes, and this is because they contain a lot more information.

Tokens can be hijacked

It is common to use JWT tokens for authentication. The authentication state is handled in the client. The tokens can be hijacked by hackers and they are harder to be invalidated on the server.

Best Practices for Token Authentication

  1. Validate your JWT Tokens and reject those that do not conform to your signature algorithm. You should also validate all claims, issuers, expiration dates, and audience.
  2. Ensure that an expiration time is set for tokens. If you fail to set an expiration time for your tokens expressly, it could be set to remain valid forever.
  3. You should avoid hardcoding tokens as it could ultimately make the work of compromising your applications easy for hackers.
  4. Enforce HTTPS communication and avoid sending tokens across non-secure connections where they can be intercepted and compromised.

When to use Token Authentication

This authentication method is most suitable for mobile apps or single-page web applications. The key transport mechanism here is the access token in the authorization header.

Common Misconception

While traditionally websites use session authentication with cookies, and mobile apps/SPAs use token authentication with Authorization header, this are not necessarily the case. Authorization Header and Cookies are about the transfer mechanism. Tokens and sessions essentially are about where the authorization state is handled, whether on the server-side or the client-side. For example, a server can issue a JWT token via cookie, or expect a stateful session ID to be provided in the “Authorization” header.

Closing Thoughts: Which Authentication should you use?

Determining which authentication method to use is a critical factor in developing mobile apps or single-page web applications. While the need to scale with an authentication method that’s mobile-ready will draw many developers to using tokens, the simplicity of cookies may appeal to others. Ultimately, questions regarding cookie vs token authentication methods will be determined by the type of application or web platform being built. 

Authentication solution providers like Authgear provide a comprehensive solution that caters to all use cases. For instance, Authgear provides both cookie-based and token-based authentication to suit a wide range of web and mobile applications. It offers an out-of-the-box authentication solution that promotes a frictionless user experience without compromising security. Request a demo to see Authgear in action today.