Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSecurity.CurrentUserName and User.Identity.Name are null after logging in

I'm stating to figure out SimpleMembership for my ASP.Net MVC 4 site. I've augmented UserProfile with a custom property, AccountTypeId. I've updated the database table with the augmented property and can save data to the database when registering. I'm a bit confused about how to retrieve data about the user once they have logged in.

In my Account controller, I have a Login action that gets posted to when a user logs in. Here's my code:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            var userName = WebSecurity.CurrentUserName;
            var identityName = User.Identity.Name;
            var currentuserid = WebSecurity.GetUserId(model.UserName);
            var context = new UsersContext();
            var user = context.UserProfiles.SingleOrDefault(u => u.UserId == currentuserid);
            var accountTypeId = user.AccountTypeId;

            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);
    }

WebSecurity.CurrentUserName and User.Identity.Name are both empty strings, however, I can retrieve the UserId using WebSecurity.GetUserId(model.UserName) and can therefore retrieve the user data and I can get accountTypeId.

What's strange is User.Identity.Name gets displayed on my page when it's being called from a .cshtml page after the user is redirected to the landing page. So, somewhere in between the Login action of my controller and the destination page, User.Identity is getting set with data.

I'm assuming since I'm past the WebSecurity.Login check, that WebSecurity would have information about the logged in user, but it doesn't seem to be that way.

What am I missing?

like image 530
Tom Schreck Avatar asked Sep 28 '12 22:09

Tom Schreck


1 Answers

The username is written to a cookie. In order for cookie data to be available, it must be placed into the Response and sent back to the browser. Upon the next request, the cookie value will be read and used to populate the User.Identity.Name property.

In other words, the User.Identity.Name property should be an empty string until after your Redirect call. This is the purpose of redirecting after signing on: to write the cookie to the browser so that subsequent requests will treat the user as signed on.

like image 189
danludwig Avatar answered Sep 28 '22 07:09

danludwig