Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleMembershipProvider doesn't destroy session after WebSecurity.SignOut

Tags:

asp.net-mvc

I am running ASP.NET MVC 4 with all the default membership code. The code for AccountController's LogOff is:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        WebSecurity.Logout();

        return RedirectToAction("Index", "Home");
    }

I noticed that this code does not destroy the session, meaning that if I sign in with one account, save something to the session, then logout and sign in with a different account in the same instance of the web browser, I can still see the session of the previous user.

Not sure why this is happening. Any advice would be greatly appreciated. Thanks.

like image 414
user1044169 Avatar asked Nov 25 '12 20:11

user1044169


2 Answers

Session and Authentification session is not the same thing.

Here you destroyed the authentication for the user, but you did restart the ASP.NET session.

More explanatition here : https://stackoverflow.com/a/1306932/971693

Try doing this :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    WebSecurity.Logout();

    Session.Abandon();

    // clear authentication cookie
    HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
    cookie1.Expires = DateTime.Now.AddYears(-1);
    Response.Cookies.Add(cookie1);

    // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
    HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
    cookie2.Expires = DateTime.Now.AddYears(-1);
    Response.Cookies.Add(cookie2);


    return RedirectToAction("Index", "Home");
}
like image 90
Yan Brunet Avatar answered Nov 15 '22 09:11

Yan Brunet


This is more 'the why' part of the answer.

Consider a shopping cart such as Amazon that has a 'This is not me' link next to the username at the top of the screen.

If you add something to your cart, but WebSecurity.Logout were to clear your session then you'd lose this session data.

like image 29
Simon_Weaver Avatar answered Nov 15 '22 08:11

Simon_Weaver