All rules
CA5383Security Enabled by default: No

Ensure use secure cookies in ASP.NET Core

Ensure use secure cookies in ASP.NET Core

Microsoft docs

Description

Applications available over HTTPS must use secure cookies, which indicate to the browser that the cookie should only be transmitted using Transport Layer Security (TLS).

Cause

The Microsoft.AspNetCore.Http.CookieOptions.Secure property may be set as false when invoking Microsoft.AspNetCore.Http.IResponseCookies.Append. For now, this rule only looks at the Microsoft.AspNetCore.Http.Internal.ResponseCookies class, which is one of the implementations of Microsoft.AspNetCore.Http.IResponseCookies.

This rule is similar to CA5382, but analysis can't determine that the Microsoft.AspNetCore.Http.CookieOptions.Secure property is definitely false or not set.

By default, this rule analyzes the entire codebase, but this is configurable.

How to fix violations

Set Microsoft.AspNetCore.Http.CookieOptions.Secure property as true under all circumstances.

Example

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;

class ExampleClass
{
    public void ExampleMethod(string key, string value)
    {
        var cookieOptions = new CookieOptions();
        cookieOptions.Secure = false;
        Random r = new Random();

        if (r.Next(6) == 4)
        {
            cookieOptions.Secure = true;
        }

        var responseCookies = new ResponseCookies(null, null);
        responseCookies.Append(key, value, cookieOptions);
    }
}

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;

class ExampleClass
{
    public void ExampleMethod(string key, string value)
    {
        var cookieOptions = new CookieOptions();
        cookieOptions.Secure = true;
        var responseCookies = new ResponseCookies(null, null);
        responseCookies.Append(key, value, cookieOptions);
    }
}

When to suppress

  • If cookies are configured to be secure by default, such as using Microsoft.AspNetCore.CookiePolicy.CookiePolicyMiddleware in Startup.Configure:
  • If you're sure there's no sensitive data in the cookies.
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0