EF: ObjectContext and DbContext :👈 👉:Web API Best Practices

Cookies in ASP.NET

When Do We Use Cookies?

Cookies are small pieces of data stored by a web browser on a user's device. Websites use cookies to maintain information between HTTP requests because HTTP is inherently stateless.

Common Uses of Cookies

  • Authentication: Maintaining a user's authenticated session through a protected authentication cookie.
  • User preferences: Remembering language, theme, or other display preferences.
  • Session management: Identifying a user's session using a session identifier.
  • Personalization: Remembering selected settings or preferences.
  • Analytics: Understanding website usage, subject to applicable privacy requirements and user consent.

Example in ASP.NET MVC

public ActionResult SetPreference()
{
    HttpCookie cookie = new HttpCookie("Theme", "Dark");

    cookie.Expires = DateTime.Now.AddDays(7);
    cookie.HttpOnly = true;
    cookie.Secure = Request.IsSecureConnection;
    cookie.Path = "/";

    Response.Cookies.Add(cookie);

    return Content("Cookie created successfully.");
}

To read the cookie:

public ActionResult GetPreference()
{
    HttpCookie cookie = Request.Cookies["Theme"];

    if (cookie != null)
    {
        return Content("Selected theme: " + cookie.Value);
    }

    return Content("No theme preference found.");
}

Important: The example demonstrates the cookie API. In a production application, use HTTPS and set the Secure flag appropriately. For authentication cookies, also configure HttpOnly, Secure, and an appropriate SameSite policy. Do not store passwords, access tokens, or other sensitive information in ordinary cookies.


Explain How Cookies Work. Give an Example of Cookie Abuse.

How Cookies Work

Cookies allow a website to associate information with subsequent requests from the same browser.

  1. Step 1 — Server creates a cookie: The server sends an HTTP response containing a Set-Cookie header.
  2. Step 2 — Browser stores the cookie: The browser stores it according to its expiration, domain, path, and security settings.
  3. Step 3 — Browser sends the cookie: For subsequent matching requests, the browser includes the cookie in the HTTP Cookie header.
  4. Step 4 — Server reads the cookie: The server uses the cookie value to retrieve a preference, identify a session, or perform another permitted operation.

Example HTTP Exchange

Server response:

HTTP/1.1 200 OK
Set-Cookie: Theme=Dark; Path=/; Secure; HttpOnly; SameSite=Lax

Subsequent browser request:

GET /Home/Index HTTP/1.1
Cookie: Theme=Dark

The browser sends the cookie automatically when the request matches the cookie's scope and security rules.

Example of Cookie Abuse

Session hijacking is one example of cookie abuse. If an attacker obtains a valid session cookie belonging to another user, the attacker may be able to impersonate that user until the session expires or is invalidated.

Other cookie-related risks include:

  • Cross-site scripting (XSS): Malicious script may steal cookies that are accessible to JavaScript if the application has an XSS vulnerability.
  • Session fixation: An attacker may attempt to make a victim use a session identifier known to the attacker.
  • Cross-site request forgery (CSRF): A browser may automatically send authentication cookies with a forged request if appropriate protections are missing.
  • Cookie tampering: A user may modify a client-side cookie value. The application must not trust unvalidated cookie contents.

How to Protect Cookies

  • Use HTTPS and set the Secure flag.
  • Set HttpOnly for cookies that do not need to be accessed by JavaScript.
  • Configure an appropriate SameSite policy.
  • Regenerate session identifiers after authentication or privilege changes.
  • Use anti-forgery protection for state-changing requests where appropriate.
  • Validate or cryptographically protect client-controlled data.
  • Expire and invalidate sessions appropriately, especially after logout.

Interview point: Cookies are not inherently secure or insecure. Their security depends on their contents, configuration, transport, and how the server validates and uses them.

🔙
EF: ObjectContext and DbContext :👈 👉:Web API Best Practices