使用者點擊「登出」後,瀏覽器快取仍保留受保護頁面。按「返回鍵」無需重新驗證即可進入,造成資安風險。尤其在 iPad、Android 瀏覽器上更明顯。
| 方案 | 核心做法 | 優點 | 缺點 |
|---|---|---|---|
| 1. 禁用快取 | Response.Cache.SetNoStore() 等標頭 | 桌面瀏覽器有效 | 行動裝置 (iPad/Android) 常失效 |
| 2. JS 強制前進 | window.history.forward(1) | 簡單 | 同方案 1,行動裝置無效 |
| 3. location.replace | Response.Write("<script>location.replace('login.aspx')</script>") | 不留歷史紀錄 | 若為表單提交仍可返回 |
| 4. AJAX 登出 + location.replace (推薦) | 非同步清除 Session,成功後 replace 導向 | 跨平台穩定、不重整頁面、歷史紀錄乾淨 | 需前端配合 JS |
function logout(isLogout) {
if (!isLogout) return "Error";
$.ajax({
url: "Ajax/logout.aspx",
data: { code: encodeURI(isLogout) },
cache: false,
dataType: "html",
success: LogoutReturn
});
}
function LogoutReturn(context) {
if (context === "success") {
location.replace('login.aspx'); // 不留歷史
}
}
protected void Page_Load(object sender, EventArgs e)
{
Session.Clear();
Session.Abandon();
Response.Cache.SetNoStore();
Response.Write("success");
Response.End();
}
location.replace:以新 URL 取代目前歷史記錄項目,使用者無法按「返回」回到已登出頁面。cache: false:防止 AJAX 被快取導致登出失效。Page_Init 檢查 Session["User"] == null 則 Response.Redirect("login.aspx"),雙重保險。