如何强制注销网站的所有用户?

Jea*_*uis 15 c# mysql asp.net-mvc

我正在使用MySQL Connector/.NET,它的所有提供者都使用FormsAuthentication.

我需要所有用户在某个时刻注销.该方法FormsAuthentication.SignOut()不能像我想的那样工作.

如何注销所有网站用户?

Bre*_*ett 16

正如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>
Run Code Online (Sandbox Code Playgroud)

MyAssembly.dll中的HttpModule:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请记住,对web.config的更改将导致应用程序重新启动,您应该将forcedLogout放在其他位置.可能会提供一个站点管理页面来设置它. (2认同)