Upcoming SameSite Cookie Changes in ASP.NET and ASP.NET Core

Avatar

Barry

SameSite is a 2016 extension to HTTP cookies intended to mitigate cross site request forgery (CSRF). The original design was an opt-in feature which could be used by adding a new SameSite property to cookies. It had two values, Lax and Strict. Setting the value to Lax indicated the cookie should be sent on navigation within the same site, or through GET navigation to your site from other sites. A value of Strict limited the cookie to requests which only originated from the same site. Not setting the property at all placed no restrictions on how the cookie flowed in requests. OpenIdConnect authentication operations (e.g. login, logout), and other features that send POST requests from an external site to the site requesting the operation, can use cookies for correlation and/or CSRF protection. These operations would need to opt-out of SameSite, by not setting the property at all, to ensure these cookies will be sent during their specialized request flows.

Google is now updating the standard and implementing their proposed changes in an upcoming version of Chrome. The change adds a new SameSite value, “None”, and changes the default behavior to “Lax”. This breaks OpenIdConnect logins, and potentially other features your web site may rely on, these features will have to use cookies whose SameSite property is set to a value of “None”. However browsers which adhere to the original standard and are unaware of the new value have a different behavior to browsers which use the new standard as the SameSite standard states that if a browser sees a value for SameSite it does not understand it should treat that value as “Strict”. This means your .NET website will now have to add user agent sniffing to decide whether you send the new None value, or not send the attribute at all.

.NET will issue updates to change the behavior of its SameSite attribute behavior in .NET 4.7.2 and in .NET Core 2.1 and above to reflect Google’s introduction of a new value. The updates for the .NET Framework will be available on December 10th. .NET Core updates will be available with .NET Core 3.1 starting with preview 1, in early November. .NET 3.0 and 2.1 updates will release on 19th November.

.NET Core 3.1 will contain an updated enum definition, SameSite.Unspecified which will not set the SameSite property.

The OpenIdConnect middleware for Microsoft.Owin v4.1 and .NET Core will be updated at the same time as their .NET Framework and .NET updates, however we cannot introduce the user agent sniffing code into the framework, this must be implemented in your site code. The implementation of agent sniffing will vary according to what version of ASP.NET or ASP.NET Core you are using and the browsers you wish to support.

For ASP.NET 4.7.2 with Microsoft.Owin 4.1.0 agent sniffing can be implemented using ICookieManager;

public class SameSiteCookieManager : ICookieManager
{
  private readonly ICookieManager _innerManager;

  public SameSiteCookieManager() : this(new CookieManager())
  {
  }

  public SameSiteCookieManager(ICookieManager innerManager)
  {
    _innerManager = innerManager;
  }

  public void AppendResponseCookie(IOwinContext context, string key, string value,
                                   CookieOptions options)
  {
    CheckSameSite(context, options);
    _innerManager.AppendResponseCookie(context, key, value, options);
  }

  public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
  {
    CheckSameSite(context, options);
    _innerManager.DeleteCookie(context, key, options);
  }

  public string GetRequestCookie(IOwinContext context, string key)
  {
    return _innerManager.GetRequestCookie(context, key);
  }

  private void CheckSameSite(IOwinContext context, CookieOptions options)
  {
    if (options.SameSite == SameSiteMode.None && DisallowsSameSiteNone(context))
    {
        options.SameSite = null;
    }
  }

  public static bool DisallowsSameSiteNone(IOwinContext context)
  {
    // TODO: Use your User Agent library of choice here.
    var userAgent = context.Request.Headers["User-Agent"];
    return userAgent.Contains("BrokenUserAgent") ||
           userAgent.Contains("BrokenUserAgent2")
  }
}

And then configure OpenIdConnect settings to use the new CookieManager;

app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
    // … Your preexisting options … 
    CookieManager = new SameSiteCookieManager(new SystemWebCookieManager())
});

SystemWebCookieManager will need the .NET 4.7.2 or later SameSite patch installed to work correctly.

