事件起因:
公司正在做一個sso的單點登錄的項目,做完之后,在測試階段,不同的終端的兼容測試時候,好幾個不同的瀏覽器出現了不同的問題,有登錄之后自動退出,有登陸不成功等問題。
在 pc 端只有 uc 瀏覽器不成功,移動端有 safari、360瀏覽器、qq瀏覽器、uc瀏覽器等。
結果排查:
后面具體查詢,發現是由於后端在請求響應頭設置 set-cookie 來處理 cookie 數據沒有生效。由於數據沒有正常寫入 cookie 中,導致了上面各瀏覽器登錄不成功的問題。
問題解決:
而最終引發問題的原因是 set-cookie 中的 samesite 的兼容性引起的。
http://www.ruanyifeng.com/blog/2019/09/cookie-samesite.html 阮一峰老師對於 samesite 的介紹。
samesite 的出現是為了解決 CSRF 攻擊和用戶追蹤。
后面又查到了這篇文章:https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
上面詳細介紹了 samesite 的前世今生及經測試過非規范的瀏覽器兼容列表以及處理方案:
public static bool DisallowsSameSiteNone(string userAgent) { if (string.IsNullOrEmpty(userAgent)) { return false; } // 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; }
處理方法:
if (options.SameSite == SameSiteMode.None) { var userAgent = httpContext.Request.Headers["User-Agent"].ToString(); // TODO: Use your User Agent library of choice here. if (DisallowsSameSiteNone(userAgent)) {
// For .NET Core < 3.1 set SameSite = (SameSiteMode)(-1)
options.SameSite = SameSiteMode.Unspecified;
}
}
在不能識別 samesite 新值的,瀏覽器版本中,set-cookie 中的 samesite 值設為 -1,在前端請求頭中,將發現 set-cookie 的值中已沒有了samesite 配置。
UC瀏覽器截圖:
chrome瀏覽器截圖: