首先,好訊息是Google將于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/
如果因為各種原因無法升級.net core,可以使用nginx反向代理,加入如下配置即可,
這個方案只能解決Chrome,放棄掉Safari部分版本的兼容性,(本人用的這種方式)
proxy_cookie_path / "/; httponly; secure; SameSite=None;";
如果希望Chrome和Safari兼顧,可以安裝ngx_http_js_module模塊,讓nginx嗅探瀏覽器,動態去設定SameSite,參考
https://blog.csdn.net/tmyth/article/details/104340403
http://nginx.org/en/docs/http/ngx_http_js_module.html
原文地址:https://www.thinktecture.com/en/identity/samesite/prepare-your-identityserver/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/50976.html
標籤:.NET Core
上一篇:遠程終端管理和檢測系統