For ASP.NET Core you should install the patches and then implement the agent sniffing code within a cookie policy. For versions prior to 3.1 replace SameSiteMode.Unspecified with (SameSiteMode)(-1).

private void CheckSameSite(HttpContext httpContext, CookieOptions options)
{
    if (options.SameSite == SameSiteMode.None)
    {
        var userAgent = httpContext.Request.Headers["User-Agent"].ToString();
        // TODO: Use your User Agent library of choice here.
        if (/* UserAgent doesn’t support new behavior */)
        {
               // For .NET Core < 3.1 set SameSite = (SameSiteMode)(-1)
               options.SameSite = SameSiteMode.Unspecified;
         }
    }
}

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
        options.OnAppendCookie = cookieContext => 
            CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
        options.OnDeleteCookie = cookieContext => 
            CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
    });
}

public void Configure(IApplicationBuilder app)
{
    app.UseCookiePolicy(); // Before UseAuthentication or anything else that writes cookies.
    app.UseAuthentication();
    // …
}

Under testing with the Azure Active Directory team we have found the following checks work for all the common user agents that Azure Active Directory sees that don’t understand the new value.

public static bool DisallowsSameSiteNone(string userAgent)
{
    // Cover all iOS based browsers here. This includes:
    // - Safari on iOS 12 for iPhone, iPod Touch, iPad
    // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad
    // - Chrome on iOS 12 for iPhone, iPod Touch, iPad
    // All of which are broken by SameSite=None, because they use the iOS networking stack
    if (userAgent.Contains("CPU iPhone OS 12") || userAgent.Contains("iPad; CPU OS 12"))
    {
        return true;
    }

    // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes:
    // - Safari on Mac OS X.
    // This does not include:
    // - Chrome on Mac OS X
    // Because they do not use the Mac OS networking stack.
    if (userAgent.Contains("Macintosh; Intel Mac OS X 10_14") && 
        userAgent.Contains("Version/") && userAgent.Contains("Safari"))
    {
        return true;
    }

    // Cover Chrome 50-69, because some versions are broken by SameSite=None, 
    // and none in this range require it.
    // Note: this covers some pre-Chromium Edge versions, 
    // but pre-Chromium Edge does not require SameSite=None.
    if (userAgent.Contains("Chrome/5") || userAgent.Contains("Chrome/6"))
    {
        return true;
    }

    return false;
}

This browser list is by no means canonical and you should validate that the common browsers and other user agents your system supports behave as expected once the update is in place.

Chrome 80 is scheduled to turn on the new behavior in February or March 2020, including a temporary mitigation added in Chrome 79 Beta. If you want to test the new behavior without the mitigation use Chromium 76. Older versions of Chromium are available for download.

If you cannot update your framework versions by the time Chrome turns the new behavior in early 2020 you may be able to change your OpenIdConnect flow to a Code flow, rather than the default implicit flow that ASP.NET and ASP.NET Core uses, but this should be viewed as a temporary measure.

We strongly encourage you to download the updated .NET Framework and .NET Core versions when they become available in November and start planning your update before Chrome’s changes are rolled out.

Avatar
Barry Dorrans

Follow Barry   

