Search code examples
asp.netasp.net-mvc-4calllogoff

ASP.NET MVC4 LogOff doesnt work


first of all im a newbie in ASP.NET and so sorry if this question is stupid!

i have created a login system using session variables if the username/password match the database data ! The problem is that while im able to login i cant logout

 //
    // POST: /Account/LogOff

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        Session.RemoveAll();
        return RedirectToAction("Index", "Home");
    }

the above code is from the AccountController

@if (Session["LoggedUser"]!=null) {
<text>
    Hello, @Html.ActionLink(Session["Username"].ToString(), "Manage", "Account", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" })!
    @using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) {
        @Html.AntiForgeryToken()
        <a href="javascript:document.getElementById('logoutForm').submit()">LogOff</a>
    }
</text>} else {
<ul>
    <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
    <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>}

and the above is from the _partialLogin

My problem is that when i press logOff the site just skips the LogOff part of the controller and the session is not cleared, meaning that im still logged as a user thank you for your help

EDIT : here is the controller of the login page in case it is need :

  //
    // GET: /Account/Login

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            DefaultConnection dc = new DefaultConnection();
            var Users = (from c in dc.NonActivated_Users select c).ToList<NonActivated_Users>();
            foreach (NonActivated_Users nua in Users){
                if (nua.Password_Hash == Hasher.HashString(model.Password) && nua.Username==model.UserName){
                    Session["LoggedUser"] = nua;
                    Session["Rights"] = 4; //non activated user
                    Session["Username"] = 0;
                    nua.LastActive = DateTime.Now;
                    dc.SaveChanges();
                    return RedirectToLocal(returnUrl);
                }   
            }
            var Users1 = (from c in dc.User select c).ToList<User>();
            foreach (User au in Users1)
            {
                if (au.Password_Hash == Hasher.HashString(model.Password) && au.Username == model.UserName)
                {
                    Session["LoggedUser"] = au;
                    if (au.Membership == false) {
                        Session["Rights"] = 3; //activated user non premium
                    }
                    else
                    {
                        Session["Rights"] = 2; //activated user premium
                    }
                    au.Last_Active = DateTime.Now;
                    dc.SaveChanges();
                    return RedirectToLocal(returnUrl);
                }
            }
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

Solution

  • You are not setting FormsAuthentication cookie, and for that reason, you can't reach your LogOff action.

    You will need to decorate your LogOff action with [AllowAnonymous] attribute, or set authentication cookie upon successful login

    FormsAuthentication.SetAuthCookie(user.Username, false);
    

    EDIT:

    I would suggest you to check user authentication with User.Identity.IsAuthenticated rather than checking for a session existance. In addition to that, you can store your session variables to a single custom object, and then store that object to a single session. It will be easier to track your sessions in the later stage of the project :)