Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Understanding HTTP Protocol 
3.
Cookie
3.1.
Types of Cookies
3.1.1.
Session Cookies
3.1.2.
Persistent Cookies
3.1.3.
Non-Persistent Cookies
3.1.4.
Session vs Cookies
3.2.
Uses of Cookies
3.2.1.
Storing Relevant Information
3.2.2.
Authentication with Sessions
3.2.3.
Authentication with Password
3.3.
Creating Cookies using PHP
3.4.
Advantages of Cookies Authentication
4.
Frequently asked questions
4.1.
What is Cookie Authentication?
4.2.
How does cookie authentication work?
4.3.
What are the different types of cookies?
4.4.
What are session cookies?
4.5.
What is cookieless authentication?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Cookie Authentication

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Hey Ninjas!! You must have heard of online shopping websites like Amazon or Flipkart. Most of us like to shop, so we always have our cart filled with some items.

But imagine this: whenever you reload the page or close the tab. Your shopping cart becomes empty. And you have to add all those items again.

How irritating, right? This is why these websites save your cart. So we can stay satisfied and add those items again.

But have you ever wondered how these websites store and display the data every time you visit?

Introduction Image

They use Cookies to store your data. Cookies are used to remember the previous state of the website. And to load it with the same configuration you used last time to avoid multiple repetitions of work.

Before we get into cookies, let's look at some of the websites' protocols.

Understanding HTTP Protocol 

The HTTP or HyperText Transfer Protocol is one of the most potent protocols widely used on websites. It acts as a conduit between the Client and the Server. When you request a web application, such as ‘codingninjas.com’, the HTTP protocol requests the site on your behalf to the Server and returns the Server's response to you. The server and the client contact each other via messages. Client sends the message as Requests, while Server sends messages as Responses.

http

When you shop online, you are the Client, and the website/vendor from which you are ordering is the Server. On the other hand, the delivery man can be assumed as the HTTP protocol since they deliver your order to your door as a response from the Server.

The HTTP protocol is considered Stateless because it doesn't remember the previous request/response. It means if you're scrolling through a landing page and come across another link to the following website, the HTTP protocol makes another request on behalf of the user and receives a response from the Server. Every request-response cycle is independent of the previous process and does not store any information.

stateless process

Since HTTP is stateless, you'll need a way to store user data between HTTP requests if you want to link one request to another. To make the behavior of HTTP protocol from Stateless to Stateful, sessions, and cookies are being used.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Cookie

A cookie is an information that your web browser saves. When you visit a website, it may place a cookie on your web browser to recognize your device in the future. If you see that site again, the browser reads that cookie, remembers you from your previous visit, and tracks you over time.

Let's see how these e-commerce sites work with their shopping carts.

When you go to these sites for the first time, they ask you to log in/register with them. Even if you don't sign in, these websites have empty cookies to store the data. 

When you start shopping, you add items to your cart individually. 

cookie -1

But now, accidentally, you close the tab where you were shopping. 

So now you again open a new tab and revisit the site. Here you see the cart is in the same state as you left. 

How did this happen? When you were shopping, you were updating the cart. 

When your session ended with the site, the cookie stored the cart, and so on; revisiting the site, the cookie retrieved the cart for you, and you got the initial cart, which you left.

cookie - 2

Types of Cookies

There are many different types of cookies available, like Session Cookies, Permanent Cookies, First-Party Cookies, Third-Party Cookies, Flash Cookies, etc.

Here we will be focussing more on Session Cookies, and how they work.

Session Cookies

Session Cookies are a type of cookie, where it stores the relevant session id. The session id is stored in the server, against the user’s login, and so during signing in, the session ID is matched, rather than username and password matching, as this is a bit faster than the latter.

This is a server-specific cookie, so if your application has servers distributed across the globe, it would be difficult for the cookie to match, as it allows the browser to re-identify itself to the single server, from which the user was previously authenticated. 

Persistent Cookies

