【问题标题】:System.Web.HttpContext.Current.User.Identity.IsAuthenticated fails sometimesSystem.Web.HttpContext.Current.User.Identity.IsAuthenticated 有时会失败
【发布时间】:2016-04-17 15:12:37
【问题描述】:

我的生产站点(不是我的开发站点)遇到了问题。 Firefox 和 Chrome 时不时地无法登录用户(我们的客户端网络和一般网络上的所有用户)。但奇怪的是,Internet Explorer 始终可以正常工作并且从未失败过(我已经删除了浏览器中的缓存和 cookie,但仍然发生同样的事情)。

然后在一小时或 X 时间后,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()

上述总是在 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>

【问题讨论】:

  • 并且 pingdom 报告该站点没有停机,并且能够运行事务检查以每 10 分钟成功登录一次
  • 编写自己的 IsAuthenticated Session 变量,而不是依赖 IIS
  • 为什么会这样?
  • 我没有提供修复,而是我一直使用的替代方案;我在 User.Identity 和 Context 方面遇到了很多问题,所以我总是开始编写自己的变量来捕获身份验证状态,而不是四处寻找解决问题;因为它是自定义的会话变量,并且在登录时由开发人员更新,所以无论浏览器类型/版本如何,它都可以工作;

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


【解决方案1】:

如果您使用MembershipProvider,则不需要自己创建Form Authentication cookie。

我回答了one of your question,但阅读此内容后,请忽略该回答,因为您使用的是Membership Provider,它会自动为您创建IPrincipal 对象。

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

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

注意: applicationName 对于membership 和roleManager 应该是相同的。它们在您的 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";
}

【讨论】:

  • 你怎么知道你已经登录了?
  • 如果我删除代码和 web.config 中的所有 FormsAuth 内容,这仍然可以正常工作:
  • 这个:返回 System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
  • 我添加了代码。您仍然需要 web.config 中的 authentication 标签、membership 标签和 roleManager 标签才能使 MembershipProvider 工作。
  • 我正在查找要添加到身份验证标签的内容
猜你喜欢
  • 2014-05-01
  • 2011-08-10
  • 2016-06-21
  • 2010-12-06
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
相关资源
最近更新 更多