System.Web.HttpContext.Current.User.Identity.IsAuthenticated有时会失败

时间:2016-01-12 20:32:47

标签: c# asp.net authentication cookies forms-authentication

我的生产网站(不是我的开发网站)遇到了问题。有时Firefox和Chrome都无法登录用户(所有用户都在我们的客户网络和一般网络上)。但奇怪的是,Internet Explorer始终可以正常运行并且一次都没有失败(我在浏览器中删除了缓存和cookie,但仍然会发生同样的事情)。

然后,经过一小时或一段时间后,Firefox和Chrome会再次开始正常运行。

我将其缩小到以下功能,即使在登录后也始终返回false。

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

因此,用户将使用此功能登录以下过程:

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.");
        }
    }
}

因此,当用户进行身份验证时,重定向将转至../myinternalsite.aspx。在页面加载页面上调用VerifyLogin函数并调用:

public bool isLoggedIn()

以上ALWAYS在Chrome和FF中返回falso,提示重定向到主页。几个小时后,这个问题就解决了。 IE 100%的工作时间。

web.config是这样的:

// 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"/>

Chrome和Firefox中的Cookie设置完毕。我删除了它们,看到它们被正确重置。但是这个问题是什么?为什么IsAuthenticated仅针对某些浏览器失败并为其他浏览器工作然后自行修复?

我的所有不同步骤的登录模板也是这样的:

<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>

1 个答案:

答案 0 :(得分:1)

如果您使用 MembershipProvider ,则无需自行创建表单身份验证 Cookie。

我回答one of your question,但在阅读完之后,请忽略该答案,因为您使用会员提供商,这将自动为您创建 IPrincipal 对象。

您所要做的就是使用ASP.Net Login控件。

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

注意: applicationName 对于成员资格和角色管理器都应该相同。它们在 web.config 中有所不同。

如何查看经过身份验证的用户信息

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";
}