2011-03-30 43 views
14

我正在使用MySQL Connector/.NET,它的所有提供者都使用FormsAuthentication。如何強制登出網站的所有用戶?

我需要所有用戶在某個時刻註銷。方法FormsAuthentication.SignOut()不能像我想要的那樣工作。

如何註銷所有網站用戶?

+1

是你在嘗試將應用程序離線?然後看看使用'app_offline.htm'文件。 http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx – rcravens 2011-03-30 15:38:50

+1

我不確定是否有一個簡單的一行代碼來完成此操作,但如果在特定日期之前忽略所有會話cookie並將該日期存儲在數據庫中? – Joe 2011-03-30 15:39:29

+0

@rcravens:不,我只想重置所有用戶的身份驗證。 – 2011-03-30 15:41:19

回答

14

正如Joe所建議的那樣,您可以編寫一個HttpModule來使給定DateTime之前存在的任何Cookie無效。如果你把它放在配置文件中,你可以在必要時添加/刪除它。例如,

Web.config文件:

<appSettings> 
    <add key="forcedLogout" value="30-Mar-2011 5:00 pm" /> 
</appSettings> 

<httpModules> 
    <add name="LogoutModule" type="MyAssembly.Security.LogoutModule, MyAssembly"/> 
</httpModules> 

的HttpModule在MyAssembly.dll程序:

public class LogoutModule: IHttpModule 
{ 
    #region IHttpModule Members 
    void IHttpModule.Dispose() { } 
    void IHttpModule.Init(HttpApplication context) 
    { 
     context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest); 
    } 
    #endregion 


    /// <summary> 
    /// Handle the authentication request and force logouts according to web.config 
    /// </summary> 
    /// <remarks>See "How To Implement IPrincipal" in MSDN</remarks> 
    private void context_AuthenticateRequest(object sender, EventArgs e) 
    { 
     HttpApplication a = (HttpApplication)sender; 
     HttpContext context = a.Context; 

     // Extract the forms authentication cookie 
     string cookieName = FormsAuthentication.FormsCookieName; 
     HttpCookie authCookie = context.Request.Cookies[cookieName]; 
     DateTime? logoutTime = ConfigurationManager.AppSettings["forcedLogout"] as DateTime?; 
     if (authCookie != null && logoutTime != null && authCookie.Expires < logoutTime.Value) 
     { 
      // Delete the auth cookie and let them start over. 
      authCookie.Expires = DateTime.Now.AddDays(-1); 
      context.Response.Cookies.Add(authCookie); 
      context.Response.Redirect(FormsAuthentication.LoginUrl); 
      context.Response.End(); 
     } 
    } 
} 
+2

請記住,對web.config的更改會導致應用程序重新啓動,您應該將其他地方的forcedLogout。可能提供一個網站管理頁面來設置這個。 – ScottTx 2011-03-30 21:14:13

+0

同意。這是一個很方便的例子。當然還有更好的選擇:用admin UI在數據庫中存儲forcedLogout;使用時間窗口(forcedLogoutStart,forcedLogoutEnd)來避免多個web.config版本;在app_data中放置一個文本文件... – Brett 2011-03-31 01:42:12

+1

爲什麼authCookie.Expires會小於logoutTime值?因爲我的網站登錄可能在未來30天有效,在這種情況下如何處理這種情況? – Mou 2016-04-07 19:09:01

相關問題