Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 SimpleMembership - Why WebSecurity.CurrentUserId -1 after login

I am trying to set a cookie upon login and having issues with getting the current user id after login. In the below, intUserId is -1 and WebSecurity.IsAuthenticated is false. Is this not the correct place to put this code? After this, it redirects to the home page...so not sure why this is not the correct place.

// POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                //TODO: set current company and facility based on those this user has access to
                int intUserId = WebSecurity.GetUserId(User.Identity.Name);
                int intUserId2 = WebSecurity.GetUserId(model.UserName);
                UserSessionPreferences.CurrentCompanyId = 1;
                UserSessionPreferences.CurrentFacilityId = 1;

                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);
        }
like image 860
crichavin Avatar asked Dec 13 '12 00:12

crichavin


1 Answers

Login only sets the Forms Authentication cookie.

The way asp.net authentication works is that it must read the cookie to set the authenticate the request, but since the cookie did not exist when the Login page was started, the framework doesn't know anything about the user.

Reload the page, and you will find the information is available.

FYI, this is nothing new with SimpleMembership or WebSecurity, this is the way Forms Authentication has always worked.

like image 77
Erik Funkenbusch Avatar answered Nov 16 '22 01:11

Erik Funkenbusch