User.Identity.IsAuthenticated is always false on first click? [duplicate]
-
21-12-2019 - |
Question
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");
}
}
Solution 2
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)
OTHER TIPS
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.
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.