Cookie Authentication

Alisha Chhabra
Last Updated: May 13, 2022

Introduction 

Do you like the coffee at Starbucks? Because we are programmers, of course. Coffee has a different fan base among programmers.

Source: tenor

Assume you're visiting Starbucks for the first time and order your favourite coffee. The next day, you returned to Starbucks and ordered the same coffee. You're no longer interested in ordering the same coffee every day. So you want them to always remember your favourite coffees or desserts? However, Starbucks has resolved this enigma by providing Identification cards to their customers. And your past orders are saved in their database for future reference. When you go to Starbucks, all you have to do is show your card, and you'll be served your favourite coffee automatically. Isn't it fantastic? 

Now, What does this have to do with our topic today? In the same way that we talked about ordering coffee, web applications use cookies to remember you for future visits so that the user doesn't have to enter their username and password every time he visits the site.

You’ve probably seen the options for Remember me or Keep me logged in on the login pages. Websites use cookies to remember the user to enhance the user experience. 

Source: codecharge

 

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

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. Clients and servers communicate by sending and receiving individual messages (as opposed to a data stream). Requests are messages sent by the Client; usually, a Web browser, and responses are messages sent by the server as an answer.

When you order food online, for example, you are the Client, and the restaurant from which you are ordering is the Server. On the other hand, the delivery man can be assumed as the HTTP protocol since he takes your order and delivers the food to your door as a response from the Server.

The HTTP protocol is located on the application layer and relies on the TCP protocol for support. TCP stands for Transmission Control Protocol, and it is used to send packets from the source to the destination.

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. As a result, the website now performs poorly, and the user experience suffers. 

Now, how is this deemed to relate to our topic,i.e., the Cookie Authentication?

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 behaviour of HTTP protocol from Stateless to Stateful, sessions, and cookies are being used. 

Now, what are sessions and cookies?

Let us discuss them one by one:-

What are sessions?

The term "session" refers to a visitor's time spent on a website. It's meant to represent the time between when a visitor first visits a page on the site and when they leave.

A session is a period during which a user interacts with a website or software application. A web session is a series of contiguous actions performed by the user on a single website within a specified time frame. This could include your search engine queries, completing a form to receive content, scrolling on a website page, adding items to a shopping cart, researching airfare, or which pages you viewed on a single website. Any interaction with a single website is recorded as a web session to that website's property.

For example, if you visit a website and then open a new tab and visit other websites, the session for the previous one is still active, and so on for the subsequent ones. Websites such as Facebook, Amazon, and Flipkart offer extensive session time. On the other hand, banking applications only provide a session for 10 minutes or less when the user is inactive, i.e., when you leave the site open in your browser.

Now, how is the current state being tracked?

A web session ID is stored in a user's browser(i.e., the Client-side) to track sessions. Any HTTP requests made by the user while on the site are passed along with this session ID.

Source: hazelcast
 

A single session never lasts longer than a specific duration, at least as far as the web property is concerned, because the code that initialises a session also includes an expiration. Depending on the site, a web session can be as short as five minutes or as long as 1,440 minutes(an entire day).

For example, whenever you visit a new website or download new applications, you've most likely seen the guided path at the beginning. There are several steps provided to educate the user about the application or website. However, returning to that site or application will not guide you unless you create a new account or re-download the application. This example shows how sessions work on websites or in any software application. Each session has an expiry time associated with it. 

You now have a clear understanding of what the sessions entail.

Let's take a look at the cookies and how they relate to the session:-

Cookies and Sessions

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 recognise your device in the future. If you visit that site again, it can read that cookie to remember you from your previous visit and track you over time. 

Source: O'Reilly

 

Now, what exactly is stored in the cookie?

The contents of a cookie are determined by the website that created that cookie. 

A cookie's content is nothing more than a small piece of text. The text's meaning can be anything. What it means depends on the software that the website is using.

Uses of Cookies

  • Cookies are frequently used to store a unique identifier to establish a stateful connection between the browser and web server. The session ID is the unique identifier provided by the session. When a session begins, a unique session ID 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 is permitted to act; otherwise, access is denied. As previously stated, sessions have an expiry date, whereas cookies are stored permanently on your local computers, i.e., your web browser.
  • The Client sends a GET or POST request to the server in the first step.
  • The session_ID is generated on the Server, and it is saved in the database. As a response to the Client, it returns the session_ID along with a cookie.
  • The Server receives a cookie with the session_ID stored on the browser. The server compares this id to the saved session_ID and sends an HTTP200 response.
  • In other cases, cookies are used to store authentication information (such as a user's username and a crypto hash) so that users are automatically logged in when they return to a website.
  • Collect information about the pages you visit and your activities on the site allow the site to recognise you.

 

For example,

  • by remembering your user ID and providing an online shopping cart
  • keeping track of your preferences in case, you return to the website
  • personalise your web browsing experience
  • deliver advertisements that are tailored to you.

 

Session vs. Cookies

Many people 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'sServer 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 unauthorised user gains access to our system, he can manipulate the data.

 

Creating Cookies with PHP

To create a cookie in PHP, use the setcookie() function, which must be placed before the <html> tag. This function's syntax is as follows:

setcookie(namevalue, expire, path, domain, secure, httponly);

 

Only the name argument is required in the above syntax, and the others are optional.

For Example:

setcookie("NinjaID", "1234", "time()+3600");

 

Cookie Attribute:-

Name:- It defines the name of the cookie.

Value:- It defines the value of the cookie.

Expire:- This specifies when the cookie will expire. Cookies will be deleted at the end of the session if it is not used or set to 0. 

Path: It specifies the cookie's server path. If it is set to "/," the cookie will be accessible across the entire domain.

Domain: It specifies the cookie's domain name. If we set it to "codingninjas.com," it will be available for all codingninjas.com subdomains.

Secure: This specifies whether cookies are only sent over HTTPS or not. If set to True, cookies will be set only for the secured connection.

HTTPOnly: If set to TRUE, cookies will only be accessible via the HTTP protocol.

Summary of Cookie Authentication

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 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 way, if someone gains access to your database, they won't be able to see your users' passwords.

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 to the Server as an HTTP request.

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 sent back to the Client. Set an expiration date/time to keep the user's session limited.

Cookies will be attached to every request (and response) sent between the Client and the Server from now on.

 

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 in the database associated with that user every time the Client requests a page that requires authorization (i.e., they must be logged in). Access is granted if it checks out.

Now, let us discuss some frequently asked questions on Cookie authentication :-

Frequently asked questions

  1. What is Cookie Authentication ?
    Over the stateless HTTP protocol, cookie authentication uses HTTP cookies to authenticate client requests and maintain 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.
  2. 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.
  3. What is the distinction between first-party cookies and third-party cookies?
    The following are the primary distinctions between first-party and third-party cookies: Setting a cookie: The publisher's webserver or any JavaScript loaded on the website sets a first-party cookie. A third-party cookie can be set by a third-party server, like an AdTech vendor, or by code on the publisher's website.

Key takeaways

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

If you don't want to be attacked by the hijack, create your accounts on trustworthy websites.

Till then, stay tuned for excellent articles and enjoy cookies with Starbucks coffee.😁
 

Was this article helpful ?
4 upvotes

Comments

No comments yet

Be the first to share what you think