“记住我”功能不起作用

时间:2018-02-19 11:26:05

标签: html .net

我想创建一个记住我(复选框)功能的登录页面。我试过了 几乎所有的代码都可以在互联网上找到,但没有任何工作正常。我想用asp.net(网络表格)编码。

HTML

<form id="form1" runat="server">
    UserName:
    <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
    Password:
    <asp:TextBox ID="txtPassword" TextMode="Password" runat="server"></asp:TextBox><br />
    Remember me:
    <asp:CheckBox ID="chkRemember" runat="server" /><br />
    <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="Login_Click" />
</form>

WEB CONFIG

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" />
        <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" />
    </system.web>
</configuration>

.aspx.cs代码

protected void Login_Click(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)
        {
            txtUserName.Text = Request.Cookies["UserName"].Value;
            txtPassword.Attributes["value"] = Request.Cookies["Password"].Value;
        }
    }
    if (chkRemember.Checked)
    {
        Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30);
        Response.Cookies["Password"].Expires = DateTime.Now.AddDays(30);
    }
    else
    {
        Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
        Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);

    }
    Response.Cookies["UserName"].Value = txtUserName.Text.Trim();
    Response.Cookies["Password"].Value = txtPassword.Text.Trim();
}

1 个答案:

答案 0 :(得分:0)

我不是ASP点网人!不过,我会说你使用的逻辑是错误的(我的假设)。

首先考虑一下“Remeber me”复选框应该做什么。如果用户过去每天登录到您的Web应用程序,那么他不想输入他的用户名和用户名。密码每日。这并不意味着你必须明确地尝试设置他的用户名和&amp;密码在各自的方框中。另外setting user's credential in a cookie is unethical. You should not store his credentials in a cookie which can be accessed easily in client side.

而不是执行该逻辑(if(chkRemember.Checked))尝试增加会话cookie到期日期,如下所示。因此,当用户试图进入网站(比如something.com)时,它会直接将他转发到主页。

if (chkRemember.Checked)
{
    Response.Cookies["sessionCookie"].Expires = DateTime.Now.AddDays(30);
}
else
{
    Response.Cookies["sessionCookie"].Expires = DateTime.Now.AddDays(-1);

}

我想,if (!IsPostBack)部分不是必需的。而不是在你的logout页面写一个逻辑来将sessionCookie到期时间设置为-1天!!

此外,你可以有条件(如上所述30天),

if(expiry of sessionCookie is more than 30 days) {
Print "You need to login again. System won't allow you to be logged in for more than 30 days"
}