As the name suggests, persistent cookies are the cookies that are persistent in the browser. These are valid for multiple sessions and are not removed when the user closes the browser or logs out of the site. etc.

Non-Persistent Cookies

These cookies are valid only for a single session and are removed when the user closes the browser or logs out of the session. These are useful for security purposes like banking websites. etc

Session vs Cookies

People often get confused between the sessions and cookies about their life span. 

Let us not do that and understand their differences and relation more clearly:-

Session

Cookies

A session saves the variables and their values to a file in the server's temporary directory. Cookies are text files that are held on the user's computer.
When the user logs out of the application or closes his web browser, the session ends. Cookies expire after the user-specified lifetime.
We can store as much data as we want within a session, but a maximum memory limit of 128 MB that a script can use at one time. The browser's cookies have a maximum size of 4 KB.
Sessions are more secure than cookies because they save data in encrypted form. Cookies are not secure because the data is stored in a text file, and if an unauthorized user gains access to our system, he can manipulate the data.

Uses of Cookies

There are various uses for cookies, and we will be majorly focusing on Cookie Authentication and its working.

Storing Relevant Information

Cookies are used to store other relevant information; like in the example above, cookies are used to store the shopping cart list. The list will be retrieved when the user revisits the website. Cookies are also used to store users' preferences, like dark/light theme mode and ads tailored to your preferences, etc.

Authentication with Sessions

Sometimes, when you re-visit a website, it asks you to log in again. While this is good for security issues, it frustrates most users. We use cookies to authenticate the user on the user's behalf, preventing the signing-in process.

Cookies can also be used to authenticate users with the websites. Let's dive deeper into the working of cookie authentication.

When you check the option, it stores your creates and stores your session, with necessary details like your username, session creation date, and session expiration date. etc.

Step 1: When you try to log in to any website, you may have noticed that you are prompted with the checkmark Remember Me or something similar. 

When you check the option, it stores your creates and keeps your session, with necessary details like your username, session creation date, and session expiration date. Etc.

Step 2: When a session begins, a session ID (unique identifier provided by the session) is randomly generated in the database, and the same ID is then passed to the cookie. 

When a user returns to the site, the cookie stored in the web browser is compared to the session ID stored in the Server's database for authentication. If both match, the user can act; otherwise, access is denied. Sessions have an expiry date, whereas cookies are stored permanently on your local computers, i.e., your web browser.

step 2

As you can see in the above image, the Client first sends a GET or POST request to the Server. The session_ID is generated on the Server and saved in the database. As a response to the Client, the Server returns the session_ID along with a cookie which is stored in the user's browser.

Step 3: When the user logins again or revisit the website. The browser sends the cookie to the Server. The Server receives a cookie with the session_ID stored on the browser and compares this id to the saved session_ID on the database. If the saved session_id and the current received session_id match, then the user is authenticated and sends an HTTP-200 response.

Otherwise, it sends an HTTP-401 response.

Note: The cookies never store username and password, as it is prone to many cyberattacks, such as Cross-Site Request Forgeries (CSRF). 

Authentication with Password

Don't be startled; we won't store the password in the cookies. As discussed above, we never store the user's password in the cookies, as it is prone to cyber-attacks. 

We can store the user's username and the crypto hash of the user's password. 

A hash is an irreversible function of a predefined length and is of one-time use. One can't generate the original item from the hash. 

So if we store authentication information (such as a user's username and the crypto hash of the user's password), users are automatically logged in when they return to a website.

Here's a brief description of user authentication with a password.

Step 1: Client -> Signing up

First and foremost, the user must register. The Client sends an HTTP request with their username and password to the Server.

step 1

Step 2: Handling sign-ups on the Server

The Server receives this request and hashes the password before storing the username and password in your database. This prevents anyone to gain see your password by hacking your database.

Step 3: Login as a client or as a user.

The user is now logged in. They enter their username and password, which is sent via an HTTP request, to the server.

Step 4: Server -> Login Validation

The Server looks up the provided login password in the database, hashes it, and compares it to the previously hashed password in the database. If it doesn't match, we'll deny them access by returning a 401 status code and terminating the request.

