C#idiomatic C#
ca5396fundamentals/code-analysis/quality-rules

Code analysis

CA5396: Set HttpOnly to true for HttpCookie

Provides information about code analysis rule CA5396, including causes, how to fix violations, and when to suppress it.

CA5396 Security enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

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 System.Web.HttpCookie.HttpOnly is set, such as in the following example:

    xml
    <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.

csharp
#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.

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

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

Example

Violation:

csharp
using System.Web;

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

Solution:

csharp
using System.Web;

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