萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 防惡意刷新:Session 與 Cookie 兩種實作模式完整代碼

前言

防止使用者短時間內瘋狂刷新頁面(F5 攻擊、CC 攻擊雛形),可在伺服器端以 Session 或 Cookie 記錄上次請求時間,若間隔小於閾值則攔截並提示等待。本文提供兩種完整可用的實作模式。

模式一:Session 版(伺服器端狀態,較安全)

public partial class BasePage : System.Web.UI.Page
{
    private const int FreezeSeconds = 1; // 冷卻秒數
    
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        AntiRefreshCheck();
    }

    private void AntiRefreshCheck()
    {
        // Session 未就緒
        if (Session.SessionID == null) { Response.End(); return; }

        // 初始化 Session 標識
        if (Session["AntiRefresh_SessionId"] == null)
            Session["AntiRefresh_SessionId"] = Session.SessionID;

        // 不同 SessionID 視為新使用者,重置
        if (!Session.SessionID.Equals(Session["AntiRefresh_SessionId"]))
        {
            Session["AntiRefresh_LastTime"] = DateTime.Now;
            Session["AntiRefresh_SessionId"] = Session.SessionID;
            return;
        }

        // 檢查間隔
        if (Session["AntiRefresh_LastTime"] != null)
        {
            var last = (DateTime)Session["AntiRefresh_LastTime"];
            var elapsed = (DateTime.Now - last).TotalMilliseconds;
            
            if (elapsed < FreezeSeconds * 1000)
            {
                ShowWarnAndEnd(FreezeSeconds);
                return;
            }
        }

        // 更新時間
        Session["AntiRefresh_LastTime"] = DateTime.Now;
    }

    private void ShowWarnAndEnd(int seconds)
    {
        Response.Write($@"<table width='778' border='0' align='center' cellpadding='3' cellspacing='2' bgcolor='#009900' style='font-size:14px;'>
            <tr bgcolor='#FFFFFF'>
                <td><img src='/images/logo.gif' /></td>
                <td bgcolor='#EEFFEE'>為確保訪問安全,請 {seconds} 秒後 <a href='{Request.RawUrl}' style='color:red;'>點擊重新整理</a></td>
            </tr></table>");
        Response.End();
    }
}

模式二:Cookie 版(客戶端狀態,無 Session 依賴)

public partial class BasePage : System.Web.UI.Page
{
    private const int FreezeSeconds = 2;
    
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        AntiRefreshCookieCheck();
    }

    private void AntiRefreshCookieCheck()
    {
        var currentUrl = Request.Url.PathAndQuery;
        var pageCookie = Request.Cookies["AntiRefresh_Page"];
        var timeCookie = Request.Cookies["AntiRefresh_Time"];

        bool isRefresh = pageCookie != null && pageCookie.Value == currentUrl;

        if (isRefresh && timeCookie != null && DateTime.TryParse(timeCookie.Value, out var lastTime))
        {
            var elapsed = (DateTime.Now - lastTime).TotalSeconds;
            if (elapsed < FreezeSeconds)
            {
                ShowWarnCookie(FreezeSeconds, currentUrl);
                return;
            }
        }

        // 更新/建立 Cookie
        var cPage = new HttpCookie("AntiRefresh_Page", currentUrl) { HttpOnly = true };
        var cTime = new HttpCookie("AntiRefresh_Time", DateTime.Now.ToString("o")) { HttpOnly = true };
        Response.Cookies.Set(cPage);
        Response.Cookies.Set(cTime);
    }

    private void ShowWarnCookie(int seconds, string url)
    {
        Response.Write($@"<table width='778' border='0' align='center' cellpadding='3' cellspacing='2' bgcolor='#009900' style='font-size:14px;'>
            <tr bgcolor='#FFFFFF'>
                <td><img src='/images/logo.gif' /></td>
                <td bgcolor='#EEFFEE'>頁面將在 {seconds} 秒後自動跳轉...</td>
            </tr></table>
            <meta http-equiv='refresh' content='{seconds};url={HttpUtility.UrlEncode(url)}'>");
        Response.End();
    }
}

兩種模式比較

維度Session 版Cookie 版
儲存位置伺服器記憶體/State Server/SQL客戶端瀏覽器
安全性高(使用者無法竄改)中(可被刪除/封鎖)
跨分頁影響同 Session 共享冷卻同域名共享冷卻
適用場景登入後系統、需嚴格控制公開頁面、無 Session 環境
叢集部署需 Session 共享天然支援

進階強化建議

  • IP + URL 組合鍵:避免單一使用者影響他人(Cookie 版天然隔離,Session 版需自行實作)。
  • 滑動視窗演算法:記錄最近 N 次請求時間戳,判斷頻率而非單純間隔。
  • 整合 ASP.NET Core 中介軟體:全域攔截,不侵入業務頁面。
  • 回傳 429 Too Many Requests:配合前端友善提示,而非直接 Response.End()。

結語

Session 版適合登入後的後台系統,安全性高;Cookie 版適合公開頁面、無狀態服務。實務上建議結合 IP 限流、驗證碼、WAF 多層防護,單靠頁面級冷卻只能擋住最基礎的惡意刷新。

copyright © 萬盛學電腦網 all rights reserved