Cookie ‘HttpOnly’ attribute is not set to true¶
ID: cs/web/cookie-httponly-not-set
Kind: problem
Security severity: 5.0
Severity: warning
Precision: high
Tags:
- security
- external/cwe/cwe-1004
Query suites:
- csharp-code-scanning.qls
- csharp-security-extended.qls
- csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Cookies without the HttpOnly flag set are accessible to client-side scripts such as JavaScript running in the same origin. In case of a Cross-Site Scripting (XSS) vulnerability, the cookie can be stolen by a malicious script. If a sensitive cookie does not need to be accessed directly by client-side JS, the HttpOnly flag should be set.
Recommendation¶
Set the HttpOnly flag to true for authentication cookies to ensure they are not accessible to client-side scripts.
When using ASP.NET Core, CookiePolicyOptions can be used to set a default policy for cookies. When using ASP.NET Web Forms, a default may also be configured in the Web.config file, using the httpOnlyCookies attribute of the the <httpCookies> element.
Example¶
In the example below, Microsoft.AspNetCore.Http.CookieOptions.HttpOnly is set to true.
class MyController : Controller
{
void Login()
{
var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { HttpOnly = true };
Response.Cookies.Append("auth", "secret", cookieOptions);
}
}
In the following example, CookiePolicyOptions are set programmatically to configure defaults.
public class Startup
{
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCookiePolicy(new CookiePolicyOptions()
{
Secure = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always,
HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always
});
}
}
In the example below, System.Web.HttpCookie.HttpOnly is set to true.
class MyController : Controller
{
void Login()
{
var cookie = new System.Web.HttpCookie("cookieName") { HttpOnly = true };
}
}
In the example below, the httpOnlyCookies attribute is set to true in the Web.config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<httpCookies httpOnlyCookies="true"/>
</system.web>
</configuration>
References¶
ASP.Net Core docs: CookieOptions.HttpOnly Property.
MDN: Set-Cookie Header.
Web Forms docs: HttpCookie.HttpOnly Property.
Web Forms docs: httpCookies Element.
PortSwigger: Cookie without HttpOnly flag set
Common Weakness Enumeration: CWE-1004.