Chrome80調整SameSite策略對IdentityServer4的影響以及處理方案(翻譯)

  • 2020 年 3 月 29 日
  • 筆記

首先,好消息是Goole將於2020年2月份發佈Chrome 80版本。本次發佈將推進Google的「漸進改良Cookie」策略,打造一個更為安全和保障用戶隱私的網絡環境。

壞消息是,本次更新可能導致瀏覽器無法向服務端發送Cookie。如果你有多個不同域名的應用,部分用戶很有可能出現會話時常被打斷的情況。還有部分用戶可能無法正常登出系統。

本篇博客將處理第一個問題(無法發送cookie到服務端)。至於第二個問題(cookie無法被刪除),請參考另一篇博客

首先,SameSite是什麼

互聯網是十分開放的平台:Cookie誕生於二十多年前,於2011年修訂(RFC 6265)。當時跨站訪問攻擊(CSRF)沒有現在這麼猖獗,侵犯用戶隱私的行為也不像現在這樣泛濫。

簡而言之,Cookie標準規範規定,如果某域名下設置了Cookie,不管你是直接跳轉到該域名,或是加載了該域名的某些資源(例如圖片),或是向該域名發送POST請求,亦或將其嵌入iframe,瀏覽器訪問該域名的每次請求,都將帶上這個Cookie。

對於iframe嵌入的場景,你可能不希望瀏覽器將用戶會話cookie自動發送到服務器,因為這樣任何其他網站都可以在用戶不知情的情況下,用他的會話上下文,跟你的服務器發送請求。

為了避免這種情況,SameSite cookie規範於2016年起草。對於發送cookie我們有了更多的控制權:現在可以明確指定每個cookie是否被發送。規範引入了同站/跨站cookie的概念,如果瀏覽器訪問A域名,請求服務端也是A域名,這些cookie就叫同站cookies(same-site cookies),如果瀏覽器訪問A域名,請求服務端是B域名,這些cookie就叫跨站cookies(cross-site cookies)。

為了向後兼容,same-site的默認設置並未改變之前的行為。你必須手動指定SameSite=Lax或者SameSite=Strict,來能使用這項特性加固安全。所有的.NET框架和常見的瀏覽器都已支持這一特性。設置為Lax,大多數情況不允許發送第三方Cookie,導航到目標網址的Get請求除外。設置為Strict,完全禁止第三方Cookie,除非你之前訪問過該域名而Cookie已經存在於瀏覽器。

悲哀的是,這項新特性的採用率低的可憐(基於Chrome2019年3月份統計顯示,在所有的cookie中,只有0.1%使用了SameSite標誌)。

Google決定推進這項特性的使用。他們決定修改世界上最多人使用的瀏覽器——Chrome的默認設置:如果想保持之前處理cookie的方式,Chrome 80要求顯示指定SameSite=None。如果像以前一樣忽略SameSite屬性,Chrome將視作SameSite=Lax。

請注意:SameSite=None只有在Cookie同時被標記為Secure並且使用https連接時才會生效。

更新:如果你想知道關於SameSite cookies的更多背景知識,請擴展閱讀這篇文章

這會影響我嗎?什麼影響?

如果你有一個單頁應用(SPA),使用另一域名的認證服務(比如IdentityServer4)進行身份認證,並且使用了所謂的靜默令牌刷新的話,你將受影響。
譯者註:使用refresh_token刷新access_token,用戶無感知

登錄到認證服務的時候,它會為當前用戶設置會話cookie,這個cookie屬於認證服務域名。認證流程結束之後,另一域名會收到認證服務頒發的access token,有效期通常不會太長。當access token過期之後,應用無法訪問api,用戶需要頻繁的登錄,體驗十分差。

為了避免這一情況,我們可以使用refresh_token實現靜默刷新。應用創建一個用戶不可見的iframe,在iframe中進行新的認證流程。iframe中加載了認證服務站點,當瀏覽器發送會話cookie的時候,認證服務識別出當前用戶然後頒發新的token。

SPA網站使用iframe嵌入了認證服務站點的內容,這就是一個跨站請求,只有將iframe中屬於認證服務站點的cookie設置為SameSite=None,Chrome 80才會將iframe中的cookie發送到認證服務。否則,token靜默刷新將無法正常運行。

可能還會導致一些其他的問題:如果應用中嵌入了其他域名的資源,比如視頻自動播放設置,它們需要cookie才能正常運行。某些依賴cookie認證來訪問第三方API的應用也會出現問題。