Step 5: Server -> Access ID Generation

If everything looks good, we'll generate an access ID that will be used to identify the user's session. 

It should be saved in the database for that user.

Add it to a response cookie that will be returned to the Client. Set an expiration date/time to keep the user's session limited.

From now on, cookies will be attached to every request (and response) sent between the Client and the Server.

step 5

Step 6: Client -> Making page requests.

We are now logged in on the client side. The Server obtains the access ID from the cookie and compares it to the one which is stored in the database associated with that user. So now when a user tries to log in again, the access ID is matched and the user is logged in.

Creating Cookies using PHP

Now that we’ve discussed cookies, let’s see how one can create such. Here we will be using PHP, to create a cookie.

setcookie(name, value, expire, path, domain, secure, httpOnly);

<!--
	Required Arguments
	name:- name of the cookie.
	
	Optional Arguments
	value:- defines value of the cookie.
	expire:- specifies when the cookie will expire.
	path: specifies the cookie's server path.
	domain: specifies the cookie's domain name.
	secure: specifies whether cookies are only sent over HTTPS or not.
	httpOnly: if set to TRUE, cookies will only be accessible via the HTTP protocol.
-->

Advantages of Cookies Authentication

Here we will be looking over some advantages and disadvantages of cookies authentication, and why one should prefer this.

  • Cookies can be made available for a larger time period, by maintaining the session for a longer period of time.
     
  • They are easily configurable and transparent to the users/developers.
     
  • The expiration date and time can be set by the developers according to their needs.
     
  • They are user-friendly by not making the user log in over again when revisiting a website. Instead, it stores the session id, which shall be useful when another session is established.
     

However, there are certain disadvantages to cookie authentication as well.

  • They are vulnerable to CSRF attacks. CSRF stands for Cross-Site Request Forgery, where users are tricked into performing unintended actions, on the websites they were authenticated before.
     
  • They do not work on mobile phone browsers.
     
  • They are less scalable, and the overhead rises when the website traffic increases.

Frequently asked questions

What is Cookie Authentication?

Over the stateless HTTP protocol, cookie authentication uses HTTP protocol in order to verify the client requests and to store the session information on the Server. The Server then verifies the validity of the session ID stored in the cookie by comparing it to the database.

How does cookie authentication work?

The key for cookie authentication could be something like 'username', with the Ninja as the value. Ninja's browser will include the cookies in every request he makes to a website, and the host server will check the cookies. As a result, authentication can be done automatically in this manner.

What are the different types of cookies?

Different types of cookies are available, like Session Cookies, Permanent Cookies, First-Party Cookies, Third-Party Cookies, and Flash Cookies, etc

What are session cookies?

Session cookies are the cookies that contain the user's activities for as long as the session expires. Once the session expires, the cookie gets deleted. 

What is cookieless authentication?

Cookieless authentication means authentication without storing any sessions. They use JWT or JSON web tokens to authenticate the user, instead of creating a cookie.

Conclusion

We've explored Cookie Authentication in the discussion, which enhances the user experience. HTTP cookies are necessary for everyday Internet use, but they risk your privacy. HTTP cookies are required for web browsing because they allow web developers to provide you with more personalized and convenient website visits. Cookies enable websites to remember you, your logins, shopping carts, and other information.

Here are some articles which may interest you

Also, check out the Coding Ninjas Studio library to better understand the data structures and algorithms.

Side by side, you can also practice a wide variety of coding questions commonly asked in interviews in Coding Ninjas Studio. Along with coding questions, you can also find the interview experience of scholars working in renowned product-based companies here.

Check out the Interview guide for Product Based Companies and some of the popular interview problems from top companies like AmazonAdobeGoogleUberMicrosoft, etc., on Coding Ninjas Studio.

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSand System Design, etc. as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Happy Learning!

Previous article
Difference between Authentication and Authorization
Next article
Cookie vs Token authentication
Live masterclass