CA5396: Set HttpOnly to true for HttpCookie

Property Value
Rule ID CA5396
Title Set HttpOnly to true for HttpCookie
Category Security
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

Cause

System.Web.HttpCookie.HttpOnly is set to false. The default value of this property is false.

Rule description

As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies.

How to fix violations

Set System.Web.HttpCookie.HttpOnly to true.

When to suppress warnings

  • If the global value of HttpOnly is set, such as in the following example:

    <system.web>
        ...
        <httpCookies httpOnlyCookies="true" requireSSL="true" />
    </system.web>
    
  • If you're sure there's no sensitive data in the cookies.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA5396
// The code that's violating the rule is on this line.
#pragma warning restore CA5396

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA5396.severity = none

For more information, see How to suppress code analysis warnings.

Example

Violation:

using System.Web;

class ExampleClass
{
    public void ExampleMethod()
    {
        HttpCookie httpCookie = new HttpCookie("cookieName");
        httpCookie.HttpOnly = false;
    }
}

Solution:

using System.Web;

class ExampleClass
{
    public void ExampleMethod()
    {
        HttpCookie httpCookie = new HttpCookie("cookieName");
        httpCookie.HttpOnly = true;
    }
}