Understand JavaScript Cookie

Cookies are small pieces of data that websites store on a user’s device to remember information about the user. They are widely used to make websites work efficiently, improve user experience, and provide information to website owners.

Here’s a detailed breakdown of cookies:

💡Types of Cookie

Session Cookies

 Purpose: These cookies are temporary and are deleted once the user closes their browser.

 Use Case: They are used to keep track of the user’s activities during a single browsing session, such as items in a shopping cart.

Persistent Cookies

Purpose: These cookies remain on the user’s device for a set period or until they are manually deleted.

Use Case: They are used to remember login details, preferences, and other settings to enhance user experience over multiple visits.

First-Party Cookies

Purpose: These cookies are set by the website the user is visiting.

Use Case: They store preferences and data needed for the website to function correctly.

Third-Party Cookies

 Purpose: These cookies are set by domains other than the user is visiting.

 Use Case: They are often used for tracking and advertising across different websites.

💡Functions of Cookies

1. Authentication:

   Cookies store authentication tokens to keep users logged in as they navigate different pages.

2. User Preferences:

 Cookies remember user settings and preferences, such as language, theme, or layout choices.

3. Analytics:

   Cookies collect data about user interactions and behaviors on the site, helping website owners understand how users engage with their content.

4. Advertising:

   Cookies track users’ browsing habits and interests to serve targeted ads.

5. Session Management:

   Cookies track the items users add to their shopping cart or input information into forms during a session.

Security Measures for Using Cookies on Banking Websites

Like any other website, using cookies on banking websites comes with security considerations. While cookies are essential for maintaining sessions and improving user experience, they must be managed carefully to ensure security, especially for sensitive applications like banking. Here are some key points to consider:

Use Secure Cookies

 Set the `Secure` flag on cookies to ensure they are only sent over HTTPS connections.
This prevents cookies from being sent over unencrypted HTTP connections, reducing the risk of interception.

  document.cookie = "sessionToken=abc123; Secure; path=/;";

HttpOnly Flag

Set the `HttpOnly` flag to prevent cookies from being accessed via JavaScript. This helps protect against cross-site scripting (XSS) attacks.

 document.cookie = "sessionToken=abc123; Secure; HttpOnly; path=/;";

SameSite Attribute

Use the `SameSite` attribute to control how cookies are sent with cross-site requests. Options include `Strict`, `Lax`, or `None`. It helps mitigate cross-site request forgery (CSRF) attacks.

 document.cookie = "sessionToken=abc123; Secure; HttpOnly; SameSite=Strict; path=/;";

Short-lived Cookies

Use cookies with short expiration times for sensitive data. Limits the time window in which an attacker can use a stolen cookie.

 var date = new Date();
 date.setTime(date.getTime() + (30 * 60 * 1000)); // 30 minutes
 var expires = "expires=" + date.toUTCString();
 document.cookie = "sessionToken=abc123; Secure; HttpOnly; " + expires + "; path=/;";

Encryption of Cookie Values

Encrypt sensitive information stored in cookies. Adds an extra layer of security if the cookie is intercepted.

Regular Rotation of Session Tokens

Regularly rotate session tokens and invalidate old tokens. Reduces the risk of session hijacking.

Example Implementation

Here’s an example of setting a secure cookie for a banking website:

// Create a cookie with secure settings
function setSecureCookie(name, value, minutes) {
    var date = new Date();
    date.setTime(date.getTime() + (minutes * 60 * 1000));
    var expires = "expires=" + date.toUTCString();
    document.cookie = name + "=" + value + "; Secure; HttpOnly; SameSite=Strict; " + expires + "; path=/;";
}
// Usage
setSecureCookie("sessionToken", "abc123", 30); // Set cookie for 30 minutes

Storage Options for JWTs

LocalStorage – Available in browser APIs to store data.

Disadvantages – Vulnerable to Cross-Site Scripting (XSS) attacks since JavaScript can easily access `localStorage`.

SessionStorage – Available in browser APIs to store data but for a session.

Disadvantages – Vulnerable to XSS attacks since JavaScript can easily access `sessionStorage`.

Cookies

Advantages

 – Can be more secure if proper flags are set (e.g., `HttpOnly`, `Secure`, `SameSite`).

 – Automatic inclusion in requests to the server (no need to manually attach the token to requests).

Disadvantages

 – Susceptible to Cross-Site Request Forgery (CSRF) if not properly managed.

 – Less straightforward to implement compared to `localStorage` or `sessionStorage`.

For security reasons, storing JWTs in cookies with appropriate flags is generally recommended over using `localStorage` or `sessionStorage`.

