System.Web.HttpContext.Current.User.Identity.IsAuthenticated有时会失败 [英] System.Web.HttpContext.Current.User.Identity.IsAuthenticated fails sometimes

查看:934
本文介绍了System.Web.HttpContext.Current.User.Identity.IsAuthenticated有时会失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经与我的生产现场(不是我的开发用地)的麻烦。时不时地,Firefox和Chrome都无法登录的用户(所有用户我们的客户网络和一般的网页上都)。但奇怪的是,Internet Explorer始终正常工作,从来没有一次失败(我有删除浏览器缓存和Cookie,但仍是同样的事情发生)。

随后的一个小时的时间或X量之后,Firefox和Chrome开始再次正常行为。

我有一种缩小它向下跌破这一始终即使登录后返回false工作。

 公共BOOL isLoggedIn()
{
    返回System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
}

所以,过程中与用户打算使用此功能,在下面登录云:

 公共无效Login_OnClick(对象发件人,EventArgs参数)
{
    字符串email = UserName.Text;
    字符串密码= Password.Text;
    字符串ERRORMSG =的String.Empty;
    布尔CB = cb_agreeterms.Checked;如果(测试)
    {
        //这里的code测试,看是否电子邮件,密码等都已填写。
        //这个工程的100%的时间,是没有问题的。
    }
    其他
    {
        //验证用户。
        如果(Membership.ValidateUser(电子邮件,密码))
        {
            //获取登录的用户
            的MembershipUser用户= Membership.GetUser(电子邮件);            如果(user.IsLockedOut)
            {
                user.UnlockUser();
            }    //获取用户信息的数据表中我们一般的数据库
            数据表dtUserData = this.dbData.GetUserByEmail(user.UserName);            如果(dtUserData.Rows.Count大于0)
            {
                FormsAuthentication.SetAuthCookie(user.UserName,真);                //用户id,屏幕名等。下得到由DataTable中寻找在行0中设置的细节        //该LoginSession功能intializes一个GUID的会议上,所有的数据保存到一个应用程序上下文。这将创建一个SessionGuid饼干,我看到坐上FF和Chrome(总是在IE浏览器)创建的。
                LoginSession(用户ID,屏幕名,permissionLevel,user.UserName);                的Response.Redirect(../ myinternalsite.aspx);
            }
        }
        否则如果(UserExistsInMembership(电子邮件))
        {
            //测试了这一点,并输入凭据不好失败的登录名和显示正确地在屏幕上的登录控制误差。            //我们已经无法登录。
            ShowLoginError(E-​​mail或密码不正确。);
        }
    }
}

因此​​,当用户进行身份验证,重定向去../myinternalsite.aspx。在页面的页面加载VerifyLogin函数被调用,并呼吁:

 公共BOOL isLoggedIn()

上面总是返回FALSO在Chrome和FF它会提示重定向到主页。几个小时后,这个自我修复。 IE工程的100%的时间。

在web.config是这样的:

  // authenticationConnection工作,正确链接到数据库AUTH就好。
<的sessionState超时=120/><会员defaultProvider =sqlProvider的>    <供应商>        <添加的connectionStringName =authenticationConnection的applicationName =验证minRequiredPasswordLength =6minRequiredNonalphanumericCharacters =0NA​​ME =sqlProvider的TYPE =System.Web.Security.SqlMembershipProviderrequiresQuestionAndAnswer =假了passwordFormat =散列enablePasswordReset设置=真maxInvalidPasswordAttempts =1000passwordAttemptWindow =1/>    < /供应商>< /会员>< roleManager启用=真正的defaultProvider =SqlRoleManager>    <供应商>        <添加名称=SqlRoleManagerTYPE =System.Web.Security.SqlRoleProvider的connectionStringName =authenticationConnection的applicationName =MyApp的/>    < /供应商>< / roleManager><身份冒充=真/>

在Chrome和Firefox的饼干被置1。我删除它们,看到它们被正确复位。但是,这是什么问题?为什么IsAuthenticated失败的只有一些浏览器和给别人打工,然后自我修复?

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

 < ASP:的UpdatePanel ID =updateTheLogin=服务器>
    <&的ContentTemplate GT;
         < ASP:文本框ID =用户名=服务器的CssClass =loginTextbox>< / ASP:文本框>
         < ASP:文本框的id =密码=服务器文本模式=密码的CssClass =loginTextbox>< / ASP:文本框>
         <输入类型=按钮级=BTN-小右拉式禁用ID =LoginButtonVALUE =登录onserverclick =Login_Click=服务器/>
    < /&的ContentTemplate GT;
< / ASP:的UpdatePanel>


解决方案

如果您使用的MembershipProvider ,你不需要自己创建的窗体身份验证的cookie。

我回答<一个href=\"http://stackoverflow.com/questions/34755093/formsauthentication-setauthcookieuser-username-true-cookie-name\">one你的问题,但看完这个,忽略这个问题的答案,因为你正在使用会员提供将自动创建的IPrincipal 作为您的对象。

所有你所要做的就是使用ASP.Net的登录控制。

 &LT; ASP:登录ID =登录=服务器&GT;&LT; / ASP:登录&GT;

注: 的applicationName 应该是相同的两个成员和roleManager。他们是不同的在的web.config

如何查看认证用户的信息

 保护无效的Page_Load(对象发件人,EventArgs的发送)
{
    如果(User.Identity.IsAuthenticated)
    {
        VAR SB =新的StringBuilder();
        VAR ID =(FormsIdentity)User.Identity;
        VAR票= id.Ticket;
        sb.Append(认证);
        sb.Append(&LT; BR /&GT; CookiePath:+ ticket.CookiePath);
        sb.Append(&LT; BR /&GT;保质期:+ ticket.Expiration);
        sb.Append(&LT; BR /&GT;过期:+ ticket.Expired);
        sb.Append(&LT; BR /&GT; IsPersistent:+ ticket.IsPersistent);
        sb.Append(&LT; BR /&GT; IssueDate:+ ticket.IssueDate);
        sb.Append(&LT; BR /&GT;名称:+ ticket.Name);
        sb.Append(&LT; BR /&GT;的UserData:+ ticket.UserData);
        sb.Append(&LT; BR /&GT;版本:+ ticket.Version);
        Label1.Text = sb.ToString();
    }
    其他
        Label1.Text =未经过身份验证;
}

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>

解决方案

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

这篇关于System.Web.HttpContext.Current.User.Identity.IsAuthenticated有时会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