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, which is a small file that stores information about the user including unique session ID, time of login and expirations, and more, is created by the server and stored in the database 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.
- You attempt to log in using your credentials.
- Your login credentials are verified, and the server creates a session with a session ID for you. This session is stored in the database.
- Your session ID is stored in your browser (client) as a cookie.
- 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.
- 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
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.
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
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
- Keep Session IDs long and random to prevent brute force attacks. The recommended length is 128 bits.
- Record Session ID without sensitive or user-specific data. Ideally, the ID should be a random and meaningless string of characters.
- Enforce mandatory HTTPS communications for all session-based apps.
- Create Cookies with secure and HTTP-only attributes.
- 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. When user attempts to log in, 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, which is what differentiates token authentication from session authentication. When the server receives the token, it does not look up for the user's session ID in the database for authentication. The server simply checks whether the token is valid or not.
How Token Authentication Works
Let’s explore how Token authentication typically works.
- You attempt to log in using your user credentials.
- The server verifies your credentials, and if valid, it returns a signed token.
- 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.
- 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.
- 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.
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
- 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.
- 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.
- You should avoid hardcoding tokens as it could ultimately make the work of compromising your applications easy for hackers.
- 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.
The table below summarizes the differences between session and token authentication.
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.