47 comments

  • Avatar
    Alan Miers

    This seems to be affecting me today.
    Chrome browser version 78.0.3904.70
    when running locally (localhost)
    authenticating against AAD.

  • Rowan Merewood
    Rowan Merewood

    A minor correction to:
    However browsers which adhere to the original standard and are unaware of the new value have a different behavior to browsers which use the new standard as the SameSite standard states that if a browser sees a value for SameSite it does not understand it should treat that value as “Strict”.

    This is the bug in iOS and MacOS: https://bugs.webkit.org/show_bug.cgi?id=198181 It does not correspond to earlier versions of the standard.

    However, that earlier version: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-02 does still state the following:
    If the “SameSite” attribute’s value is neither of these, the cookie will be ignored.

    This is the behaviour exhibited by browsers implementing the previous version of the spec and is still incompatible, just with a slightly different effect of rejecting the cookie entirely.

  • Collin B
    Collin B

    “.NET will issue updates to change the behavior of its SameSite attribute behavior in .NET 4.7.2 and in .NET Core 2.1 and above…”

    I think you meant .NET Core 3.1?

  • Todd Snyder
    Todd Snyder

    Checking to see if there will be an updated blog post when the fix is available? Or an ETA when Microsoft.Owin 4.1.0 will be released?

    Plus, has anyone had any luck with setting the chrome flags. With Chrome 76 we were able to set the flags and see an error coming back from OpenId/Microsoft.Owin. With the latest version (Chrome 78), Chrome Beta 79 and the canary version of Chrome 80 setting the flags no longer raises an error. We do still see the warnings in Chrome console.

    • Avatar
      Barry Dorrans

      Unfortunately circumstances outside our control have pushed back the release until January. We’re still trying to figure out if we can release 4.8 earlier but it’s not looking hopeful.

      The flags contain a temporary time based mitigation, where if a post comes within a short period of time Chrome will let it all happen. This will go away in future versions.

      • Todd Snyder
        Todd Snyder

        Thanks for the update. Do you have a better ETA on when the release will be available in January, if not at least a date when we might get a more confirmed release date?

        Are there other options that customers could pursue to work around the issue?

          • Avatar
            Robert Slaney

            Doesn’t leave a lot of time to patch codebases, get through test cycles and into production. Many orgs have deployment/code freezes over the XMas/New Year period due to reduced resources.

            Will the fix include the System.Web cookie handler, not just Owin. We had to ditch the native Owin cookie handler and forward cookie handling back to System.Web. ASP.NET was (seemingly) randomly clearing the OWIN set-cookie headers.

  • Clement Gutel
    Clement Gutel

    Would the asp.net team provide a nuget package with this cookie policy so that we can easily add this into our projects?

    • Avatar
      Barry Dorrans

      The browser sniffing code? No, we won’t.

      I don’t know if you remember browsercap.ini, but it was a file in asp.net which used to user browser agents to provide information about whether a browser supported features like javascript, frames and so on. It had no update mechanism other than a new version of the .NET Framework which shipped maybe once a year at most, so it was woefully out of date always.

      The sniffing code is very much like that. We can’t auto update it, we don’t know what browsers you care about, and we don’t want to make assumptions that may work for one customer but not for another. So we’ll provide sample code for you to use and customise, with the browser strings that Azure Active Directory have helped us with, the ones they see, but we won’t be providing this in binary form.

      • Clement Gutel
        Clement Gutel

        Thanks for the quick answer, I see what you’re saying.
        I wasn’t expecting an official Microsoft.* package but it seems like some sort of unofficial/unsupported community package would be useful rather than everyone tweaking their own sniffing logic…

  • Clement Gutel
    Clement Gutel

    As an alternative solution, how about issuing 2 cookies?
    One with SameSiteMode.Unspecified and one with SameSiteMode.None.
    At least one of the two cookies should be sent, regardless of the standard version implement by the browser.
    Obviously, the code would need to change to be aware of the 2 cookies, but at least it doesn’t rely on user agent sniffing.

    • Avatar
      Barry Dorrans

      We thought about that, but that would mean everyone having to wait on every component to get updated. With the approach we choose it doesn’t matter if your third party component is unaware of the changes, the central cookie handling will take over and do the right thing.

        • Avatar
          Barry Dorrans

          And that’s a single scenario. Which, depending on the number of claims in your auth cookie, may break under iOS due to stricter limitations on the size of cookies a single domain can issue. Which is then doubled by issuing double cookies.

          By using the single extension point we can support multiple scenarios, multiple libraries which write cookies and which have not, or cannot be updated.

          • Clement Gutel
            Clement Gutel

            Got it, but if we implement the double cookie ourselves (I really don’t want to sniff the agent), this should work fine, right?
            (We have a low number of claims and our cookies are pretty small so size is unlikely to be a problem for us…)

          • Avatar
            Barry Dorrans

            For some reason wordpress isn’t letting me reply to your newer comment.

            You could yes, if you wrote your own cookie auth handler.

      • Avatar
        Dominik Rauch

        @Barry Dorrans: According to the experts at Auth0 (https://auth0.com/blog/browser-behavior-changes-what-developers-need-to-know/) you should definitely go for the recommended Google workaround as browser sniffing does not work in all scenarios.

        See especially:

        We could use UA Sniffing to detect Chrome 80+ and only apply SameSite=None for that, right? Again, not as simple. Due to the WebKit bug forever present on iOS 12, you’d also need to factor in the operating system major version and the rendering engine. Plus, other browser vendors are already signaling that they’ll be adopting these changes. In time, when this becomes an official standard, all browsers will. We’re seeking a solution with few drawbacks that works on all browsers, regardless of their age, vendor, operating system, or rendering engine.

        So please go for the multi-cookie approach!

        Best regards,
        D.R.

        • Avatar
          Barry Dorrans

          Double cookies have their own problems especially for mobile browsers, and Auth0 entirely controls their stack and don’t have a framework that other people write code against. For us this is the best approach, the one we chose, and the one we have shipped.

          • Avatar
            Dominik Rauch

            So the only problem is mobile browsers? => What problems exactly?

            For us this is the best approach

            If you’re reading the Auth0 article, you’ll recognize that browser sniffing is simply not going to work. Don’t know why you opted for this “best approach”. Is there a GitHub issue with more background information about your decision process and all the pros/cons? If I read the Auth0 article correctly, nobody can use your proposed solution without running into problems.

            Best regards,
            D.R.

          • Avatar
            Barry Dorrans

            For some reason wordpress isn’t letting me reply to your newer comment.

            There is no github issue, this approach spans more than the open source .NET Core, and the decision was made taking into account the concerns of multiple products internally and the multiple browser scenarios they have to decide. Auth0’s requirements are simpler, they just have to support Auth0, and customers than can update their single library. .NET cannot limit themselves to that scenario.

          • Avatar
            Dominik Rauch

            (I can’t reply to your last comment either…)

            OK, if you have an application which does not run into max cookie count problems then the double cookie policy is probably the best solution. Unfortunate, that ASP.NET Core doesn’t allow you to choose but recommends a single “best for everyone” solution. But I can see that it is too late now to change this decision.

            I’ve created a GitHub issue on how to implement the double cookie policy ourselves.

            Best regards,
            D.R.

          • Avatar
            Robert Slaney

            Taking into account the chunking cookie manager to get around individual set-cookie header limits, this becomes an absolute nightmare is we have to double up every cookie

            The list of strict samesite 2016 spec browsers is small and doesn’t force double cookies on the other 99% of browsers

          • Avatar
            Barry Dorrans

            I don’t disagree Robert, but the ship date is out of our control. After much discussion you’ll see the patches arrive today at 10am.

  • Chris DaMour
    Chris DaMour

    with this change the behaviour went in .net core from None meaning DO NOT set samesite param to set it as samesite=none.

    https://github.com/aspnet/AspNetCore/pull/13858/files

    this made the suggested fixes for https://github.com/aspnet/AspNetCore/issues/4647 completely uneffective. This is the iOS 12/safari 12 bug where it interprets samesite=none as strict. That’s quite a backwards incompatible change.

    I think this was a mistake as we’re breaking behaviour within a patch version. Why wasn’t this done as an opt in? at the very least the docs for asp.net core no longer are correct

    https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.samesitemode?view=aspnetcore-2.1 -> “None 0 No SameSite field will be set, the client should follow its default cookie policy.”

    ditto https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.samesitemode?view=aspnetcore-2.2 (and all the way to 3.0 the docs for 3.1 seem to be missing).

    This is contrast to asp.net https://docs.microsoft.com/en-us/dotnet/api/system.web.samesitemode?view=netframework-4.7.2 that makes mentions of the the behaviour changing.

    This really sucks because all of a sudden my app is now adding samesite=none to openidconnect cookies when i explicitly did not want them because of iOS 12 users who can’t work with em.

    Note to whoever if you want to opt out of this change for now https://docs.microsoft.com/en-us/dotnet/core/compatibility/aspnetcore#opt-out-switches

    • Avatar
      Barry Dorrans

      Unfortunately we’re damned if we do and damned if we don’t, hence the documented browser sniffing approach.

      If we don’t update we lock out Chrome, if we do you have to do some work to support older browsers. We took the path that supports the more popular browsers by default. While you can opt-out for now, or not install the update on your servers (its not a security update) you will have to do something before Chrome implements its incompatible change.

  • Avatar
    Kevin Jones

    Hi Barry,

    I see here that you say the updates should drop on Dec 10th. Is that only for Framework. I can’t see an update to ASP.NetCore 2.1 in Nuget, should I expect to see that and if so when?

    Thanks

  • Avatar
    Jaap Mosselman

    I have .NET Framework 4.7 ASP.NET MVC application using Owin with Owin Ws-Federation for AAD authentication. After the .NET Framework update was installed on the server last week, we could not authenticate with AAD in some cases. I updated to Owin 4.1 but that did not fix the problem.
    When I used Chrome (79) it dit not work, but when I use Edge it just works.
    So I analyzed by debugging the application (got Owin code locally to debug it). What I saw was that the /signing-federation POST callback is just there with the correct information. The Owin Ws-Federation middleware sets the .AspNet.External cookie with the identity. But for some reason that cookie seems to be left out from the actual written response. With Chrome it is not in the response. With Edge it is. I looked even with Fiddler to the response to verify that. I can’t see why it would be UA dependent. So it seems randomly. In my opinion this has nothing to do with the SameSite changes which just should do something with a value inside the cookie.
    I noticed also that Robert Slaney in a previous comment mentioned something about Owin Cookies randomly removed. No idea if this is the same problem.
    Any idea what’s going on here?

  • Avatar
    Rune Moberg

    I tried this in my web.config:

    <httpCookies sameSite=”none” requireSSL=”true” />

    But it gets ignored. IIS still sets this cookie:

    set-cookie: ASP.NET_SessionId=a5hrhikf5wvykxw3gxeqtph1; path=/; secure; HttpOnly; SameSite=Lax

    as Lax. Which causes problems down the road when I get a POST back from the site taking care of SSO for us.

    Edit: Never mind! Found the correct invocation:

    <sessionState cookieSameSite=”None” />

  • Robert Slaney
    Robert Slaney

    It looks like the AntiForgeryToken system in MVC 5 ( via Microsoft.AspNet.WebPages ) hasn’t been updated for samesite. It’s still writing directly to ASP.NET’s response cookies without any samesite value.

    Should the AntiForgeryConfig static class be updated ?

  • Avatar
    Martin Brown

    We’re having trouble with deploying this with an Azure Web App.

    The site being deployed targets .Net 4.7.2, and the changes work when tested locally as expected.

    If we decompile the System.Web.dll (downloaded through Kudu) we’re seeing an older version that doesn’t handle samesite cookies.

    This appears to be an issue for others (with 4.7.2 despite the 4.8 topic).

    https://feedback.azure.com/forums/169385-web-apps/suggestions/37566262-upgrade-app-service-with-net-4-8

    Would the expectation be that Azure would have also been patched now? The timestamp on the System.Web.dll is 11/12/2019 but decompiled seeing:

                if (this._sameSite != SameSiteMode.None)
                {
                    stringBuilder.Append("; SameSite=");
                    stringBuilder.Append(this._sameSite);
                }
  • Jose Rivas
    Jose Rivas

    We Have an app running on 4.8. implemented the same-site fix. it works locally but when deployed to the server the user-agent is not there. so it fails.
    any idea as to why? local is iisExpress and server is windows server 2016 with iis10. server also has 4.8 runtime. all owin packages are updated to 4.1..

Leave a comment