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

1

8

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?

Gatewood answered 28/9, 2012 at 22:1 Comment(0)
N
9

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.

Nagey answered 29/9, 2012 at 15:17 Comment(1)
I made a kind of 'wrapper' to this so that when I'd set the cookie it would return the expected valueCurlew

© 2022 - 2024 — McMap. All rights reserved.