Asp.net

會話在 asp.net 網站上混在一起

  • June 27, 2011

我正在分析一個由幾個月前離開公司的同事創建的舊 asp.net 站點的問題。

問題是我們有幾次經歷過兩個使用者會話混合在一起,例如,如果兩個使用者登錄,一個使用者會看到其他使用者的數據。由於這種情況很少發生(大約一個月一次),因此很難弄清楚哪裡出了問題。

我現在已經通過他的程式碼進行身份驗證,它是這樣的:

  1. 使用者在公共頁面上輸入使用者名/密碼並按送出
  2. Page_LoadMasterpage 上,程式碼在 mySql 數據庫中檢查使用者名/密碼是否有效、未過期等,如果正常則返回唯一的使用者 ID
  3. 然後該頁面將登錄頁面保存在會話中,如下所示(用於以後註銷): HttpContext.Current.Session(Consts.CCookieName_LoginUrl) = Request.RawUrl
  4. 然後使用者標識是這樣保存的:FormsAuthentication.SetAuthCookie(userid, False)
  5. 然後執行到安全區域的重定向:Context.Response.Redirect(secureurl, False)
  6. Page_Init安全區域的母版頁中,使用者 ID 由以下方式讀取:userid = Context.User.Identity.Name
  7. 根據使用者ID載入使用者數據
  8. 使用者導航安全區域,即。重複步驟 6 - 7
  9. 使用者突然看到另一個使用者數據

我對出了什麼問題有一些想法,但想在修改程式碼之前有一些輸入,所以請任何人?

這裡很難說。您是否配置了表單身份驗證?

這是表單身份驗證必須遵循的過程:在 web.config 中設置身份驗證系統:

<authentication mode="Forms">
   <forms loginUrl="Login.aspx" defaultUrl="Home.aspx" timeout="30" slidingExpiration="true" />
</authentication>

<authorization>
 <deny users="?"/>
</authorization>

您的登錄頁面(回發)檢查憑據(不是您的母版頁)。如果使用者有效,那麼您設置 cookie:

FormsAuthentication.SetAuthCookie(userid, False)

並重定向到另一個頁面。現在,您必須在此處設置您的主體讀取 cookie:

protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
   if (HttpContext.Current.User != null) {
       if (Request.IsAuthenticated == true) {    
           // Debug#1            
           FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
           // In this case, ticket.UserData = "Admin"                
           string[] roles = new string[1] { ticket.UserData }; 
           FormsIdentity id = new FormsIdentity(ticket);
           Context.User = new System.Security.Principal.GenericPrincipal(id, roles);
           // Debug#2
       }
   }
}

顯然,我已經簡化了,但這是你必須遵循的正確做事的路徑。

引用自:https://stackoverflow.com/questions/6200172