[研究]ASP.NET WebForm,Web.config 加上<add name="X-Content-Type-Options" value="nosniff"/>,導致 Session Time Out 時自動 Logout 出錯 ? Why ?
2025-07-17
環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 20
********************************************************************************
在 ASP.NET WebForm 中,Web.config 加上:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Content-Type-Options" value="nosniff" />
</customHeaders>
</httpProtocol>
</system.webServer>
|
本意是防止 MIME 嗅探攻擊,與 Session Timeout 應無直接關聯,但實務上若發生「自動登出出錯(如跳錯頁、JavaScript 出錯、AJAX 失敗)」的情況,可能有以下間接原因:
✅ 問題可能原因分析
1. Session Timeout 對 AJAX 或 JSON 響應格式造成影響
- 假設你使用 ASP.NET WebForm + UpdatePanel、AJAX call,Session 過期時伺服器可能回傳一段 HTML 頁面(例如登入頁面)取代原本的 JSON。
- 若你的 JavaScript 嘗試 response.json() 或處理 XML,會因 Content-Type 不正確或被限制為非 sniffable 而失敗。
- X-Content-Type-Options: nosniff 告訴瀏覽器:「不要猜測檔案類型,只依 Content-Type 決定如何處理」,導致接收到錯誤格式的資料時不會 fallback,而直接拋錯。
2. ASP.NET 回傳 Login Redirect 頁面時沒正確設定 Content-Type
- 比如 Session Timeout 時跳轉登入頁,但是透過 iframe 或 XMLHttpRequest 發出的,瀏覽器本應根據回傳 Content-Type 判斷型態,但 nosniff 禁止它這樣做。
3. 登入頁面或 Timeout 頁面非 HTML,但標頭設定錯誤
- 有些登入頁面可能設定為 Content-Type: text/plain 或 application/json,但實際回傳 HTML,造成 nosniff 阻止瀏覽器解讀為 HTML,導致畫面空白或亂碼。
🔧 解法建議
✅ 方式一:針對登入頁或 AJAX 錯誤處理改善
- 確保 Session Timeout 時回傳的頁面有正確的 Content-Type(例如 text/html)。
- 在 AJAX call 中加入對 HTTP 302(重導)或 Session Timeout 狀況的偵測與處理。
- 若是 ASP.NET WebForm,處理 Application_EndRequest 或 Session_End,加入判斷。
✅ 方式二:針對 AJAX / JSON API 分開處理 Content-Type
- 對 X-Content-Type-Options: nosniff 的設定進行條件排除,例如只加在靜態資源請求上(如 .js, .css, .svg),而非所有頁面。
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
var path = HttpContext.Current.Request.Path.ToLower();
if (path.EndsWith(".js") || path.EndsWith(".css") || path.EndsWith(".svg"))
{
Response.Headers.Set("X-Content-Type-Options", "nosniff");
}
}
|
🔍 小結
| 問題 | 原因 |
| Session Timeout 時自動 Logout 出錯 | 回傳的 Content-Type 不正確 + nosniff 導致瀏覽器無法解讀 |
| 常見現象 | 畫面空白、AJAX 錯誤、登入頁無法正確顯示 |
********************************************************************************
(完)
相關
沒有留言:
張貼留言