Security BasicsJanuary 5, 202412 min read

Cookie Security: Secure, HttpOnly, and SameSite Explained

Deep dive into cookie security flags and how to properly implement them to prevent session hijacking and CSRF attacks.

By zdelab Team

Cookie Security: Secure, HttpOnly, and SameSite Explained


Cookies are essential for web applications, enabling session management, user preferences, and authentication. However, improperly configured cookies can expose your application to serious security vulnerabilities. This guide explains the three critical cookie security flags: Secure, HttpOnly, and SameSite.


Understanding Cookie Security Flags


Cookie security flags are attributes that control how cookies behave and who can access them. Properly configured flags prevent:

  • Session hijacking
  • Cross-Site Scripting (XSS) attacks
  • Cross-Site Request Forgery (CSRF) attacks
  • Man-in-the-middle attacks

  • The Secure Flag


    What It Does


    The Secure flag ensures cookies are only sent over HTTPS connections, never over unencrypted HTTP.


    Why It Matters


    Without the Secure flag, cookies can be intercepted during transmission over unencrypted connections, allowing attackers to steal session tokens and impersonate users.


    Implementation


    JavaScript:

    document.cookie = "sessionId=abc123; Secure; SameSite=Strict";

    Server-Side (Express.js):

    res.cookie('sessionId', 'abc123', {
      secure: true,
      httpOnly: true,
      sameSite: 'strict'
    });

    PHP:

    setcookie('sessionId', 'abc123', [
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Strict'
    ]);

    Python (Flask):

    response.set_cookie('sessionId', 'abc123', secure=True, httponly=True, samesite='Strict')

    The HttpOnly Flag


    What It Does


    The HttpOnly flag prevents JavaScript from accessing the cookie via document.cookie, making it inaccessible to client-side scripts.


    Why It Matters


    This flag protects against XSS attacks. Even if an attacker injects malicious JavaScript, they cannot steal HttpOnly cookies.


    Implementation


    Important: HttpOnly cookies can only be set server-side, not via JavaScript.


    Express.js:

    res.cookie('sessionId', 'abc123', {
      httpOnly: true,
      secure: true,
      sameSite: 'strict'
    });

    PHP:

    setcookie('sessionId', 'abc123', [
        'httponly' => true,
        'secure' => true,
        'samesite' => 'Strict'
    ]);

    Testing


    Try accessing an HttpOnly cookie via JavaScript:

    console.log(document.cookie); // HttpOnly cookies won't appear

    The SameSite Flag


    What It Does


    The SameSite flag controls when cookies are sent with cross-site requests, providing protection against CSRF attacks.


    Values


    1. Strict: Cookie is never sent with cross-site requests

    2. Lax: Cookie is sent with top-level navigation (GET requests)

    3. None: Cookie is always sent (requires Secure flag)


    SameSite=Strict


    Best for: Session cookies, authentication tokens


    Behavior:

  • Cookie is only sent with same-site requests
  • Provides maximum CSRF protection
  • May break functionality if users navigate from external links

  • Example:

    res.cookie('sessionId', 'abc123', {
      sameSite: 'strict',
      secure: true,
      httpOnly: true
    });

    SameSite=Lax


    Best for: Most cookies, balance between security and functionality


    Behavior:

  • Cookie is sent with same-site requests
  • Cookie is sent with top-level GET requests (user clicks a link)
  • Cookie is NOT sent with cross-site POST requests (prevents CSRF)
  • Cookie is NOT sent in iframes

  • Example:

    res.cookie('preferences', 'dark-mode', {
      sameSite: 'lax',
      secure: true,
      httpOnly: true
    });

    SameSite=None


    Best for: Third-party integrations, embedded widgets


    Behavior:

  • Cookie is always sent with requests
  • Requires Secure flag
  • Use only when necessary

  • Example:

    res.cookie('thirdPartyId', 'xyz789', {
      sameSite: 'none',
      secure: true, // Required when SameSite=None
      httpOnly: true
    });

    Recommended Cookie Configurations


    Session/Authentication Cookies


    {
      secure: true,
      httpOnly: true,
      sameSite: 'strict',
      maxAge: 3600000 // 1 hour
    }

    User Preference Cookies


    {
      secure: true,
      httpOnly: true,
      sameSite: 'lax',
      maxAge: 31536000000 // 1 year
    }

    Third-Party Cookies (if necessary)


    {
      secure: true,
      httpOnly: true,
      sameSite: 'none',
      maxAge: 86400000 // 1 day
    }

    Common Vulnerabilities


    1. Missing Secure Flag


    Risk: Cookies sent over HTTP can be intercepted


    Fix: Always set secure: true in production


    2. Missing HttpOnly Flag


    Risk: XSS attacks can steal cookies


    Fix: Set httpOnly: true for sensitive cookies


    3. Incorrect SameSite Configuration


    Risk: CSRF attacks or broken functionality


    Fix: Use strict for auth cookies, lax for most others


    4. SameSite=None Without Secure


    Risk: Browsers will reject the cookie


    Fix: Always use secure: true with sameSite: 'none'


    Testing Cookie Security


    Browser DevTools


    1. Open DevTools → Application/Storage → Cookies

    2. Check cookie flags

    3. Verify Secure, HttpOnly, and SameSite values


    Automated Testing


    Use security scanners to check cookie configurations:

  • OWASP ZAP
  • Burp Suite
  • Custom security headers checks

  • Migration Guide


    Updating Existing Cookies


    1. Add Secure flag (if using HTTPS)

    2. Add HttpOnly flag (for sensitive cookies)

    3. Set SameSite (start with 'lax', move to 'strict' if possible)


    Handling Legacy Browsers


    Some older browsers don't support SameSite. Consider:

  • Feature detection
  • Progressive enhancement
  • Fallback mechanisms

  • Best Practices Summary


    1. ✅ Always use Secure flag in production

    2. ✅ Use HttpOnly for sensitive cookies

    3. ✅ Prefer SameSite=Strict for authentication

    4. ✅ Use SameSite=Lax as default

    5. ✅ Only use SameSite=None when necessary

    6. ✅ Set appropriate expiration times

    7. ✅ Use strong, random session IDs

    8. ✅ Rotate session tokens regularly


    Conclusion


    Proper cookie security is essential for protecting user sessions and preventing common web attacks. By implementing Secure, HttpOnly, and SameSite flags correctly, you can significantly improve your application's security posture.


    Remember:

  • Secure: Always use HTTPS
  • HttpOnly: Protect against XSS
  • SameSite: Protect against CSRF

  • Stay secure, protect your users!

    Found this helpful?

    Scan your web application for security vulnerabilities and get actionable insights.