2

I have an asp.net webforms app that has a login screen. When I click the login button, the User.Identity.IsAuthenticated is always false on the first click. Here is the code for logging in:

protected void SignIn(object sender, EventArgs e)
    {
        var userStore = new UserStore<ApplicationUser>();
        var userManager = new UserManager<ApplicationUser>(userStore);
        var user = userManager.Find(UserName.Text, Password.Text);

        if (user != null && user.PasswordRetryCount < 3)
        {
            Session["UserName"] = user.UserName;

            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            authenticationManager.SignIn(new AuthenticationProperties {IsPersistent = false}, userIdentity);

            if (User.Identity.IsAuthenticated) //false on first click
                Response.Redirect("Default.aspx");
        }
    }
xaisoft
  • 2,805
  • 7
  • 33
  • 69

3 Answers3

3

You have logged in the user, but the event(s) and values that set the IsAuthenticated flag don't run until your next request. You are still in the context of the of the un-authenticated request.

What is the return value for authenticationManager.SignIn(..)? If it returns a bool or any other information that tells you if you authenticated successfully or not, you can use that as the flag for your if statement.

Babak Naffas
  • 11,532
  • 3
  • 32
  • 48
  • How can I get around this because what happens is that I enter the username and password, and then the password field clears out and I have to enter it again and then I go to a different part of the website. – xaisoft Feb 25 '14 at 18:17
  • Look at this similar question: http://stackoverflow.com/questions/17642630/user-identity-isauthenticated-is-false-after-successful-login – Babak Naffas Feb 25 '14 at 18:18
  • I saw that, but I can't see how it can help me avoid having the user enter their password twice. – xaisoft Feb 25 '14 at 18:20
  • 2
    `authenticationManager.SignIn(..)` return type is void. – xaisoft Feb 25 '14 at 18:22
1

Instead of doing:

if (User.Identity.IsAuthenticated) to check if the user is authenticatd, I did checked the following property of IdentityResult which seems to work fine:

if (userIdentity.IsAuthenticated)

xaisoft
  • 2,805
  • 7
  • 33
  • 69
0

The property User.Identity.IsAuthenticated will be filled based on cookies from HttpRequest in one of application authenticate event. So, in your case this property will have "false" value.

Anton Levshunov
  • 398
  • 1
  • 9