User.Identity.IsAuthenticated is false after successful login

user982119 picture user982119 · Jul 14, 2013 · Viewed 58.5k times · Source

I need to get the UserId Guid directly after a successful login. The following code doesn't work:

if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value))
{
    FormsAuthentication.SignOut();
    FormsAuthentication.SetAuthCookie(txtUsername.Value, true);

    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
        // doesn't run
        Guid puk = (Guid)Membership.GetUser().ProviderUserKey;            
    }
}

The following code does work:

if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value))
{
    FormsAuthentication.SignOut();
    FormsAuthentication.SetAuthCookie(txtUsername.Value, true);

    MembershipUser user = Membership.GetUser(txtUsername.Value);

    if (user != null)
    {
        Guid puk = (Guid)user.ProviderUserKey;
    }
}

Why does this happen? Is there something more to do besides SetAuthCookie?

Answer

cihancoskun picture cihancoskun · Jan 4, 2015

I had the same problem too. I forgot to set the web.config configuration.

Maybe you missed too.

   <system.web> 
    <authentication mode="Forms">
      <forms loginUrl="~/user/login" timeout="1000" name="__Auth" />
    </authentication>  
  </system.web>