Setting the JWT in a Secure Cookie

 document.cookie = "token=your_jwt_token; Secure; HttpOnly; SameSite=Strict; path=/;";

 – Secure: Ensures the cookie is only sent over HTTPS.

 – HttpOnly: Prevents JavaScript from accessing the cookie, mitigating XSS attacks.

 – SameSite: Helps mitigate CSRF attacks by controlling when the cookie is sent with cross-site requests. Use `Strict` or `Lax`.

Sending the JWT with Requests

 – With cookies, the browser automatically includes them in requests to the same origin, simplifying the authentication process.

💡 Additional Security Measures

Content Security Policy (CSP)

– Implement CSP to mitigate XSS attacks by restricting sources of script execution.

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; object-src 'none';">

SameSite Attribute

– Use `SameSite=Strict` or `SameSite=Lax` for cookies to prevent CSRF attacks.

Secure Your Application

– Regularly update and audit your code for vulnerabilities.
– Implement secure coding practices and keep dependencies up to date.

How cookies are sent with APIs?

There are two types of request –

  1. Same-Origin Requests – cookies are automatically included in the HTTP requests. No additional configuration is needed.

   2. Cross-Origin Requests – When making cross-origin requests, you need to configure your Angular application to include cookies. This involves setting the withCredentials property to true in your HTTP requests.

 this.http.get('https://example.com/api/data', { withCredentials: true });

Understand JavaScript Cookie

Server-Side Configuration –

 const express = require('express');
      const cors = require('cors');
      const app = express();

      app.use(cors({
      origin: 'http://your-angular-app-domain.com', // Replace with your Angular app domain
      credentials: true // Allow cookies to be included
      }));

How Cookies Are Stored on the server when sent with an HTTP request?

When cookies are sent with HTTP requests to a server, they can be stored and managed on the server side in various ways. Here’s an overview of how cookies are handled and stored on the server when received with HTTP requests:

Client Sends Cookies

 – When a client (browser) sends an HTTP request to a server, any cookies relevant to the request’s domain and path are included in the `Cookie` header of the HTTP request.

 GET /some-path HTTP/1.1
   Host: example.com
   Cookie: sessionId=abc123; username=JohnDoe

Server Receives Cookies

The server receives the HTTP request and can access the cookies from the `Cookie` header.

Server-Side Handling and Storage

The specific implementation of how cookies are handled and stored on the server can vary depending on the server technology and framework in use. Below are some common approaches for different server-side technologies.

Node.js with Express

Reading Cookies

– You can use middleware like `cookie-parser` to easily parse cookies from incoming requests.

 const express = require('express');
   const cookieParser = require('cookie-parser');
   const app = express();

   app.use(cookieParser());

   app.get('/some-path', (req, res) => {
     console.log(req.cookies); // { sessionId: 'abc123', username: 'JohnDoe' }
     // Handle the request using the cookies
   });

   app.listen(3000, () => {
     console.log('Server running on port 3000');
   });

Storing Session Data

 – If you are using cookies to manage sessions, it is common to store session data in a server-side store (e.g., memory, database, or Redis) with a session ID stored in the cookie.

const session = require('express-session');
   const RedisStore = require('connect-redis')(session);

   app.use(session({
     store: new RedisStore({ client: redisClient }),
     secret: 'your-secret-key',
     resave: false,
     saveUninitialized: false,
     cookie: { secure: true, httpOnly: true, maxAge: 60000 }
   }));

   app.get('/some-path', (req, res) => {
     // Access session data
     console.log(req.session);
     res.send('Session data accessed');
   });

Java with Spring Boot

Reading Cookies

– In Spring Boot, you can access cookies via the `HttpServletRequest`.

Storing Session Data

 – Spring Boot supports server-side session management. By default, session data is stored in the HTTP session, but it can be configured to use other stores like Redis.

Understand JavaScript Cookie

How does the Server send cookies to the Browser?

The Set-Cookie header is used in the HTTP response to instruct the browser to store a cookie.

HTTP/1.1 200 OK
Set-Cookie: sessionId=abc123; Path=/; HttpOnly; Secure; SameSite=Strict
Content-Type: text/html
const express = require('express');
const app = express();

app.get('/set-cookie', (req, res) => {
  res.cookie('sessionId', 'abc123', {
    httpOnly: true,
    secure: true, // Ensure this is true if using HTTPS
    sameSite: 'Strict',
    maxAge: 3600000 // 1 hour
  });
  res.send('Cookie set');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Summary

Cookies are a powerful tool for managing user sessions, personalizing experiences, maintaining shopping carts, tracking user behavior, delivering targeted ads, auto-filling forms, enhancing security, and localizing content. By leveraging cookies effectively, websites can offer a seamless and customized user experience.

Understand JavaScript Cookie