以编程方式注销ASP.NET用户

时间:2010-06-23 03:19:03

标签: c# asp.net login

我的应用允许管理员暂停/取消暂停用户帐户。我使用以下代码执行此操作:

MembershipUser user = Membership.GetUser(Guid.Parse(userId));
user.IsApproved = false;
Membership.UpdateUser(user);

上述工作正常可以暂停用户,但不会撤销他们的会话。因此,只要其会话cookie仍然存在,被挂起的用户就可以继续访问该应用程序。任何修复/

4 个答案:

答案 0 :(得分:27)

无法从会话“外部”放弃会话。您必须在每个页面加载时检查数据库,如果该帐户已被禁用,则注销。你也可以使用HttpModule实现这一点,这会让事情变得更清晰。

例如:

public class UserCheckModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.PreRequestHandlerExecute += new EventHandler(OnPreRequestHandlerExecute);
    }

    public void Dispose() {}

    private void OnPreRequestHandlerExecute(object sender, EventArgs e)
    {
        // Get the user (though the method below is probably incorrect)
        // The basic idea is to get the user record using a user key
        // stored in the session (such as the user id).
        MembershipUser user = Membership.GetUser(Guid.Parse(HttpContext.Current.Session["guid"]));

        // Ensure user is valid
        if (!user.IsApproved)
        {
            HttpContext.Current.Session.Abandon();
            FormsAuthentication.SignOut();
            HttpContext.Current.Response.Redirect("~/Login.aspx?AccountDisabled");
        }
    }
}

这不是一个完整的示例,并且需要调整使用存储在会话中的密钥来检索用户的方法,但这应该可以帮助您入门。它将涉及对每个页面加载进行额外的数据库检查,以检查用户帐户是否仍处于活动状态,但没有其他方法可以检查此信息。

答案 1 :(得分:6)

如果使用表单身份验证:

FormsAuthentication.SignOut();

答案 2 :(得分:5)

当您注销用户时,最好覆盖FormsAuthenticationTicket

HttpContext context = HttpContext.Current;

//overwrite the authentication cookie
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, context.User.Identity.Name, DateTime.Now, DateTime.Now.AddDays(-1), false, Guid.NewGuid().ToString());
string encrypted_ticket = FormsAuthentication.Encrypt(ticket);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted_ticket);
cookie.Expires = ticket.Expiration;
context.Response.Cookies.Add(cookie);

//clear all the sessions
context.Session.Abandon();

//sign out and go to the login page
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();

答案 3 :(得分:2)

在某个常见页面上,检查该帐户是否有效,如果该帐户已被撤销,请致电Session.Abandon()

修改(刚刚注意到这仍然是开放的。)

我知道这很有效,因为我这样做了。

在母版页上,检查帐户状态。这意味着在每个导航上你都有机会将它们注销。

(最终)修改

不要将其视为“我正在终止他们的会话”,将其视为“他们的会话终止。”

相关问题