注意:很顯然你只能修改自己服務的cookie設置。如果使用了其他域名的資源,這些不在你的控制範圍之內,你需要聯繫第三方修改他們的cookie設置。

好的,我會修改代碼將SameSite設置為None的,這樣就萬事大吉了,是嗎?

很不幸,並不是:Safari存在一個"bug"。這個bug導致Safari不會將None識別為SameSite的合法值。當Safari遇到非法參數值的時候,它會將其視作SameSite=Strict,不會向認證服務發送會話cookie。IOS13和macOS 10.15 Catalina系統上的Safari 13已修復此bug,macOS 10.14 Mojave和iOS 12將不會修復,而這幾個版本依舊存在大量用戶群。

現在我們進退兩難:要麼忽略此次更新,Chrome用戶無法使用靜默刷新,要麼設置SameSite=None,那麼無法更新到最新系統的iPhone,iPad和Mac用戶的應用將出現異常。

有沒有方法明確知道自己受影響?

幸運的是,你可以。如果你已經設置了SameSite=None,應該注意到應用在iOS 12,macOS 10.4的Safari上運行異常。如果還沒有設置的話,確保要在上面版本系統的Safari上做一下測試。

如果還沒有設置的話,可以打開Chrome的開發者工具。可以看到這些警告:

A cookie associated with a cross-site resource at {cookie domain} was set without the `SameSite` attribute.  A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`.  You can review cookies in developer tools under Application>Storage>Cookies and see more details at  https://www.chromestatus.com/feature/5088147346030592 and  https://www.chromestatus.com/feature/5633521622188032.  

如果設置了SameSite=None但是沒有Secure標識,將看到如下警告:

A cookie associated with a resource at {cookie domain} was set with `SameSite=None` but without `Secure`.  A future release of Chrome will only deliver cookies marked `SameSite=None` if they are also marked `Secure`.  You can review cookies in developer tools under Application>Storage>Cookies and  see more details at https://www.chromestatus.com/feature/5633521622188032.  

怎樣才能修復這個問題?我需要Chrome和Safari都能正常運行。

我和我的同事Boris Wilhelms做了一些研究和驗證,找到了一個解決方案。微軟的Barry Dorrans寫了一篇很不錯的博客可以參考。這個解決方案並不是完美之策,它需要在服務端嗅探瀏覽器類型,但是它很簡單,在過去幾周,我們已經用這個方案修復了數個項目。

首先我們需要確保需要通過跨站請求發送的cookie – 比如會話cookie – 被設置為SameSite=None並且標識為Secure。我們需要在項目中找到Cookie選項配置代碼,然後做出調整。這樣Chrome的問題修復了,然後Safari會出現問題。

然後我們需要將下面的類和代碼段加到項目中。這段代碼在ASP.NET Core應用中配置了一個cookie策略。這個策略會檢查cookie是否應該被設置位SameSite=None。

請注意:這個解決方案是.NET Core使用的。至於.NET Framework項目,請查看Barry Dorran的這篇博客

將這個類加到項目中

using Microsoft.AspNetCore.Builder;  using Microsoft.AspNetCore.Http;    namespace Microsoft.Extensions.DependencyInjection  {     public static class SameSiteCookiesServiceCollectionExtensions     {        /// <summary>        /// -1 defines the unspecified value, which tells ASPNET Core to NOT        /// send the SameSite attribute. With ASPNET Core 3.1 the        /// <seealso cref="SameSiteMode" /> enum will have a definition for        /// Unspecified.        /// </summary>        private const SameSiteMode Unspecified = (SameSiteMode) (-1);          /// <summary>        /// Configures a cookie policy to properly set the SameSite attribute        /// for Browsers that handle unknown values as Strict. Ensure that you        /// add the <seealso cref="Microsoft.AspNetCore.CookiePolicy.CookiePolicyMiddleware" />        /// into the pipeline before sending any cookies!        /// </summary>        /// <remarks>        /// Minimum ASPNET Core Version required for this code:        ///   - 2.1.14        ///   - 2.2.8        ///   - 3.0.1        ///   - 3.1.0-preview1        /// Starting with version 80 of Chrome (to be released in February 2020)        /// cookies with NO SameSite attribute are treated as SameSite=Lax.        /// In order to always get the cookies send they need to be set to        /// SameSite=None. But since the current standard only defines Lax and        /// Strict as valid values there are some browsers that treat invalid        /// values as SameSite=Strict. We therefore need to check the browser        /// and either send SameSite=None or prevent the sending of SameSite=None.        /// Relevant links:        /// - https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1        /// - https://tools.ietf.org/html/draft-west-cookie-incrementalism-00        /// - https://www.chromium.org/updates/same-site        /// - https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/        /// - https://bugs.webkit.org/show_bug.cgi?id=198181        /// </remarks>        /// <param name="services">The service collection to register <see cref="CookiePolicyOptions" /> into.</param>        /// <returns>The modified <see cref="IServiceCollection" />.</returns>        public static IServiceCollection ConfigureNonBreakingSameSiteCookies(this IServiceCollection services)        {           services.Configure<CookiePolicyOptions>(options =>           {              options.MinimumSameSitePolicy = Unspecified;              options.OnAppendCookie = cookieContext =>                 CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);              options.OnDeleteCookie = cookieContext =>                 CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);           });             return services;        }          private static void CheckSameSite(HttpContext httpContext, CookieOptions options)        {           if (options.SameSite == SameSiteMode.None)           {              var userAgent = httpContext.Request.Headers["User-Agent"].ToString();                if (DisallowsSameSiteNone(userAgent))              {                 options.SameSite = Unspecified;              }           }        }          /// <summary>        /// Checks if the UserAgent is known to interpret an unknown value as Strict.        /// For those the <see cref="CookieOptions.SameSite" /> property should be        /// set to <see cref="Unspecified" />.        /// </summary>        /// <remarks>        /// This code is taken from Microsoft:        /// https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/        /// </remarks>        /// <param name="userAgent">The user agent string to check.</param>        /// <returns>Whether the specified user agent (browser) accepts SameSite=None or not.</returns>        private 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.           // Notes from Thinktecture:           // Regarding https://caniuse.com/#search=samesite iOS versions lower           // than 12 are not supporting SameSite at all. Starting with version 13           // unknown values are NOT treated as strict anymore. Therefore we only           // need to check version 12.           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.           // Notes from Thinktecture:           // Regarding https://caniuse.com/#search=samesite MacOS X versions lower           // than 10.14 are not supporting SameSite at all. Starting with version           // 10.15 unknown values are NOT treated as strict anymore. Therefore we           // only need to check version 10.14.           if (userAgent.Contains("Safari")              && userAgent.Contains("Macintosh; Intel Mac OS X 10_14")              && userAgent.Contains("Version/"))           {              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.           // Notes from Thinktecture:           // We can not validate this assumption, but we trust Microsofts           // evaluation. And overall not sending a SameSite value equals to the same           // behavior as SameSite=None for these old versions anyways.           if (userAgent.Contains("Chrome/5") || userAgent.Contains("Chrome/6"))           {              return true;           }             return false;        }     }  }  

配置並啟用cookie策略

在Starup中加入下面的代碼,使用cookie策略

public void ConfigureServices(IServiceCollection services)  {     // Add this     services.ConfigureNonBreakingSameSiteCookies();  }    public void Configure(IApplicationBuilder app)  {     // Add this before any other middleware that might write cookies     app.UseCookiePolicy();       // This will write cookies, so make sure it's after the cookie policy     app.UseAuthentication();  }  

Ok,完事了嗎?

還需要做全面的測試,特別是Chrome79,以及受影響的Safari版本。
檢查一下你的靜默token刷新,還有需要cookie的跨站請求,是否正常工作。
這些都沒問題就完事了。

可以等IdentityServer4修復這個問題嗎?

不太可能。並不是IdentityServer在管理這些cookie。IdentityServer依賴於ASP.NET Core框架內置的認證系統,它們在管理會話cookie。然而微軟表示它們不能使用在ASP.NET Core直接嗅探瀏覽器版本的方案。所以基本上短期內只能靠自己了。

總結

Chrome於2020年2月發佈的新版本修改了cookie的默認行為。新版本需要SameSite明確設置為None,同時有Secure標識,才會將該cookie發送到跨站請求。如果你這麼做的話,很多版本的Safari會出現問題。

為了確保應用在所有瀏覽器運行正常,我們將所有受影響的cookie設置為Secure,SameSite=None,然後新增一個Cookie策略,根據瀏覽器版本動態處理SameSite設置。

譯者注

文中提到的方案需要設置SameSiteMode=-1,這個新增加的枚舉,需要更新微軟相補丁包,.net core2.1由於是長期維護版本微軟提供了補丁包,.net core 3.x也已經支持。如果是2.2或者其他不再維護的版本,可能需要升級到3.x。詳情見下面的博客。
https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/

原文地址:https://www.thinktecture.com/en/identity/samesite/prepare-your-identityserver/