簡體   English   中英

System.Web.HttpContext.Current.User.Identity.IsAuthenticated有時會失敗

[英]System.Web.HttpContext.Current.User.Identity.IsAuthenticated fails sometimes

我的生產站點(而不是開發站點)遇到了麻煩。 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中也返回f,還會提示您重定向到首頁。 幾個小時后,它會自行修復。 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>

如果使用MembershipProvider ,則無需自己創建表單身份驗證 cookie。

我回答了您的一個問題 ,但在閱讀此內容后,請忽略該回答,因為您正在使用會自動為您創建IPrincipal對象的Membership Provider

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

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

注意: memberName和roleManager的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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM