首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 登錄權限驗證:Session與Cookie結合實現「記住我」及BasePage攔截器模式

     編輯:關於ASP.NET

核心業務流程

登錄成功 → 實體存入 Session → 勾選「記住我」則將 UserId 寫入 Cookie(有效期 3 天) → 後續訪問:Session 為空時讀取 Cookie → 查詢用戶實體 → 回寫 Session → 實現免登錄。

前台登錄核心代碼

BlogUserBLL bll = new BlogUserBLL();
// 1. 驗證用戶名密碼(密碼已 MD5)
List<BlogUser> list = bll.GetModelList("LoginName='" + name + "' and LoginPwd='" + md5Pwd + "'");
if (list.Count > 0) {
    // 2. 存入 Session
    Context.Session["uInfo"] = list[0];
    // 3. 記住登錄 → 寫 Cookie
    if (!string.IsNullOrWhiteSpace(remember)) {
        HttpCookie cookie = new HttpCookie("uid", list[0].Id.ToString());
        cookie.Expires = DateTime.Now.AddDays(3);
        Context.Response.Cookies.Add(cookie);
    }
    Response.Write("<script>alert('登錄成功');window.location='BlogList.aspx'</script>");
} else {
    Response.Write("<script>alert('登錄失敗');window.location='/Login.aspx'</script>");
}
Response.End();

BasePage 攔截器:OnInit 管道事件攔截

所有需登錄頁面繼承 BasePage,重寫 OnInit 實現統一攔截:

protected override void OnInit(EventArgs e) {
    if (Session["uInfo"] == null) {
        // 嘗試從 Cookie 恢復
        if (Request.Cookies["uid"] != null) {
            BlogUserBLL bll = new BlogUserBLL();
            BlogUser umodel = bll.GetModel(int.Parse(Request.Cookies["uid"].Value));
            Session["uInfo"] = umodel;
            return;
        }
        // 完全未登錄 → 跳轉登錄頁
        Response.Redirect("/Login.aspx");
    }
    base.OnInit(e);
}

關鍵點:OnInit 是頁面生命周期早期事件,在此攔截可避免後續邏輯執行;BasePage 僅適用 .aspx 頁面,.ashx 需單獨實現 BaseHandler。

安全性補充建議

  • Cookie 值應加密/簽名,防止篡改 UserId 竊取賬號
  • 密碼存儲應使用 BCrypt/Argon2 而非單純 MD5
  • Session 存儲建議使用 Redis 等分布式方案支撐集群
  • 攔截器模式現代替代方案:ASP.NET Core Middleware / Filter Pipeline
  1. 上一篇文章: No
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved