1

I have been having trouble with my production site (not my development sites). Every now and then both Firefox and Chrome fail to log users in (all users both on our client network and general web). But the strange part is that Internet Explorer always works correctly and has NEVER failed once (I have delete cache and cookies in browsers but still the same thing happens).

Then after an hour or X amount of time, Firefox and Chrome start behaving normally again.

I have a narrowed it down to function below that always returns false even after login.

public bool isLoggedIn()
{
    return System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
}

So the process goes below with the user going to login with this function:

public void Login_OnClick(object sender, EventArgs args)
{
    string email = UserName.Text;
    string password = Password.Text;
    string errorMsg = string.Empty;
    bool cb = cb_agreeterms.Checked;

if (tests)
    {
        // The code in here tests to see if email, password, etc. have been filled out.
        //  This works 100% of the time and is NOT a problem.
    }
    else
    {
        // Validate user.
        if (Membership.ValidateUser(email, password))
        {
            // Get the logged in user
            MembershipUser user = Membership.GetUser(email);

            if (user.IsLockedOut)
            {
                user.UnlockUser();
            }

    // Gets a datatable of the user details in our general database
            DataTable dtUserData = this.dbData.GetUserByEmail(user.UserName);

            if (dtUserData.Rows.Count > 0)
            {
                FormsAuthentication.SetAuthCookie(user.UserName, true);

                // The details for the userId, screenName, etc. below get set by looking at the row 0 in datatable

        // The LoginSession function intializes a session with a guid and saves all the data into an Application Context. This creates a SessionGuid cookie which I see get created on FF and Chrome (and always on IE).
                LoginSession(userId, screenName, permissionLevel, user.UserName);

                Response.Redirect("../myinternalsite.aspx");
            }
        }
        else if (UserExistsInMembership(email))
        { 
            // Tested this out and entering bad credentials fails the login and error is shown correctly on screen in the login control.

            // We have failed to login.
            ShowLoginError("E-mail or password is incorrect.");
        }
    }
}

So when the user authenticates, the redirect goes to ../myinternalsite.aspx. On the page in Page Load a VerifyLogin function gets called and calls:

public bool isLoggedIn()

The above ALWAYS returns falso in Chrome and FF which prompts a redirect to the home page. After a couple hours this fixes itself. IE works 100% of the time.

The web.config is this:

// authenticationConnection works and links correctly to the auth database just fine.
<sessionState timeout="120"/>

<membership defaultProvider="SqlProvider">

    <providers>

        <add connectionStringName="authenticationConnection" applicationName="Auth" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" requiresQuestionAndAnswer="false" passwordFormat="Hashed" enablePasswordReset="true" maxInvalidPasswordAttempts="1000" passwordAttemptWindow="1" />

    </providers>

</membership>

<roleManager enabled="true" defaultProvider="SqlRoleManager">

    <providers>

        <add name="SqlRoleManager" type="System.Web.Security.SqlRoleProvider" connectionStringName="authenticationConnection" applicationName="MyApp"/>

    </providers>

</roleManager>

<identity impersonate="true"/>

The cookies in Chrome and Firefox get set. I deleted them and saw them get reset correctly. But what is this issue? Why is IsAuthenticated failing for only some browsers and working for others and then fixes itself?

My login template with all my different steps is something like this too:

<asp:UpdatePanel ID="updateTheLogin" runat="server">
    <ContentTemplate>
         <asp:TextBox ID="UserName" runat="server" CssClass="loginTextbox"></asp:TextBox>
         <asp:TextBox id="Password" runat="server" textMode="Password" CssClass="loginTextbox"></asp:TextBox>
         <input type="button" class="btn-small pull-right disabled" id="LoginButton" value="Log In" onserverclick="Login_Click" runat="server" />
    </ContentTemplate>
</asp:UpdatePanel>
cdub
  • 24,555
  • 57
  • 174
  • 303
  • And pingdom reported no downtime for the site and also was able to run a transaction check to login every 10 min successfully – cdub Jan 12 '16 at 20:33
  • write your own IsAuthenticated Session variable instead of depending on IIS – techspider Jan 12 '16 at 20:36
  • how and why would that be the case? – cdub Jan 12 '16 at 20:38
  • I'm not providing the fix but an alternative that I always use; I have had enough issues with User.Identity and Context, so I always started writing my own variables to capture authentication status instead of tumbling around to fix the issue; Because it is customized session variable and is updated by developer during login, it will work irrespective of browser type/version; – techspider Jan 12 '16 at 20:42

1 Answers1

1

If you use MembershipProvider, you do not need to create Form Authentication cookie by yourself.

I answered one of your question, but after reading this, ignore that answer since you are using Membership Provider which will automatically create IPrincipal object for you.

All you have to do is to use ASP.Net Login control.

<asp:Login ID="Login" runat="server"></asp:Login>

Note: applicationName should be same for both membership and roleManager. They are different in your web.config.

How to View Authenticated User's Information

protected void Page_Load(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        var sb = new StringBuilder();
        var id = (FormsIdentity) User.Identity;
        var ticket = id.Ticket;
        sb.Append("Authenticated");
        sb.Append("<br/>CookiePath: " + ticket.CookiePath);
        sb.Append("<br/>Expiration: " + ticket.Expiration);
        sb.Append("<br/>Expired: " + ticket.Expired);
        sb.Append("<br/>IsPersistent: " + ticket.IsPersistent);
        sb.Append("<br/>IssueDate: " + ticket.IssueDate);
        sb.Append("<br/>Name: " + ticket.Name);
        sb.Append("<br/>UserData: " + ticket.UserData);
        sb.Append("<br/>Version: " + ticket.Version);
        Label1.Text = sb.ToString();
    }
    else
        Label1.Text = "Not Authenticated";
}
Community
  • 1
  • 1
Win
  • 61,100
  • 13
  • 102
  • 181
  • how do you tell you are logged in? – cdub Jan 13 '16 at 01:13
  • if I remove all the FormsAuth stuff in code and web.config, will this still work properly: – cdub Jan 13 '16 at 01:18
  • this: return System.Web.HttpContext.Current.User.Identity.IsAuthenticated; – cdub Jan 13 '16 at 01:18
  • I added the code. You still need **authentication** tag, **membership** tag and **roleManager** tag inside web.config in order for **MembershipProvider** to work. – Win Jan 13 '16 at 01:24
  • i'm looking up what to add to the authentication tag now – cdub Jan 13 '16 at 01:31
  • also any idea why it worked most times and only failed in certain browsers? – cdub Jan 13 '16 at 01:33
  • `` Default authentication should be fine unless you want to tweak. I cannot say exactly what went wrong in your case. However, if you hand-roll Authentication by yourself, a lot of things can go wrong easily. – Win Jan 13 '16 at 01:41
  • oh so you still need authentication mode="Forms">? and I updated my post to show my login template and hope that is still okay to use – cdub Jan 13 '16 at 01:48
  • You need `` for **Membership Provider** which uses **Form Authentication**. – Win Jan 13 '16 at 01:55
  • cool thanks. i really hope this works and my login template is correct too. i got my fingers crossed! :) thx for your help – cdub Jan 13 '16 at 02:44
  • so weird, the User.Identity.IsAuthenticated is always false – cdub Jan 13 '16 at 23:53
  • Where do you check it? – Win Jan 14 '16 at 13:54
  • I got it to to work by making FormsAuthentication.RedirectFromLoginPage(email, false); tho wonder if it shold be true – cdub Jan 14 '16 at 19:52