Cookie vs Token authentication
To protect communication between the client and the server, we generally require authentication, an inbound request accompanied by a set of identifying credentials. With the growing number of threats, the authentication mechanism's stability has become critical for all applications. However, selecting one is difficult due to the numerous approaches available, each with its own set of skills.
One of the authenticated types, Cookie-based authentication, was discussed in the previous article. You may proceed if you already have a good understanding of cookies, sessions, and the HTTP protocol. Although, in this article, we'll solely cover cookie-based authentication.
Additionally, it is critical to understand which authentication method is more accurate at what moment. A web application may suffer as a result of the high traffic. We'll walk you through all of the technical aspects of cookie-based and token-based authentication.
Let’s get started with Cookie vs token authentication right away:-
Authentication is the process of trading user credentials for a piece of unique identification.
This unique identifier (cookie) is generated on the server and sent to the browser in cookie-based authentication.
A cookie-based authentication employs HTTP cookies to authenticate client requests and preserve session information on the server using the stateless HTTP protocol.
When you log in to a web application, your browser receives a cookie from the application's server, which it stores locally, and sends that cookie with each subsequent request to allow the server to verify that the requests are from the same person.
Let's break down the cookie-based authentication process into five dimensions to understand better how it works.
1. Using credentials, the user logs in to the application.
2. The server verifies the credentials and creates a session in the database.
3. The server responds to the browser by putting the cookie in the Set-Cookie header.
This cookie is supplied as a name-value pair and provides a unique id that identifies the user. A cookie contains information such as the expiry date, domain, age, last access, and so forth.
The following is an example response with several Set-Cookie headers:-
HTTP/2.0 200 OK
Set-Cookie: <cookie-name>=<cookie-value>; Path=<path>
Set-Cookie: <cookie-name>=<cookie-value>; Secure;
4. The Cookie is stored in the browser and sent with subsequent requests.
When the server receives a Cookie-enabled request, it compares the session ID to the session in the database to validate the user.
All Cookies saved in your browser can be found in the Cookie storage area of the application section when using dev tools.
5. The server will erase the session from the database when the user logs out.
The server will expire the Cookie by clearing the database session whenever the user logs out of the system. The browser accomplishes the same thing by removing it from the Cookie storage.
Now that you have a fundamental grasp of how cookie-based authentication works, let's look at some of its features:
Features of Cookie-based authentication
- Fully automated process:-
If you utilise Cookies for authentication, you don't need to write any code to add Cookies to requests. The browser will handle Cookie processing, and it will add the Cookie to all requests automatically.
Although this automated approach makes developers' jobs easier, it also has a few downsides. Some requests, for example, do not require any authentication. However, with this strategy, Cookie is sent with each request.
Furthermore, CSRF attackers can use this approach to mislead the browser into sending requests, including the Cookie to bogus websites.
Cross-Site Request Forgery (CSRF) attacks leverage an authenticated end-user connection to perform unwanted actions on web applications. Threat actors commonly use social engineering tactics to dupe people into carrying out these assaults.
A user, for example, might receive an email or text message containing a link that deploys malware or injects harmful code into a web page. When a user clicks on a link, attackers use malware or injected code to send requests to the web application on the user's behalf.
The below image demonstrates the CSRF attacks more clearly:-
- Security concerns:-
Cookie-based authentication does not provide adequate security against attacks by default. It is particularly vulnerable to cross-site scripting (XSS), and cross-site request forgery (CSRF) attacks discussed above.
However, we can expressly adjust Cookie headers to protect them from such assaults.
Cookies, for example, can be readily safeguarded against XSS attacks by setting the Cookie headers with the HttpOnly flag. If the HTTP response header contains the HttpOnly flag, the client-side script cannot retrieve the cookie.
|Set-Cookie: <cookie-name>=<cookie-value>; Secure;|
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly;
In addition, we can use the SameSite property in the cookie header to successfully block CSRF attacks.
|Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict;|
The SameSite attribute has three possible values:-
- SameSite=Lex ensures that the browser does not deliver Cookies on cross-site requests (this is the normal behaviour of Cookies if the SameSite attribute is not defined).
- SameSite=Strict ensures that the browser only delivers the Cookie for same-site requests.
- SameSite=None enables you to deliver Cookies in conjunction with both cross-site and same-site requests.
- APIs are ineligible:-
Cookies aren't the way to go if you're creating an API to expose services to clients. Unless the client is a browser, it will complicate matters for the client. In comparison to query params, simple request headers, or the request body, handling cookies is a significant nuisance for clients other than browsers. A query parameter is a predefined collection of parameters that are appended to the end of a URL. They are URL extensions that assist in defining customized content or actions based on the data being delivered.
On the other hand, using cookies in a browser can make a lot of things much easier.
So, an API might look for authentication data in the Authorization header first because that's probably where non-browser clients will prefer to put it. Still, it might also check for a session cookie for server-side log-in to simplify and streamline browser-based clients, but only if the regular Authorization header was missing.
- There may be concerns with scalability:-
As previously said, the server is in charge of the Cookie setting, and we must save each user's sessions in the database.
Even though there are well-known methods for scalability (for example, utilising in-memory databases like Redis for session storage), it still adds to the complexity.
However, when the number of users rises, expanding and managing those sessions may become difficult. When the site has a large number of visitors, this makes it less scalable and increases overhead.
- Usually works on the single domain unless specified:-
Unless you specifically enable it, cookies only operate on a single domain.
It is, for example, impossible to read or transfer a cookie from a site like codingninjas.com to a domain like meta.com. This is a problem when the API service for mobile and web platforms comes from distinct domains.
Although it appears to be a drawback from the outside, it is one of the most powerful features for enforcing single-origin by default.
If your frontend and backend (API) come from separate domains or subdomains, you must explicitly whitelist that in the Cookie. Otherwise, the Cookie will not be sent along with the request by the browser.
Token-based authentication was created to overcome numerous problems of the Cookie-based authentication method. In contrast to cookies, the token-based strategy necessitates manual implementation, and tokens are kept on the client-side, making them more scalable.
To further understand how tokens work, we'll divide the process into four steps and use JWT, the most extensively used token standard, as an example.
The most widely used open standard in token-based authentication is JSON Web Token (JWT).
1. The user logs in to the application using their credentials.
2. The server validates the credentials, produces a token, signs it with a secret key, and returns it to the browser.
A JWT token has three pieces that are separated by dots (.). The three components are the JWT header, the JWT payload, and the signature (header.payload.signature).
Example of a token:-
Let us further breakdown the components of the JWT token:-
JWT header = The header generally consists of two parts:-
The type of token, which is JWT, and the signing technique, such as HMAC SHA256 or RSA
The JWT Header is a JSON object that has been Base64 URL encoded.
Base64 is a collection of binary-to-text encoding techniques that convert binary data into a radix-64 representation in an ASCII string format.
JWT payload = The payload, which contains the claims, is the second element of the token. Claims are statements about an entity (usually, the user) and extra information. There are three sorts of claims: registered claims, public claims, and private claims.
- Registered claims:- This is a set of preconfigured claims that are not required but are recommended to give a set of relevant, interoperable claims. Iss (issuer), exp (expiration time), sub (topic), aud (audience), and others are examples.
- Public Claims:- Those that use JWTs can define them as they see fit. They should, however, be specified in the IANA JSON Web Token Registry or as a URI that has a collision-resistant namespace to avoid clashes.
- Private Claims:- Private claims often include information unique to your company, such as an internal user ID. Private claims, unlike public claims, are vulnerable to collision since they are not recorded and should be utilised with caution.
An example of a payload could be:-
"name": "John Doe",
JWT Signature = To produce the signature section, you must sign the encoded header, the encoded payload, a secret, and the algorithm provided in the header.
For example, if you wish to utilise the HMAC SHA256 algorithm, the signature will be generated as follows:
|HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)|
The signature is used to ensure that the message hasn't been tampered with along the way, and in the case of tokens signed with a private key, it can also ensure that the sender of the JWT is who they claim to be.
4. When the user logs out, you must manually erase the token from its storage.
When a user logs out of the system, you must manually clear the token kept in the storage, rendering it inaccessible for future requests.
Since now you have a clear understanding of what Cookie-based and Token-based authentication is, let us now compare them and analyze the difference between them:-
Cookie vs Token authentication
- Stateless mechanism
Unlike cookies, token-based authentication is stateless. This indicates that no user information is saved in the database or on the server.
Since, the server is only responsible for creating and validating tokens, more scalable solutions can be built with a token-based mechanism than with the Cookie-based method.
- Security issues
Although tokens attempt to solve security vulnerabilities in Cookies, they are not completely foolproof.
Furthermore, because the token is stateless, if it is exposed outside, there is no way to revoke it until it expires. As a result, it's critical to keep the token as small as possible.
The back-end must perform a lookup when employing cookie-based authentication, whether a typical SQL database or a NoSQL option. The round trip will most certainly take longer than decoding a token. Furthermore, you can avoid making several search requests to get and process the required data because you may keep other data inside the JWT, such as the user's permission level.
- Mobile Ready
APIs in the modern-day do not simply interface with browsers. A single API, when correctly written, may serve both the browser and native mobile platforms such as iOS and Android. Cookies and native mobile platforms do not get along. While utilising cookies with mobile platforms is conceivable, there are several limits and constraints. Tokens, on the other hand, are far more straightforward to install on both iOS and Android. Tokens are also simpler to deploy for Internet of Things applications and services that do not use the cookie store paradigm.
The size of JWTs is the most significant downside of token authentication. In comparison to even the tiniest JWT, a session cookie is rather modest. Depending on your use case, the size of the token may become an issue if you add a lot of claims to it. Remember that each request to the server must include the JWT.
Let us now have a look at when to use Cookie vs token authentication:-
Which one to use and in what frame?
JWTs are widely used in modern web applications because they scale better than session-cookie-based sessions. After all, tokens are stored on the client-side. At the same time, the session uses server memory to store user data, which can be an issue when many users access the application simultaneously. Because JWT is transmitted with every request and contains all user information. Even if it is encoded, it is vital to utilise just the necessary information in JWT, and sensitive information should be avoided or encrypted to prevent security attacks.
No one way must be utilised at all times; it is up to the developer and the requirements to choose which approach should be used for which circumstance. To get a bearer token, for example, OAuth employs a particular bearer token and a longer-lived refresh token. To construct a flexible and resilient application, it is preferable to use a combination of both kinds.
As we can see, none of these strategies are flawless, and they all have limitations.
So, rather than chasing the optimal authentication solution, I propose selecting one depending on your project requirements.
Frequently asked questions
- What is the difference between cookies and JWT?
Both cookies and bearer tokens send data. One distinction is that cookies are used to send and store raw data, whereas bearer tokens are only used to send authorization data. This data is frequently encoded as a JWT.
- Is the session a cookie?
No, Cookies are client-side files that contain user information on a local computer, whereas Sessions are server-side files that store user information. Sessions are cookie-dependent, whereas cookies are not session-dependent.
- What exactly is the distinction between LocalStorage and cookies?
Cookies are smaller and return server information with each HTTP request, whereas LocalStorage is more extensive and can store data on the client-side.
- What is the difference between authentication and authorization?
In simple words, authentication is the process of confirming who someone is, whereas authorization ensures which specific applications, files, and data a user have access to.
For example, authentication refers to verifying and confirming employees' IDs and passwords in an organization, whereas authorization refers to determining which employee has access to which domain.
To wrap up the session, we’ve covered Cookie vs token authentication in detail. We frequently need to associate an incoming request with a set of identity credentials to secure communication between a client and a server. Using any of the Cookie vs. token authentication, we can achieve our objectives. However, we’ve also analyzed that no single method must be used at all times; it is up to the developer and the type of requirements to determine which way should be used for which scenario.
Don’t stop here, Ninja; there is a lot more to learn and grasp. Stay tuned for more amazing content and quality material. Till then, have a look at our other articles.
I hope this article has helped you understand the two most common authentication methods.